source: src/sql/sqlengine.cpp @ d03ca41

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

If no day_change was given for a conference 4 AM is assumed.

Fixes #53.

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