source: confclerk_git/src/sql/sqlengine.cpp @ 5e50875

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

Fixed: Forgot to call query.exec() at several places.

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