source: src/sql/sqlengine.cpp @ ff579df

Last change on this file since ff579df was ffb6be7, checked in by gregor herrmann <gregor@…>, 6 months ago

Bump copyright years.

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