source: confclerk_git/src/sql/sqlengine.cpp @ 0ba2b59

qt5
Last change on this file since 0ba2b59 was 0ba2b59, checked in by gregor herrmann <gregoa@…>, 10 years ago

Don't insert empty string into picture column.

(NOT NULL constraint removed from db schema.)

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