source: src/sql/sqlengine.cpp

Last change on this file was 763b877, checked in by Philipp Spitzer <philipp@…>, 5 months ago

Fix bug: display_time_shift was lost when conference was reloaded.

  • Property mode set to 100644
File size: 17.2 KB
RevLine 
[ca90cb1]1/*
2 * Copyright (C) 2010 Ixonos Plc.
[ffb6be7]3 * Copyright (C) 2011-2021 Philipp Spitzer, gregor herrmann, Stefan Stahl
[ca90cb1]4 *
[6df32f2]5 * This file is part of ConfClerk.
[ca90cb1]6 *
[6df32f2]7 * ConfClerk is free software: you can redistribute it and/or modify it
[ca90cb1]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 *
[6df32f2]12 * ConfClerk is distributed in the hope that it will be useful, but
[ca90cb1]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
[6df32f2]18 * ConfClerk.  If not, see <http://www.gnu.org/licenses/>.
[ca90cb1]19 */
[72f6fe4]20
21#include <QSqlError>
22#include <QSqlQuery>
23#include <QSqlRecord>
24#include <QVariant>
25#include <QDateTime>
[79a7671]26#include "qglobal.h"
27#if QT_VERSION >= 0x050000
[4b6ae6b]28#include <QStandardPaths>
[79a7671]29#else
30#include <QDesktopServices>
31#endif
[72f6fe4]32
33#include <QDir>
34#include "sqlengine.h"
[8d6798d]35#include "track.h"
36#include "conference.h"
[72f6fe4]37
38#include <QDebug>
39
[0816326]40SqlEngine::SqlEngine(QObject *aParent): QObject(aParent), DATE_FORMAT("yyyy-MM-dd"), TIME_FORMAT("hh:mm") {
[79a7671]41#if QT_VERSION >= 0x050000
[4b6ae6b]42    QDir dbPath(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
[79a7671]43#else
44    QDir dbPath(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
45#endif
[61346c9]46    dbFilename = dbPath.absoluteFilePath("ConfClerk.sqlite");
[72f6fe4]47}
48
[61346c9]49
50SqlEngine::~SqlEngine() {
[72f6fe4]51}
52
53
[61346c9]54void SqlEngine::open() {
[9b5a80ff]55    // we may have to create the directory of the database
[61346c9]56    QFileInfo dbFilenameInfo(dbFilename);
[a8f8b5d]57    QDir cwd;
58    cwd.mkpath(dbFilenameInfo.absolutePath());
[9b5a80ff]59    // We don't have to handle errors because in worst case, opening the database will fail
60    // and db.isOpen() returns false.
[61346c9]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;
[72f6fe4]72    }
[61346c9]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)
[e662750]84    }
[61346c9]85    return version;
86}
[72f6fe4]87
88
[61346c9]89bool SqlEngine::updateDbSchemaVersion000To001() {
[f1826af]90    return applySqlFile(":/dbschema000to001.sql");
[72f6fe4]91}
92
[61346c9]93
[c13a488]94bool SqlEngine::updateDbSchemaVersion001To002() {
95    return applySqlFile(":/dbschema001to002.sql");
96}
97
98
[61346c9]99bool SqlEngine::createCurrentDbSchema() {
[c13a488]100    return applySqlFile(":/dbschema002.sql");
[61346c9]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:
[c13a488]117        // db schema version 1
118        return updateDbSchemaVersion001To002();
119    case 2:
[61346c9]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;
[72f6fe4]127}
128
129
[f1826af]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
[763b877]147void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference, int conferenceId, bool omit_display_time_shift) {
[61346c9]148    QSqlQuery query(db);
[f0f9fdc]149    bool insert = conferenceId <= 0;
150    if (insert) { // insert conference
[5293ef0]151        query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,"
[8d47489]152                                                "day_change,timeslot_duration,utc_offset,display_time_shift,active) "
[5293ef0]153                        " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,"
[8d47489]154                                                ":day_change,:timeslot_duration,:utc_offset,:display_time_shift,:active)");
[f0f9fdc]155    } else { // update conference
[763b877]156        QString update = "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";
158        if (!omit_display_time_shift) update += ", display_time_shift=:display_time_shift";
159        update += ", active=:active WHERE id=:id";
160        query.prepare(update);
[f0f9fdc]161    }
162    foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) {
163        query.bindValue(QString(":") + prop_name, aConference[prop_name]);
164    }
165    query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
166    query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
[d03ca41]167    QTime dayChange = QTime::fromString(aConference["day_change"].left(TIME_FORMAT.size()), TIME_FORMAT);
168    query.bindValue(":day_change", QTime(0, 0).secsTo(dayChange));
[f0f9fdc]169    query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
[8d47489]170    QVariant utc_offset;
171    if (!aConference.value("utc_offset").isEmpty()) utc_offset = aConference["utc_offset"].toInt();
172    query.bindValue(":utc_offset", utc_offset);
[763b877]173    if (!omit_display_time_shift) {
174        QVariant display_time_shift;
175        if (!aConference.value("display_time_shift").isEmpty()) display_time_shift = aConference["display_time_shift"].toInt();
176        query.bindValue(":display_time_shift", display_time_shift);
177    }
[f0f9fdc]178    query.bindValue(":active", 1);
179    if (!insert) query.bindValue(":id", conferenceId);
180    query.exec();
181    emitSqlQueryError(query);
182    if (insert) {
183        aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
184    } else {
[e2c612c]185        aConference["id"] = QVariant(conferenceId).toString();
[72f6fe4]186    }
187}
188
189
[61346c9]190void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent) {
[41c4ceb]191    int conferenceId = aEvent["conference_id"].toInt();
192    Conference conference = Conference::getById(conferenceId);
193
194    // insert event track to table and get track id
[61346c9]195    Track track;
196    int trackId;
[41c4ceb]197    QString trackName = aEvent["track"];
[e27a3f5]198    if (trackName.isEmpty()) trackName = tr("No track");
[61346c9]199    try
[72f6fe4]200    {
[41c4ceb]201        track = Track::retrieveByName(conferenceId, trackName);
[61346c9]202        trackId = track.id();
203    }
204    catch (OrmNoObjectException &e) {
[41c4ceb]205        track.setConference(conferenceId);
206        track.setName(trackName);
[61346c9]207        trackId = track.insert();
208    }
[41c4ceb]209    QDate startDate = QDate::fromString(aEvent["date"], DATE_FORMAT);
210    QTime startTime = QTime::fromString(aEvent["start"], TIME_FORMAT);
[61346c9]211    QDateTime startDateTime;
212    startDateTime.setTimeSpec(Qt::UTC);
[41c4ceb]213    startDateTime = QDateTime(startDate, startTime, Qt::UTC);
[f548c17]214
[61346c9]215    bool event_exists = false;
216    {
217        QSqlQuery check_event_query;
218        check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
219        check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
220        check_event_query.bindValue(":id", aEvent["id"]);
221        if (!check_event_query.exec()) {
222            qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
223                    << "event id:" << aEvent["id"]
224                    << "error:" << check_event_query.lastError()
225                    ;
226            return;
[f548c17]227        }
[61346c9]228        if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
229            event_exists = true;
[c129da26]230        }
[72f6fe4]231    }
232
[61346c9]233    QSqlQuery result;
234    if (event_exists) {
235        result.prepare("UPDATE EVENT SET"
236                        " start = :start"
237                        ", duration = :duration"
238                        ", xid_track = :xid_track"
239                        ", type = :type"
240                        ", language = :language"
241                        ", tag = :tag"
242                        ", title = :title"
243                        ", subtitle = :subtitle"
244                        ", abstract = :abstract"
245                        ", description = :description"
246                            " WHERE id = :id AND xid_conference = :xid_conference");
247    } else {
248        result.prepare("INSERT INTO EVENT "
249                        " (xid_conference, id, start, duration, xid_track, type, "
250                            " language, tag, title, subtitle, abstract, description) "
251                        " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
252                            ":language, :tag, :title, :subtitle, :abstract, :description)");
253    }
254    result.bindValue(":xid_conference", aEvent["conference_id"]);
255    result.bindValue(":start", QString::number(startDateTime.toTime_t()));
256    result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
257    result.bindValue(":xid_track", trackId);
258    static const QList<QString> props = QList<QString>()
259        << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
260    foreach (QString prop_name, props) {
261        result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
262    }
263    if (!result.exec()) {
264        qWarning() << "event insert/update failed:" << result.lastError();
265    }
266}
[72f6fe4]267
[dcefa71]268
[61346c9]269void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson) {
270    QSqlQuery query(db);
271    query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)");
272    query.bindValue(":xid_conference", aPerson["conference_id"]);
273    query.bindValue(":id", aPerson["id"]);
274    query.bindValue(":name", aPerson["name"]);
275    query.exec(); // TODO some queries fail due to the unique key constraint
276    // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError();
277
278    query = QSqlQuery(db);
279    query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)");
280    query.bindValue(":xid_conference", aPerson["conference_id"]);
281    query.bindValue(":xid_event", aPerson["event_id"]);
282    query.bindValue(":xid_person", aPerson["id"]);
283    query.exec(); // TODO some queries fail due to the unique key constraint
284    // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError();
[72f6fe4]285}
286
287
[61346c9]288void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom) {
289    QSqlQuery query(db);
290    query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
291    query.bindValue(":conference_id", aRoom["conference_id"]);
292    query.bindValue(":name", aRoom["name"]);
[5e50875]293    query.exec();
[61346c9]294    emitSqlQueryError(query);
295    // now we have to check whether ROOM record with 'name' exists or not,
296    // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
297    //   and assign autoincremented 'id' to aRoom
298    // - if it exists, then we need to get its 'id' and assign it to aRoom
299    aRoom["id"] = "";
300    if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
301    {
302        aRoom["id"] = query.value(0).toString();
303    }
304    else // ROOM record doesn't exist yet, need to create it
[72f6fe4]305    {
[63b2343]306        query = QSqlQuery(db);
[0ba2b59]307        query.prepare("INSERT INTO ROOM (xid_conference,name) VALUES (:xid_conference, :name)");
[61346c9]308        query.bindValue(":xid_conference", aRoom["conference_id"]);
[d942dc3]309        query.bindValue(":name", aRoom["name"]);
[5e50875]310        query.exec();
[61346c9]311        emitSqlQueryError(query);
312        aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
313        //LOG_AUTOTEST(query);
[72f6fe4]314    }
[61346c9]315
316    // remove previous conference/room records; room names might have changed
317    query = QSqlQuery(db);
318    query.prepare("DELETE FROM EVENT_ROOM WHERE xid_conference=:conference_id AND xid_event=:event_id");
319    query.bindValue(":conference_id", aRoom["conference_id"]);
320    query.bindValue(":event_id", aRoom["event_id"]);
[5e50875]321    query.exec();
[61346c9]322    emitSqlQueryError(query);
323    // and insert new ones
324    query = QSqlQuery(db);
325    query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
326    query.bindValue(":conference_id", aRoom["conference_id"]);
327    query.bindValue(":event_id", aRoom["event_id"]);
328    query.bindValue(":room_id", aRoom["id"]);
[5e50875]329    query.exec();
[61346c9]330    emitSqlQueryError(query);
[72f6fe4]331}
332
333
[61346c9]334void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink) {
[72f6fe4]335    //TODO: check if the link doesn't exist before inserting
[61346c9]336    QSqlQuery query(db);
337    query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
338    query.bindValue(":xid_event", aLink["event_id"]);
339    query.bindValue(":xid_conference", aLink["conference_id"]);
340    query.bindValue(":name", aLink["name"]);
341    query.bindValue(":url", aLink["url"]);
[5e50875]342    query.exec();
[61346c9]343    emitSqlQueryError(query);
[72f6fe4]344}
345
[990afd5]346
[af9f24b]347bool SqlEngine::searchEvent(int aConferenceId, const QMultiHash<QString,QString> &aColumns, const QString &aKeyword) {
[61346c9]348    if (aColumns.empty()) return false;
[990afd5]349
[e662750]350    // DROP
[61346c9]351    QSqlQuery query(db);
352    query.exec("DROP TABLE IF EXISTS SEARCH_EVENT");
353    emitSqlQueryError(query);
354
[e662750]355    // CREATE
[61346c9]356    query.exec("CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER  NOT NULL, id INTEGER NOT NULL )");
357    emitSqlQueryError(query);
358
[e662750]359    // INSERT
[a55781e]360    QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
[66698a6]361                "SELECT DISTINCT EVENT.xid_conference, EVENT.id FROM EVENT ");
[c7b58d4]362    if( aColumns.contains("ROOM") ){
[71c3eb6]363        sql += "LEFT JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
364        sql += "LEFT JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
[c7b58d4]365    }
366    if( aColumns.contains("PERSON") ){
[71c3eb6]367        sql += "LEFT JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
368        sql += "LEFT JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
[c7b58d4]369    }
[a55781e]370    sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
[c7b58d4]371
[525e2e2]372    QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
373    QStringList whereAnd;
374    for (int i=0; i < searchKeywords.count(); i++) {
375        QStringList whereOr;
376        foreach (QString table, aColumns.uniqueKeys()) {
377            foreach (QString column, aColumns.values(table)){
378                 whereOr.append(QString("%1.%2 LIKE '\%' || :%1%2%3 || '\%'").arg(table).arg(column).arg(i));
[47eda2b]379            }
[c7b58d4]380        }
[525e2e2]381        whereAnd.append(whereOr.join(" OR "));
[990afd5]382    }
[525e2e2]383    sql += whereAnd.join(") AND (");
[a55781e]384    sql += QString(")");
[990afd5]385
[a55781e]386    query.prepare(sql);
[525e2e2]387    for (int i = 0; i != searchKeywords.size(); ++i) {
388        QString keyword = searchKeywords[i];
389        foreach (QString table, aColumns.uniqueKeys()) {
390            foreach (QString column, aColumns.values(table)) {
[53effcb]391                query.bindValue(QString(":%1%2%3").arg(table).arg(column).arg(i), keyword );
[47eda2b]392            }
[a55781e]393        }
394    }
395
[61346c9]396    bool success = query.exec();
397    emitSqlQueryError(query);
398    return success;
[e662750]399}
400
[1bad318]401
[61346c9]402bool SqlEngine::beginTransaction() {
403    QSqlQuery query(db);
404    bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
405    emitSqlQueryError(query);
406    return success;
[1bad318]407}
408
409
[61346c9]410bool SqlEngine::commitTransaction() {
411    QSqlQuery query(db);
412    bool success = query.exec("COMMIT");
413    emitSqlQueryError(query);
414    return success;
[1bad318]415}
416
[d97bcab]417
[0c71a07]418bool SqlEngine::rollbackTransaction() {
419    QSqlQuery query(db);
420    bool success = query.exec("ROLLBACK");
421    emitSqlQueryError(query);
422    return success;
423}
424
425
[61346c9]426bool SqlEngine::deleteConference(int id) {
427    QSqlQuery query(db);
428    bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
429    emitSqlQueryError(query);
430
431    QStringList sqlList;
432    sqlList << "DELETE FROM LINK WHERE xid_conference = ?"
433            << "DELETE FROM EVENT_ROOM WHERE xid_conference = ?"
434            << "DELETE FROM EVENT_PERSON WHERE xid_conference = ?"
435            << "DELETE FROM EVENT WHERE xid_conference = ?"
436            << "DELETE FROM ROOM WHERE xid_conference = ?"
437            << "DELETE FROM PERSON WHERE xid_conference = ?"
438            << "DELETE FROM TRACK WHERE xid_conference = ?"
439            << "DELETE FROM CONFERENCE WHERE id = ?";
440
441    foreach (const QString& sql, sqlList) {
442        query.prepare(sql);
443        query.bindValue(0, id);
444        success &= query.exec();
445        emitSqlQueryError(query);
[d97bcab]446    }
447
[61346c9]448    success &= query.exec("COMMIT");
449    emitSqlQueryError(query);
[d97bcab]450
[61346c9]451    return success;
[d97bcab]452}
453
[9f367eb]454
[61346c9]455void SqlEngine::emitSqlQueryError(const QSqlQuery &query) {
456    QSqlError error = query.lastError();
457    if (error.type() == QSqlError::NoError) return;
458    emit dbError(error.text());
[d97bcab]459}
Note: See TracBrowser for help on using the repository browser.