]> ToastFreeware Gitweb - toast/confclerk.git/blob - src/sql/sqlengine.cpp
Add utc_offset and display_time_shift columns to conference database.
[toast/confclerk.git] / src / sql / sqlengine.cpp
1 /*
2  * Copyright (C) 2010 Ixonos Plc.
3  * Copyright (C) 2011-2017 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 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference, int conferenceId) {
148     QSqlQuery query(db);
149     bool insert = conferenceId <= 0;
150     if (insert) { // insert conference
151         query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,"
152                                                 "day_change,timeslot_duration,active) "
153                         " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,"
154                                                 ":day_change,:timeslot_duration,:active)");
155     } else { // update conference
156         query.prepare("UPDATE CONFERENCE set title=:title, url=:url, subtitle=:subtitle, venue=:venue, city=:city, start=:start, end=:end,"
157                                             "day_change=:day_change, timeslot_duration=:timeslot_duration, active=:active "
158                       "WHERE id=:id");
159     }
160     foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) {
161         query.bindValue(QString(":") + prop_name, aConference[prop_name]);
162     }
163     query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
164     query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
165     QTime dayChange = QTime::fromString(aConference["day_change"].left(TIME_FORMAT.size()), TIME_FORMAT);
166     query.bindValue(":day_change", QTime(0, 0).secsTo(dayChange));
167     query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
168     query.bindValue(":active", 1);
169     if (!insert) query.bindValue(":id", conferenceId);
170     query.exec();
171     emitSqlQueryError(query);
172     if (insert) {
173         aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
174     } else {
175         aConference["id"] = QVariant(conferenceId).toString();
176     }
177 }
178
179
180 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent) {
181     int conferenceId = aEvent["conference_id"].toInt();
182     Conference conference = Conference::getById(conferenceId);
183
184     // insert event track to table and get track id
185     Track track;
186     int trackId;
187     QString trackName = aEvent["track"];
188     if (trackName.isEmpty()) trackName = tr("No track");
189     try
190     {
191         track = Track::retrieveByName(conferenceId, trackName);
192         trackId = track.id();
193     }
194     catch (OrmNoObjectException &e) {
195         track.setConference(conferenceId);
196         track.setName(trackName);
197         trackId = track.insert();
198     }
199     QDate startDate = QDate::fromString(aEvent["date"], DATE_FORMAT);
200     QTime startTime = QTime::fromString(aEvent["start"], TIME_FORMAT);
201     QDateTime startDateTime;
202     startDateTime.setTimeSpec(Qt::UTC);
203     startDateTime = QDateTime(startDate, startTime, Qt::UTC);
204
205     bool event_exists = false;
206     {
207         QSqlQuery check_event_query;
208         check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
209         check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
210         check_event_query.bindValue(":id", aEvent["id"]);
211         if (!check_event_query.exec()) {
212             qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
213                     << "event id:" << aEvent["id"]
214                     << "error:" << check_event_query.lastError()
215                     ;
216             return;
217         }
218         if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
219             event_exists = true;
220         }
221     }
222
223     QSqlQuery result;
224     if (event_exists) {
225         result.prepare("UPDATE EVENT SET"
226                         " start = :start"
227                         ", duration = :duration"
228                         ", xid_track = :xid_track"
229                         ", type = :type"
230                         ", language = :language"
231                         ", tag = :tag"
232                         ", title = :title"
233                         ", subtitle = :subtitle"
234                         ", abstract = :abstract"
235                         ", description = :description"
236                             " WHERE id = :id AND xid_conference = :xid_conference");
237     } else {
238         result.prepare("INSERT INTO EVENT "
239                         " (xid_conference, id, start, duration, xid_track, type, "
240                             " language, tag, title, subtitle, abstract, description) "
241                         " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
242                             ":language, :tag, :title, :subtitle, :abstract, :description)");
243     }
244     result.bindValue(":xid_conference", aEvent["conference_id"]);
245     result.bindValue(":start", QString::number(startDateTime.toTime_t()));
246     result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
247     result.bindValue(":xid_track", trackId);
248     static const QList<QString> props = QList<QString>()
249         << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
250     foreach (QString prop_name, props) {
251         result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
252     }
253     if (!result.exec()) {
254         qWarning() << "event insert/update failed:" << result.lastError();
255     }
256 }
257
258
259 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson) {
260     QSqlQuery query(db);
261     query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)");
262     query.bindValue(":xid_conference", aPerson["conference_id"]);
263     query.bindValue(":id", aPerson["id"]);
264     query.bindValue(":name", aPerson["name"]);
265     query.exec(); // TODO some queries fail due to the unique key constraint
266     // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError();
267
268     query = QSqlQuery(db);
269     query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)");
270     query.bindValue(":xid_conference", aPerson["conference_id"]);
271     query.bindValue(":xid_event", aPerson["event_id"]);
272     query.bindValue(":xid_person", aPerson["id"]);
273     query.exec(); // TODO some queries fail due to the unique key constraint
274     // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError();
275 }
276
277
278 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom) {
279     QSqlQuery query(db);
280     query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
281     query.bindValue(":conference_id", aRoom["conference_id"]);
282     query.bindValue(":name", aRoom["name"]);
283     query.exec();
284     emitSqlQueryError(query);
285     // now we have to check whether ROOM record with 'name' exists or not,
286     // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
287     //   and assign autoincremented 'id' to aRoom
288     // - if it exists, then we need to get its 'id' and assign it to aRoom
289     aRoom["id"] = "";
290     if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
291     {
292         aRoom["id"] = query.value(0).toString();
293     }
294     else // ROOM record doesn't exist yet, need to create it
295     {
296         query = QSqlQuery(db);
297         query.prepare("INSERT INTO ROOM (xid_conference,name) VALUES (:xid_conference, :name)");
298         query.bindValue(":xid_conference", aRoom["conference_id"]);
299         query.bindValue(":name", aRoom["name"]);
300         query.exec();
301         emitSqlQueryError(query);
302         aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
303         //LOG_AUTOTEST(query);
304     }
305
306     // remove previous conference/room records; room names might have changed
307     query = QSqlQuery(db);
308     query.prepare("DELETE FROM EVENT_ROOM WHERE xid_conference=:conference_id AND xid_event=:event_id");
309     query.bindValue(":conference_id", aRoom["conference_id"]);
310     query.bindValue(":event_id", aRoom["event_id"]);
311     query.exec();
312     emitSqlQueryError(query);
313     // and insert new ones
314     query = QSqlQuery(db);
315     query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
316     query.bindValue(":conference_id", aRoom["conference_id"]);
317     query.bindValue(":event_id", aRoom["event_id"]);
318     query.bindValue(":room_id", aRoom["id"]);
319     query.exec();
320     emitSqlQueryError(query);
321 }
322
323
324 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink) {
325     //TODO: check if the link doesn't exist before inserting
326     QSqlQuery query(db);
327     query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
328     query.bindValue(":xid_event", aLink["event_id"]);
329     query.bindValue(":xid_conference", aLink["conference_id"]);
330     query.bindValue(":name", aLink["name"]);
331     query.bindValue(":url", aLink["url"]);
332     query.exec();
333     emitSqlQueryError(query);
334 }
335
336
337 bool SqlEngine::searchEvent(int aConferenceId, const QMultiHash<QString,QString> &aColumns, const QString &aKeyword) {
338     if (aColumns.empty()) return false;
339
340     // DROP
341     QSqlQuery query(db);
342     query.exec("DROP TABLE IF EXISTS SEARCH_EVENT");
343     emitSqlQueryError(query);
344
345     // CREATE
346     query.exec("CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER  NOT NULL, id INTEGER NOT NULL )");
347     emitSqlQueryError(query);
348
349     // INSERT
350     QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
351                 "SELECT DISTINCT EVENT.xid_conference, EVENT.id FROM EVENT ");
352     if( aColumns.contains("ROOM") ){
353         sql += "LEFT JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
354         sql += "LEFT JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
355     }
356     if( aColumns.contains("PERSON") ){
357         sql += "LEFT JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
358         sql += "LEFT JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
359     }
360     sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
361
362     QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
363     QStringList whereAnd;
364     for (int i=0; i < searchKeywords.count(); i++) {
365         QStringList whereOr;
366         foreach (QString table, aColumns.uniqueKeys()) {
367             foreach (QString column, aColumns.values(table)){
368                  whereOr.append(QString("%1.%2 LIKE '\%' || :%1%2%3 || '\%'").arg(table).arg(column).arg(i));
369             }
370         }
371         whereAnd.append(whereOr.join(" OR "));
372     }
373     sql += whereAnd.join(") AND (");
374     sql += QString(")");
375
376     query.prepare(sql);
377     for (int i = 0; i != searchKeywords.size(); ++i) {
378         QString keyword = searchKeywords[i];
379         foreach (QString table, aColumns.uniqueKeys()) {
380             foreach (QString column, aColumns.values(table)) {
381                 query.bindValue(QString(":%1%2%3").arg(table).arg(column).arg(i), keyword );
382             }
383         }
384     }
385
386     bool success = query.exec();
387     emitSqlQueryError(query);
388     return success;
389 }
390
391
392 bool SqlEngine::beginTransaction() {
393     QSqlQuery query(db);
394     bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
395     emitSqlQueryError(query);
396     return success;
397 }
398
399
400 bool SqlEngine::commitTransaction() {
401     QSqlQuery query(db);
402     bool success = query.exec("COMMIT");
403     emitSqlQueryError(query);
404     return success;
405 }
406
407
408 bool SqlEngine::rollbackTransaction() {
409     QSqlQuery query(db);
410     bool success = query.exec("ROLLBACK");
411     emitSqlQueryError(query);
412     return success;
413 }
414
415
416 bool SqlEngine::deleteConference(int id) {
417     QSqlQuery query(db);
418     bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
419     emitSqlQueryError(query);
420
421     QStringList sqlList;
422     sqlList << "DELETE FROM LINK WHERE xid_conference = ?"
423             << "DELETE FROM EVENT_ROOM WHERE xid_conference = ?"
424             << "DELETE FROM EVENT_PERSON WHERE xid_conference = ?"
425             << "DELETE FROM EVENT WHERE xid_conference = ?"
426             << "DELETE FROM ROOM WHERE xid_conference = ?"
427             << "DELETE FROM PERSON WHERE xid_conference = ?"
428             << "DELETE FROM TRACK WHERE xid_conference = ?"
429             << "DELETE FROM CONFERENCE WHERE id = ?";
430
431     foreach (const QString& sql, sqlList) {
432         query.prepare(sql);
433         query.bindValue(0, id);
434         success &= query.exec();
435         emitSqlQueryError(query);
436     }
437
438     success &= query.exec("COMMIT");
439     emitSqlQueryError(query);
440
441     return success;
442 }
443
444
445 void SqlEngine::emitSqlQueryError(const QSqlQuery &query) {
446     QSqlError error = query.lastError();
447     if (error.type() == QSqlError::NoError) return;
448     emit dbError(error.text());
449 }