]> ToastFreeware Gitweb - toast/confclerk.git/blob - src/sql/sqlengine.cpp
Change parsing of start and end date so that 37C3 schedule works.
[toast/confclerk.git] / src / sql / sqlengine.cpp
1 /*
2  * Copyright (C) 2010 Ixonos Plc.
3  * Copyright (C) 2011-2021 Philipp Spitzer, gregor herrmann, Stefan Stahl
4  *
5  * This file is part of ConfClerk.
6  *
7  * ConfClerk is free software: you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the Free
9  * Software Foundation, either version 2 of the License, or (at your option)
10  * any later version.
11  *
12  * ConfClerk is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
15  * more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * ConfClerk.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <QSqlError>
22 #include <QSqlQuery>
23 #include <QSqlRecord>
24 #include <QVariant>
25 #include <QDateTime>
26 #include "qglobal.h"
27 #if QT_VERSION >= 0x050000
28 #include <QStandardPaths>
29 #else
30 #include <QDesktopServices>
31 #endif
32
33 #include <QDir>
34 #include "sqlengine.h"
35 #include "track.h"
36 #include "conference.h"
37
38 #include <QDebug>
39
40 SqlEngine::SqlEngine(QObject *aParent): QObject(aParent), DATE_FORMAT("yyyy-MM-dd"), TIME_FORMAT("hh:mm") {
41 #if QT_VERSION >= 0x050000
42     QDir dbPath(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
43 #else
44     QDir dbPath(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
45 #endif
46     dbFilename = dbPath.absoluteFilePath("ConfClerk.sqlite");
47 }
48
49
50 SqlEngine::~SqlEngine() {
51 }
52
53
54 void SqlEngine::open() {
55     // we may have to create the directory of the database
56     QFileInfo dbFilenameInfo(dbFilename);
57     QDir cwd;
58     cwd.mkpath(dbFilenameInfo.absolutePath());
59     // We don't have to handle errors because in worst case, opening the database will fail
60     // and db.isOpen() returns false.
61     db = QSqlDatabase::addDatabase("QSQLITE");
62     db.setDatabaseName(dbFilename);
63     db.open();
64 }
65
66
67 int SqlEngine::dbSchemaVersion() {
68     QSqlQuery query(db);
69     if (!query.exec("PRAGMA user_version")) {
70         emitSqlQueryError(query);
71         return -2;
72     }
73     query.first();
74     int version = query.value(0).toInt();
75     if (version == 0) {
76         // check whether the tables are existing
77         if (!query.exec("select count(*) from sqlite_master where name='CONFERENCE'")) {
78             emitSqlQueryError(query);
79             return -2;
80         }
81         query.first();
82         if (query.value(0).toInt() == 1) return 0; // tables are existing
83         return -1; // database seems to be empty (or has other tables)
84     }
85     return version;
86 }
87
88
89 bool SqlEngine::updateDbSchemaVersion000To001() {
90     return applySqlFile(":/dbschema000to001.sql");
91 }
92
93
94 bool SqlEngine::updateDbSchemaVersion001To002() {
95     return applySqlFile(":/dbschema001to002.sql");
96 }
97
98
99 bool SqlEngine::createCurrentDbSchema() {
100     return applySqlFile(":/dbschema002.sql");
101 }
102
103
104 bool SqlEngine::createOrUpdateDbSchema() {
105     int version = dbSchemaVersion();
106     switch (version) {
107     case -2:
108         // the error has already been emitted by the previous function
109         return false;
110     case -1:
111         // empty database
112         return createCurrentDbSchema();
113     case 0:
114         // db schema version 0
115         return updateDbSchemaVersion000To001();
116     case 1:
117         // db schema version 1
118         return updateDbSchemaVersion001To002();
119     case 2:
120         // current schema
121         return true;
122     default:
123         // unsupported schema
124         emit dbError(tr("Unsupported database schema version %1.").arg(version));
125     }
126     return false;
127 }
128
129
130 bool SqlEngine::applySqlFile(const QString sqlFile) {
131     QFile file(sqlFile);
132     file.open(QIODevice::ReadOnly | QIODevice::Text);
133     QString allSqlStatements = file.readAll();
134     QSqlQuery query(db);
135     foreach(QString sql, allSqlStatements.split(";")) {
136         if (sql.trimmed().isEmpty())  // do not execute empty queries like the last character from create_tables.sql
137             continue;
138         if (!query.exec(sql)) {
139             emitSqlQueryError(query);
140             return false;
141         }
142     }
143     return true;
144 }
145
146
147 QDateTime parseDateIgnoreTime(QString dateStr) {
148     QDateTime dateTime = QDateTime::fromString(dateStr, Qt::DateFormat::ISODate);
149     dateTime.setOffsetFromUtc(0);
150     return dateTime;
151 }
152
153
154 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference, int conferenceId, bool omit_display_time_shift) {
155     QSqlQuery query(db);
156     bool insert = conferenceId <= 0;
157     if (insert) { // insert conference
158         query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,"
159                                                 "day_change,timeslot_duration,utc_offset,display_time_shift,active) "
160                         " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,"
161                                                 ":day_change,:timeslot_duration,:utc_offset,:display_time_shift,:active)");
162     } else { // update conference
163         QString update = "UPDATE CONFERENCE set title=:title, url=:url, subtitle=:subtitle, venue=:venue, city=:city, start=:start, end=:end, "
164                          "day_change=:day_change, timeslot_duration=:timeslot_duration, utc_offset=:utc_offset";
165         if (!omit_display_time_shift) update += ", display_time_shift=:display_time_shift";
166         update += ", active=:active WHERE id=:id";
167         query.prepare(update);
168     }
169     foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) {
170         query.bindValue(QString(":") + prop_name, aConference[prop_name]);
171     }
172     query.bindValue(":start", parseDateIgnoreTime(aConference["start"]).toTime_t());
173     query.bindValue(":end", parseDateIgnoreTime(aConference["end"]).toTime_t());
174     QTime dayChange = QTime::fromString(aConference["day_change"].left(TIME_FORMAT.size()), TIME_FORMAT);
175     query.bindValue(":day_change", QTime(0, 0).secsTo(dayChange));
176     query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
177     QVariant utc_offset;
178     if (!aConference.value("utc_offset").isEmpty()) utc_offset = aConference["utc_offset"].toInt();
179     query.bindValue(":utc_offset", utc_offset);
180     if (!omit_display_time_shift) {
181         QVariant display_time_shift;
182         if (!aConference.value("display_time_shift").isEmpty()) display_time_shift = aConference["display_time_shift"].toInt();
183         query.bindValue(":display_time_shift", display_time_shift);
184     }
185     query.bindValue(":active", 1);
186     if (!insert) query.bindValue(":id", conferenceId);
187     query.exec();
188     emitSqlQueryError(query);
189     if (insert) {
190         aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
191     } else {
192         aConference["id"] = QVariant(conferenceId).toString();
193     }
194 }
195
196
197 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent) {
198     int conferenceId = aEvent["conference_id"].toInt();
199     Conference conference = Conference::getById(conferenceId);
200
201     // insert event track to table and get track id
202     Track track;
203     int trackId;
204     QString trackName = aEvent["track"];
205     if (trackName.isEmpty()) trackName = tr("No track");
206     try
207     {
208         track = Track::retrieveByName(conferenceId, trackName);
209         trackId = track.id();
210     }
211     catch (OrmNoObjectException &e) {
212         track.setConference(conferenceId);
213         track.setName(trackName);
214         trackId = track.insert();
215     }
216     QDate startDate = QDate::fromString(aEvent["date"], DATE_FORMAT);
217     QTime startTime = QTime::fromString(aEvent["start"], TIME_FORMAT);
218     QDateTime startDateTime;
219     startDateTime.setTimeSpec(Qt::UTC);
220     startDateTime = QDateTime(startDate, startTime, Qt::UTC);
221
222     bool event_exists = false;
223     {
224         QSqlQuery check_event_query;
225         check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
226         check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
227         check_event_query.bindValue(":id", aEvent["id"]);
228         if (!check_event_query.exec()) {
229             qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
230                     << "event id:" << aEvent["id"]
231                     << "error:" << check_event_query.lastError()
232                     ;
233             return;
234         }
235         if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
236             event_exists = true;
237         }
238     }
239
240     QSqlQuery result;
241     if (event_exists) {
242         result.prepare("UPDATE EVENT SET"
243                         " start = :start"
244                         ", duration = :duration"
245                         ", xid_track = :xid_track"
246                         ", type = :type"
247                         ", language = :language"
248                         ", tag = :tag"
249                         ", title = :title"
250                         ", subtitle = :subtitle"
251                         ", abstract = :abstract"
252                         ", description = :description"
253                             " WHERE id = :id AND xid_conference = :xid_conference");
254     } else {
255         result.prepare("INSERT INTO EVENT "
256                         " (xid_conference, id, start, duration, xid_track, type, "
257                             " language, tag, title, subtitle, abstract, description) "
258                         " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
259                             ":language, :tag, :title, :subtitle, :abstract, :description)");
260     }
261     result.bindValue(":xid_conference", aEvent["conference_id"]);
262     result.bindValue(":start", QString::number(startDateTime.toTime_t()));
263     result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
264     result.bindValue(":xid_track", trackId);
265     static const QList<QString> props = QList<QString>()
266         << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
267     foreach (QString prop_name, props) {
268         result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
269     }
270     if (!result.exec()) {
271         qWarning() << "event insert/update failed:" << result.lastError();
272     }
273 }
274
275
276 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson) {
277     QSqlQuery query(db);
278     query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)");
279     query.bindValue(":xid_conference", aPerson["conference_id"]);
280     query.bindValue(":id", aPerson["id"]);
281     query.bindValue(":name", aPerson["name"]);
282     query.exec(); // TODO some queries fail due to the unique key constraint
283     // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError();
284
285     query = QSqlQuery(db);
286     query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)");
287     query.bindValue(":xid_conference", aPerson["conference_id"]);
288     query.bindValue(":xid_event", aPerson["event_id"]);
289     query.bindValue(":xid_person", aPerson["id"]);
290     query.exec(); // TODO some queries fail due to the unique key constraint
291     // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError();
292 }
293
294
295 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom) {
296     QSqlQuery query(db);
297     query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
298     query.bindValue(":conference_id", aRoom["conference_id"]);
299     query.bindValue(":name", aRoom["name"]);
300     query.exec();
301     emitSqlQueryError(query);
302     // now we have to check whether ROOM record with 'name' exists or not,
303     // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
304     //   and assign autoincremented 'id' to aRoom
305     // - if it exists, then we need to get its 'id' and assign it to aRoom
306     aRoom["id"] = "";
307     if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
308     {
309         aRoom["id"] = query.value(0).toString();
310     }
311     else // ROOM record doesn't exist yet, need to create it
312     {
313         query = QSqlQuery(db);
314         query.prepare("INSERT INTO ROOM (xid_conference,name) VALUES (:xid_conference, :name)");
315         query.bindValue(":xid_conference", aRoom["conference_id"]);
316         query.bindValue(":name", aRoom["name"]);
317         query.exec();
318         emitSqlQueryError(query);
319         aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
320         //LOG_AUTOTEST(query);
321     }
322
323     // remove previous conference/room records; room names might have changed
324     query = QSqlQuery(db);
325     query.prepare("DELETE FROM EVENT_ROOM WHERE xid_conference=:conference_id AND xid_event=:event_id");
326     query.bindValue(":conference_id", aRoom["conference_id"]);
327     query.bindValue(":event_id", aRoom["event_id"]);
328     query.exec();
329     emitSqlQueryError(query);
330     // and insert new ones
331     query = QSqlQuery(db);
332     query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
333     query.bindValue(":conference_id", aRoom["conference_id"]);
334     query.bindValue(":event_id", aRoom["event_id"]);
335     query.bindValue(":room_id", aRoom["id"]);
336     query.exec();
337     emitSqlQueryError(query);
338 }
339
340
341 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink) {
342     //TODO: check if the link doesn't exist before inserting
343     QSqlQuery query(db);
344     query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
345     query.bindValue(":xid_event", aLink["event_id"]);
346     query.bindValue(":xid_conference", aLink["conference_id"]);
347     query.bindValue(":name", aLink["name"]);
348     query.bindValue(":url", aLink["url"]);
349     query.exec();
350     emitSqlQueryError(query);
351 }
352
353
354 bool SqlEngine::searchEvent(int aConferenceId, const QMultiHash<QString,QString> &aColumns, const QString &aKeyword) {
355     if (aColumns.empty()) return false;
356
357     // DROP
358     QSqlQuery query(db);
359     query.exec("DROP TABLE IF EXISTS SEARCH_EVENT");
360     emitSqlQueryError(query);
361
362     // CREATE
363     query.exec("CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER  NOT NULL, id INTEGER NOT NULL )");
364     emitSqlQueryError(query);
365
366     // INSERT
367     QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
368                 "SELECT DISTINCT EVENT.xid_conference, EVENT.id FROM EVENT ");
369     if( aColumns.contains("ROOM") ){
370         sql += "LEFT JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
371         sql += "LEFT JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
372     }
373     if( aColumns.contains("PERSON") ){
374         sql += "LEFT JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
375         sql += "LEFT JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
376     }
377     sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
378
379     QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
380     QStringList whereAnd;
381     for (int i=0; i < searchKeywords.count(); i++) {
382         QStringList whereOr;
383         foreach (QString table, aColumns.uniqueKeys()) {
384             foreach (QString column, aColumns.values(table)){
385                  whereOr.append(QString("%1.%2 LIKE '\%' || :%1%2%3 || '\%'").arg(table).arg(column).arg(i));
386             }
387         }
388         whereAnd.append(whereOr.join(" OR "));
389     }
390     sql += whereAnd.join(") AND (");
391     sql += QString(")");
392
393     query.prepare(sql);
394     for (int i = 0; i != searchKeywords.size(); ++i) {
395         QString keyword = searchKeywords[i];
396         foreach (QString table, aColumns.uniqueKeys()) {
397             foreach (QString column, aColumns.values(table)) {
398                 query.bindValue(QString(":%1%2%3").arg(table).arg(column).arg(i), keyword );
399             }
400         }
401     }
402
403     bool success = query.exec();
404     emitSqlQueryError(query);
405     return success;
406 }
407
408
409 bool SqlEngine::beginTransaction() {
410     QSqlQuery query(db);
411     bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
412     emitSqlQueryError(query);
413     return success;
414 }
415
416
417 bool SqlEngine::commitTransaction() {
418     QSqlQuery query(db);
419     bool success = query.exec("COMMIT");
420     emitSqlQueryError(query);
421     return success;
422 }
423
424
425 bool SqlEngine::rollbackTransaction() {
426     QSqlQuery query(db);
427     bool success = query.exec("ROLLBACK");
428     emitSqlQueryError(query);
429     return success;
430 }
431
432
433 bool SqlEngine::deleteConference(int id) {
434     QSqlQuery query(db);
435     bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
436     emitSqlQueryError(query);
437
438     QStringList sqlList;
439     sqlList << "DELETE FROM LINK WHERE xid_conference = ?"
440             << "DELETE FROM EVENT_ROOM WHERE xid_conference = ?"
441             << "DELETE FROM EVENT_PERSON WHERE xid_conference = ?"
442             << "DELETE FROM EVENT WHERE xid_conference = ?"
443             << "DELETE FROM ROOM WHERE xid_conference = ?"
444             << "DELETE FROM PERSON WHERE xid_conference = ?"
445             << "DELETE FROM TRACK WHERE xid_conference = ?"
446             << "DELETE FROM CONFERENCE WHERE id = ?";
447
448     foreach (const QString& sql, sqlList) {
449         query.prepare(sql);
450         query.bindValue(0, id);
451         success &= query.exec();
452         emitSqlQueryError(query);
453     }
454
455     success &= query.exec("COMMIT");
456     emitSqlQueryError(query);
457
458     return success;
459 }
460
461
462 void SqlEngine::emitSqlQueryError(const QSqlQuery &query) {
463     QSqlError error = query.lastError();
464     if (error.type() == QSqlError::NoError) return;
465     emit dbError(error.text());
466 }