source: src/sql/sqlengine.cpp @ 7ba0378

Last change on this file since 7ba0378 was 7ba0378, checked in by Philipp Spitzer <philipp@…>, 5 years ago

Import schedules with dates attached to events correctly.

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