source: src/sql/sqlengine.cpp @ 809b5e5

qt5
Last change on this file since 809b5e5 was 809b5e5, checked in by gregor herrmann <gregor@…>, 4 years ago

Merge branch 'master' into qt5

  • Property mode set to 100644
File size: 17.0 KB
RevLine 
[ca90cb1]1/*
2 * Copyright (C) 2010 Ixonos Plc.
[de5d0f1]3 * Copyright (C) 2011-2017 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>
[4b6ae6b]26#include <QStandardPaths>
[72f6fe4]27
28#include <QDir>
29#include "sqlengine.h"
[8d6798d]30#include "track.h"
31#include "conference.h"
[72f6fe4]32
33#include <QDebug>
34
35const QString DATE_FORMAT ("yyyy-MM-dd");
36const QString TIME_FORMAT ("hh:mm");
37
[61346c9]38SqlEngine::SqlEngine(QObject *aParent): QObject(aParent) {
[4b6ae6b]39    QDir dbPath(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
[61346c9]40    dbFilename = dbPath.absoluteFilePath("ConfClerk.sqlite");
[72f6fe4]41}
42
[61346c9]43
44SqlEngine::~SqlEngine() {
[72f6fe4]45}
46
47
[61346c9]48void SqlEngine::open() {
[9b5a80ff]49    // we may have to create the directory of the database
[61346c9]50    QFileInfo dbFilenameInfo(dbFilename);
[a8f8b5d]51    QDir cwd;
52    cwd.mkpath(dbFilenameInfo.absolutePath());
[9b5a80ff]53    // We don't have to handle errors because in worst case, opening the database will fail
54    // and db.isOpen() returns false.
[61346c9]55    db = QSqlDatabase::addDatabase("QSQLITE");
56    db.setDatabaseName(dbFilename);
57    db.open();
58}
59
60
61int SqlEngine::dbSchemaVersion() {
62    QSqlQuery query(db);
63    if (!query.exec("PRAGMA user_version")) {
64        emitSqlQueryError(query);
65        return -2;
[72f6fe4]66    }
[61346c9]67    query.first();
68    int version = query.value(0).toInt();
69    if (version == 0) {
70        // check whether the tables are existing
71        if (!query.exec("select count(*) from sqlite_master where name='CONFERENCE'")) {
72            emitSqlQueryError(query);
73            return -2;
74        }
75        query.first();
76        if (query.value(0).toInt() == 1) return 0; // tables are existing
77        return -1; // database seems to be empty (or has other tables)
[e662750]78    }
[61346c9]79    return version;
80}
[72f6fe4]81
82
[61346c9]83bool SqlEngine::updateDbSchemaVersion000To001() {
[f1826af]84    return applySqlFile(":/dbschema000to001.sql");
[72f6fe4]85}
86
[61346c9]87
88bool SqlEngine::createCurrentDbSchema() {
[f1826af]89    return applySqlFile(":/dbschema001.sql");
[61346c9]90}
91
92
93bool SqlEngine::createOrUpdateDbSchema() {
94    int version = dbSchemaVersion();
95    switch (version) {
96    case -2:
97        // the error has already been emitted by the previous function
98        return false;
99    case -1:
100        // empty database
101        return createCurrentDbSchema();
102    case 0:
103        // db schema version 0
104        return updateDbSchemaVersion000To001();
105    case 1:
106        // current schema
107        return true;
108    default:
109        // unsupported schema
110        emit dbError(tr("Unsupported database schema version %1.").arg(version));
111    }
112    return false;
[72f6fe4]113}
114
115
[f1826af]116bool SqlEngine::applySqlFile(const QString sqlFile) {
117    QFile file(sqlFile);
118    file.open(QIODevice::ReadOnly | QIODevice::Text);
119    QString allSqlStatements = file.readAll();
120    QSqlQuery query(db);
121    foreach(QString sql, allSqlStatements.split(";")) {
122        if (sql.trimmed().isEmpty())  // do not execute empty queries like the last character from create_tables.sql
123            continue;
124        if (!query.exec(sql)) {
125            emitSqlQueryError(query);
126            return false;
127        }
128    }
129    return true;
130}
131
132
[61346c9]133void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference, int conferenceId) {
134    QSqlQuery query(db);
135    if (conferenceId <= 0) // insert conference
[72f6fe4]136    {
[5293ef0]137        query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,"
[61346c9]138                                                "day_change,timeslot_duration,active) "
[5293ef0]139                        " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,"
[61346c9]140                                                ":day_change,:timeslot_duration,:active)");
[5293ef0]141        foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) {
[61346c9]142            query.bindValue(QString(":") + prop_name, aConference[prop_name]);
[1735f55]143        }
[61346c9]144        query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
145        query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
146        query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
147        query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
148        query.bindValue(":active", 1);
[5e50875]149        query.exec();
[61346c9]150        emitSqlQueryError(query);
151        aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
152    }
153    else // update conference
154    {
[5293ef0]155        query.prepare("UPDATE CONFERENCE set title=:title, url=:url, subtitle=:subtitle, venue=:venue, city=:city, start=:start, end=:end,"
[61346c9]156                                            "day_change=:day_change, timeslot_duration=:timeslot_duration, active=:active "
157                      "WHERE id=:id");
[5293ef0]158        foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) {
[61346c9]159            query.bindValue(QString(":") + prop_name, aConference[prop_name]);
[2dffed3]160        }
[61346c9]161        query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
162        query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
163        query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
164        query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
165        query.bindValue(":active", 1);
166        query.bindValue(":id", conferenceId);
[5e50875]167        query.exec();
[61346c9]168        emitSqlQueryError(query);
[e2c612c]169        aConference["id"] = QVariant(conferenceId).toString();
[72f6fe4]170    }
171}
172
173
[61346c9]174void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent) {
[41c4ceb]175    int conferenceId = aEvent["conference_id"].toInt();
176    Conference conference = Conference::getById(conferenceId);
177
178    // insert event track to table and get track id
[61346c9]179    Track track;
180    int trackId;
[41c4ceb]181    QString trackName = aEvent["track"];
[e27a3f5]182    if (trackName.isEmpty()) trackName = tr("No track");
[61346c9]183    try
[72f6fe4]184    {
[41c4ceb]185        track = Track::retrieveByName(conferenceId, trackName);
[61346c9]186        trackId = track.id();
187    }
188    catch (OrmNoObjectException &e) {
[41c4ceb]189        track.setConference(conferenceId);
190        track.setName(trackName);
[61346c9]191        trackId = track.insert();
192    }
[41c4ceb]193    QDate startDate = QDate::fromString(aEvent["date"], DATE_FORMAT);
194    QTime startTime = QTime::fromString(aEvent["start"], TIME_FORMAT);
195    // consider day_change (note that if day_change is e.g. at 04:00 AM, an event starting at 02:00 AM has the previous date in the XML file)
196    if (startTime < conference.dayChangeTime()) startDate = startDate.addDays(1);
[61346c9]197    QDateTime startDateTime;
198    startDateTime.setTimeSpec(Qt::UTC);
[41c4ceb]199    startDateTime = QDateTime(startDate, startTime, Qt::UTC);
[f548c17]200
[61346c9]201    bool event_exists = false;
202    {
203        QSqlQuery check_event_query;
204        check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
205        check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
206        check_event_query.bindValue(":id", aEvent["id"]);
207        if (!check_event_query.exec()) {
208            qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
209                    << "event id:" << aEvent["id"]
210                    << "error:" << check_event_query.lastError()
211                    ;
212            return;
[f548c17]213        }
[61346c9]214        if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
215            event_exists = true;
[c129da26]216        }
[72f6fe4]217    }
218
[61346c9]219    QSqlQuery result;
220    if (event_exists) {
221        result.prepare("UPDATE EVENT SET"
222                        " start = :start"
223                        ", duration = :duration"
224                        ", xid_track = :xid_track"
225                        ", type = :type"
226                        ", language = :language"
227                        ", tag = :tag"
228                        ", title = :title"
229                        ", subtitle = :subtitle"
230                        ", abstract = :abstract"
231                        ", description = :description"
232                            " WHERE id = :id AND xid_conference = :xid_conference");
233    } else {
234        result.prepare("INSERT INTO EVENT "
235                        " (xid_conference, id, start, duration, xid_track, type, "
236                            " language, tag, title, subtitle, abstract, description) "
237                        " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
238                            ":language, :tag, :title, :subtitle, :abstract, :description)");
239    }
240    result.bindValue(":xid_conference", aEvent["conference_id"]);
241    result.bindValue(":start", QString::number(startDateTime.toTime_t()));
242    result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
243    result.bindValue(":xid_track", trackId);
244    static const QList<QString> props = QList<QString>()
245        << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
246    foreach (QString prop_name, props) {
247        result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
248    }
249    if (!result.exec()) {
250        qWarning() << "event insert/update failed:" << result.lastError();
251    }
252}
[72f6fe4]253
[dcefa71]254
[61346c9]255void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson) {
256    QSqlQuery query(db);
257    query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)");
258    query.bindValue(":xid_conference", aPerson["conference_id"]);
259    query.bindValue(":id", aPerson["id"]);
260    query.bindValue(":name", aPerson["name"]);
261    query.exec(); // TODO some queries fail due to the unique key constraint
262    // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError();
263
264    query = QSqlQuery(db);
265    query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)");
266    query.bindValue(":xid_conference", aPerson["conference_id"]);
267    query.bindValue(":xid_event", aPerson["event_id"]);
268    query.bindValue(":xid_person", aPerson["id"]);
269    query.exec(); // TODO some queries fail due to the unique key constraint
270    // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError();
[72f6fe4]271}
272
273
[61346c9]274void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom) {
275    QSqlQuery query(db);
276    query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
277    query.bindValue(":conference_id", aRoom["conference_id"]);
278    query.bindValue(":name", aRoom["name"]);
[5e50875]279    query.exec();
[61346c9]280    emitSqlQueryError(query);
281    // now we have to check whether ROOM record with 'name' exists or not,
282    // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
283    //   and assign autoincremented 'id' to aRoom
284    // - if it exists, then we need to get its 'id' and assign it to aRoom
285    aRoom["id"] = "";
286    if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
287    {
288        aRoom["id"] = query.value(0).toString();
289    }
290    else // ROOM record doesn't exist yet, need to create it
[72f6fe4]291    {
[63b2343]292        query = QSqlQuery(db);
[0ba2b59]293        query.prepare("INSERT INTO ROOM (xid_conference,name) VALUES (:xid_conference, :name)");
[61346c9]294        query.bindValue(":xid_conference", aRoom["conference_id"]);
[d942dc3]295        query.bindValue(":name", aRoom["name"]);
[5e50875]296        query.exec();
[61346c9]297        emitSqlQueryError(query);
298        aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
299        //LOG_AUTOTEST(query);
[72f6fe4]300    }
[61346c9]301
302    // remove previous conference/room records; room names might have changed
303    query = QSqlQuery(db);
304    query.prepare("DELETE FROM EVENT_ROOM WHERE xid_conference=:conference_id AND xid_event=:event_id");
305    query.bindValue(":conference_id", aRoom["conference_id"]);
306    query.bindValue(":event_id", aRoom["event_id"]);
[5e50875]307    query.exec();
[61346c9]308    emitSqlQueryError(query);
309    // and insert new ones
310    query = QSqlQuery(db);
311    query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
312    query.bindValue(":conference_id", aRoom["conference_id"]);
313    query.bindValue(":event_id", aRoom["event_id"]);
314    query.bindValue(":room_id", aRoom["id"]);
[5e50875]315    query.exec();
[61346c9]316    emitSqlQueryError(query);
[72f6fe4]317}
318
319
[61346c9]320void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink) {
[72f6fe4]321    //TODO: check if the link doesn't exist before inserting
[61346c9]322    QSqlQuery query(db);
323    query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
324    query.bindValue(":xid_event", aLink["event_id"]);
325    query.bindValue(":xid_conference", aLink["conference_id"]);
326    query.bindValue(":name", aLink["name"]);
327    query.bindValue(":url", aLink["url"]);
[5e50875]328    query.exec();
[61346c9]329    emitSqlQueryError(query);
[72f6fe4]330}
331
[990afd5]332
[61346c9]333bool SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword) {
334    if (aColumns.empty()) return false;
[990afd5]335
[e662750]336    // DROP
[61346c9]337    QSqlQuery query(db);
338    query.exec("DROP TABLE IF EXISTS SEARCH_EVENT");
339    emitSqlQueryError(query);
340
[e662750]341    // CREATE
[61346c9]342    query.exec("CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER  NOT NULL, id INTEGER NOT NULL )");
343    emitSqlQueryError(query);
344
[e662750]345    // INSERT
[a55781e]346    QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
[66698a6]347                "SELECT DISTINCT EVENT.xid_conference, EVENT.id FROM EVENT ");
[c7b58d4]348    if( aColumns.contains("ROOM") ){
[71c3eb6]349        sql += "LEFT JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
350        sql += "LEFT JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
[c7b58d4]351    }
352    if( aColumns.contains("PERSON") ){
[71c3eb6]353        sql += "LEFT JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
354        sql += "LEFT JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
[c7b58d4]355    }
[a55781e]356    sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
[c7b58d4]357
[525e2e2]358    QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
359    QStringList whereAnd;
360    for (int i=0; i < searchKeywords.count(); i++) {
361        QStringList whereOr;
362        foreach (QString table, aColumns.uniqueKeys()) {
363            foreach (QString column, aColumns.values(table)){
364                 whereOr.append(QString("%1.%2 LIKE '\%' || :%1%2%3 || '\%'").arg(table).arg(column).arg(i));
[47eda2b]365            }
[c7b58d4]366        }
[525e2e2]367        whereAnd.append(whereOr.join(" OR "));
[990afd5]368    }
[525e2e2]369    sql += whereAnd.join(") AND (");
[a55781e]370    sql += QString(")");
[990afd5]371
[a55781e]372    query.prepare(sql);
[525e2e2]373    for (int i = 0; i != searchKeywords.size(); ++i) {
374        QString keyword = searchKeywords[i];
375        foreach (QString table, aColumns.uniqueKeys()) {
376            foreach (QString column, aColumns.values(table)) {
[53effcb]377                query.bindValue(QString(":%1%2%3").arg(table).arg(column).arg(i), keyword );
[47eda2b]378            }
[a55781e]379        }
380    }
381
[61346c9]382    bool success = query.exec();
383    emitSqlQueryError(query);
384    return success;
[e662750]385}
386
[1bad318]387
[61346c9]388bool SqlEngine::beginTransaction() {
389    QSqlQuery query(db);
390    bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
391    emitSqlQueryError(query);
392    return success;
[1bad318]393}
394
395
[61346c9]396bool SqlEngine::commitTransaction() {
397    QSqlQuery query(db);
398    bool success = query.exec("COMMIT");
399    emitSqlQueryError(query);
400    return success;
[1bad318]401}
402
[d97bcab]403
[61346c9]404bool SqlEngine::deleteConference(int id) {
405    QSqlQuery query(db);
406    bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
407    emitSqlQueryError(query);
408
409    QStringList sqlList;
410    sqlList << "DELETE FROM LINK WHERE xid_conference = ?"
411            << "DELETE FROM EVENT_ROOM WHERE xid_conference = ?"
412            << "DELETE FROM EVENT_PERSON WHERE xid_conference = ?"
413            << "DELETE FROM EVENT WHERE xid_conference = ?"
414            << "DELETE FROM ROOM WHERE xid_conference = ?"
415            << "DELETE FROM PERSON WHERE xid_conference = ?"
416            << "DELETE FROM TRACK WHERE xid_conference = ?"
417            << "DELETE FROM CONFERENCE WHERE id = ?";
418
419    foreach (const QString& sql, sqlList) {
420        query.prepare(sql);
421        query.bindValue(0, id);
422        success &= query.exec();
423        emitSqlQueryError(query);
[d97bcab]424    }
425
[61346c9]426    success &= query.exec("COMMIT");
427    emitSqlQueryError(query);
[d97bcab]428
[61346c9]429    return success;
[d97bcab]430}
431
[9f367eb]432
[61346c9]433void SqlEngine::emitSqlQueryError(const QSqlQuery &query) {
434    QSqlError error = query.lastError();
435    if (error.type() == QSqlError::NoError) return;
436    emit dbError(error.text());
[d97bcab]437}
[61346c9]438
Note: See TracBrowser for help on using the repository browser.