2 * Copyright (C) 2010 Ixonos Plc.
3 * Copyright (C) 2011-2021 Philipp Spitzer, gregor herrmann, Stefan Stahl
5 * This file is part of ConfClerk.
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)
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
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/>.
27 #if QT_VERSION >= 0x050000
28 #include <QStandardPaths>
30 #include <QDesktopServices>
34 #include "sqlengine.h"
36 #include "conference.h"
40 SqlEngine::SqlEngine(QObject *aParent): QObject(aParent), DATE_FORMAT("yyyy-MM-dd"), TIME_FORMAT("hh:mm") {
41 #if QT_VERSION >= 0x050000
42 QDir dbPath(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
44 QDir dbPath(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
46 dbFilename = dbPath.absoluteFilePath("ConfClerk.sqlite");
50 SqlEngine::~SqlEngine() {
54 void SqlEngine::open() {
55 // we may have to create the directory of the database
56 QFileInfo dbFilenameInfo(dbFilename);
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);
67 int SqlEngine::dbSchemaVersion() {
69 if (!query.exec("PRAGMA user_version")) {
70 emitSqlQueryError(query);
74 int version = query.value(0).toInt();
76 // check whether the tables are existing
77 if (!query.exec("select count(*) from sqlite_master where name='CONFERENCE'")) {
78 emitSqlQueryError(query);
82 if (query.value(0).toInt() == 1) return 0; // tables are existing
83 return -1; // database seems to be empty (or has other tables)
89 bool SqlEngine::updateDbSchemaVersion000To001() {
90 return applySqlFile(":/dbschema000to001.sql");
94 bool SqlEngine::updateDbSchemaVersion001To002() {
95 return applySqlFile(":/dbschema001to002.sql");
99 bool SqlEngine::createCurrentDbSchema() {
100 return applySqlFile(":/dbschema002.sql");
104 bool SqlEngine::createOrUpdateDbSchema() {
105 int version = dbSchemaVersion();
108 // the error has already been emitted by the previous function
112 return createCurrentDbSchema();
114 // db schema version 0
115 return updateDbSchemaVersion000To001();
117 // db schema version 1
118 return updateDbSchemaVersion001To002();
123 // unsupported schema
124 emit dbError(tr("Unsupported database schema version %1.").arg(version));
130 bool SqlEngine::applySqlFile(const QString sqlFile) {
132 file.open(QIODevice::ReadOnly | QIODevice::Text);
133 QString allSqlStatements = file.readAll();
135 foreach(QString sql, allSqlStatements.split(";")) {
136 if (sql.trimmed().isEmpty()) // do not execute empty queries like the last character from create_tables.sql
138 if (!query.exec(sql)) {
139 emitSqlQueryError(query);
147 QDateTime parseDateIgnoreTime(QString dateStr) {
148 QDateTime dateTime = QDateTime::fromString(dateStr, Qt::DateFormat::ISODate);
149 dateTime.setOffsetFromUtc(0);
154 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference, int conferenceId, bool omit_display_time_shift) {
156 bool insert = conferenceId <= 0;
157 if (insert) { // insert conference
158 query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,"
159 "day_change,timeslot_duration,utc_offset,display_time_shift,active) "
160 " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,"
161 ":day_change,:timeslot_duration,:utc_offset,:display_time_shift,:active)");
162 } else { // update conference
163 QString update = "UPDATE CONFERENCE set title=:title, url=:url, subtitle=:subtitle, venue=:venue, city=:city, start=:start, end=:end, "
164 "day_change=:day_change, timeslot_duration=:timeslot_duration, utc_offset=:utc_offset";
165 if (!omit_display_time_shift) update += ", display_time_shift=:display_time_shift";
166 update += ", active=:active WHERE id=:id";
167 query.prepare(update);
169 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) {
170 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
172 query.bindValue(":start", parseDateIgnoreTime(aConference["start"]).toTime_t());
173 query.bindValue(":end", parseDateIgnoreTime(aConference["end"]).toTime_t());
174 QTime dayChange = QTime::fromString(aConference["day_change"].left(TIME_FORMAT.size()), TIME_FORMAT);
175 query.bindValue(":day_change", QTime(0, 0).secsTo(dayChange));
176 query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
178 if (!aConference.value("utc_offset").isEmpty()) utc_offset = aConference["utc_offset"].toInt();
179 query.bindValue(":utc_offset", utc_offset);
180 if (!omit_display_time_shift) {
181 QVariant display_time_shift;
182 if (!aConference.value("display_time_shift").isEmpty()) display_time_shift = aConference["display_time_shift"].toInt();
183 query.bindValue(":display_time_shift", display_time_shift);
185 query.bindValue(":active", 1);
186 if (!insert) query.bindValue(":id", conferenceId);
188 emitSqlQueryError(query);
190 aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
192 aConference["id"] = QVariant(conferenceId).toString();
197 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent) {
198 int conferenceId = aEvent["conference_id"].toInt();
199 Conference conference = Conference::getById(conferenceId);
201 // insert event track to table and get track id
204 QString trackName = aEvent["track"];
205 if (trackName.isEmpty()) trackName = tr("No track");
208 track = Track::retrieveByName(conferenceId, trackName);
209 trackId = track.id();
211 catch (OrmNoObjectException &e) {
212 track.setConference(conferenceId);
213 track.setName(trackName);
214 trackId = track.insert();
216 QDate startDate = QDate::fromString(aEvent["date"], DATE_FORMAT);
217 QTime startTime = QTime::fromString(aEvent["start"], TIME_FORMAT);
218 QDateTime startDateTime;
219 startDateTime.setTimeSpec(Qt::UTC);
220 startDateTime = QDateTime(startDate, startTime, Qt::UTC);
222 bool event_exists = false;
224 QSqlQuery check_event_query;
225 check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
226 check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
227 check_event_query.bindValue(":id", aEvent["id"]);
228 if (!check_event_query.exec()) {
229 qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
230 << "event id:" << aEvent["id"]
231 << "error:" << check_event_query.lastError()
235 if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
242 result.prepare("UPDATE EVENT SET"
244 ", duration = :duration"
245 ", xid_track = :xid_track"
247 ", language = :language"
250 ", subtitle = :subtitle"
251 ", abstract = :abstract"
252 ", description = :description"
253 " WHERE id = :id AND xid_conference = :xid_conference");
255 result.prepare("INSERT INTO EVENT "
256 " (xid_conference, id, start, duration, xid_track, type, "
257 " language, tag, title, subtitle, abstract, description) "
258 " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
259 ":language, :tag, :title, :subtitle, :abstract, :description)");
261 result.bindValue(":xid_conference", aEvent["conference_id"]);
262 result.bindValue(":start", QString::number(startDateTime.toTime_t()));
263 result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
264 result.bindValue(":xid_track", trackId);
265 static const QList<QString> props = QList<QString>()
266 << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
267 foreach (QString prop_name, props) {
268 result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
270 if (!result.exec()) {
271 qWarning() << "event insert/update failed:" << result.lastError();
276 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson) {
278 query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)");
279 query.bindValue(":xid_conference", aPerson["conference_id"]);
280 query.bindValue(":id", aPerson["id"]);
281 query.bindValue(":name", aPerson["name"]);
282 query.exec(); // TODO some queries fail due to the unique key constraint
283 // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError();
285 query = QSqlQuery(db);
286 query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)");
287 query.bindValue(":xid_conference", aPerson["conference_id"]);
288 query.bindValue(":xid_event", aPerson["event_id"]);
289 query.bindValue(":xid_person", aPerson["id"]);
290 query.exec(); // TODO some queries fail due to the unique key constraint
291 // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError();
295 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom) {
297 query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
298 query.bindValue(":conference_id", aRoom["conference_id"]);
299 query.bindValue(":name", aRoom["name"]);
301 emitSqlQueryError(query);
302 // now we have to check whether ROOM record with 'name' exists or not,
303 // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
304 // and assign autoincremented 'id' to aRoom
305 // - if it exists, then we need to get its 'id' and assign it to aRoom
307 if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
309 aRoom["id"] = query.value(0).toString();
311 else // ROOM record doesn't exist yet, need to create it
313 query = QSqlQuery(db);
314 query.prepare("INSERT INTO ROOM (xid_conference,name) VALUES (:xid_conference, :name)");
315 query.bindValue(":xid_conference", aRoom["conference_id"]);
316 query.bindValue(":name", aRoom["name"]);
318 emitSqlQueryError(query);
319 aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
320 //LOG_AUTOTEST(query);
323 // remove previous conference/room records; room names might have changed
324 query = QSqlQuery(db);
325 query.prepare("DELETE FROM EVENT_ROOM WHERE xid_conference=:conference_id AND xid_event=:event_id");
326 query.bindValue(":conference_id", aRoom["conference_id"]);
327 query.bindValue(":event_id", aRoom["event_id"]);
329 emitSqlQueryError(query);
330 // and insert new ones
331 query = QSqlQuery(db);
332 query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
333 query.bindValue(":conference_id", aRoom["conference_id"]);
334 query.bindValue(":event_id", aRoom["event_id"]);
335 query.bindValue(":room_id", aRoom["id"]);
337 emitSqlQueryError(query);
341 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink) {
342 //TODO: check if the link doesn't exist before inserting
344 query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
345 query.bindValue(":xid_event", aLink["event_id"]);
346 query.bindValue(":xid_conference", aLink["conference_id"]);
347 query.bindValue(":name", aLink["name"]);
348 query.bindValue(":url", aLink["url"]);
350 emitSqlQueryError(query);
354 bool SqlEngine::searchEvent(int aConferenceId, const QMultiHash<QString,QString> &aColumns, const QString &aKeyword) {
355 if (aColumns.empty()) return false;
359 query.exec("DROP TABLE IF EXISTS SEARCH_EVENT");
360 emitSqlQueryError(query);
363 query.exec("CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL )");
364 emitSqlQueryError(query);
367 QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
368 "SELECT DISTINCT EVENT.xid_conference, EVENT.id FROM EVENT ");
369 if( aColumns.contains("ROOM") ){
370 sql += "LEFT JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
371 sql += "LEFT JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
373 if( aColumns.contains("PERSON") ){
374 sql += "LEFT JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
375 sql += "LEFT JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
377 sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
379 QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
380 QStringList whereAnd;
381 for (int i=0; i < searchKeywords.count(); i++) {
383 foreach (QString table, aColumns.uniqueKeys()) {
384 foreach (QString column, aColumns.values(table)){
385 whereOr.append(QString("%1.%2 LIKE '\%' || :%1%2%3 || '\%'").arg(table).arg(column).arg(i));
388 whereAnd.append(whereOr.join(" OR "));
390 sql += whereAnd.join(") AND (");
394 for (int i = 0; i != searchKeywords.size(); ++i) {
395 QString keyword = searchKeywords[i];
396 foreach (QString table, aColumns.uniqueKeys()) {
397 foreach (QString column, aColumns.values(table)) {
398 query.bindValue(QString(":%1%2%3").arg(table).arg(column).arg(i), keyword );
403 bool success = query.exec();
404 emitSqlQueryError(query);
409 bool SqlEngine::beginTransaction() {
411 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
412 emitSqlQueryError(query);
417 bool SqlEngine::commitTransaction() {
419 bool success = query.exec("COMMIT");
420 emitSqlQueryError(query);
425 bool SqlEngine::rollbackTransaction() {
427 bool success = query.exec("ROLLBACK");
428 emitSqlQueryError(query);
433 bool SqlEngine::deleteConference(int id) {
435 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
436 emitSqlQueryError(query);
439 sqlList << "DELETE FROM LINK WHERE xid_conference = ?"
440 << "DELETE FROM EVENT_ROOM WHERE xid_conference = ?"
441 << "DELETE FROM EVENT_PERSON WHERE xid_conference = ?"
442 << "DELETE FROM EVENT WHERE xid_conference = ?"
443 << "DELETE FROM ROOM WHERE xid_conference = ?"
444 << "DELETE FROM PERSON WHERE xid_conference = ?"
445 << "DELETE FROM TRACK WHERE xid_conference = ?"
446 << "DELETE FROM CONFERENCE WHERE id = ?";
448 foreach (const QString& sql, sqlList) {
450 query.bindValue(0, id);
451 success &= query.exec();
452 emitSqlQueryError(query);
455 success &= query.exec("COMMIT");
456 emitSqlQueryError(query);
462 bool SqlEngine::deleteStaleEvents(int conferenceId, QSet<QString> eventIdsToKeep) {
465 // get all event IDs from conference
466 query.prepare("SELECT id FROM event WHERE xid_conference = ?");
467 query.bindValue(0, conferenceId);
468 bool success = query.exec();
469 emitSqlQueryError(query);
470 if (!success) return false;
471 QSet<QString> existingEventIds;
472 while (query.next()) existingEventIds.insert(query.value(0).toString());
474 // determine events that are not existing anymore
475 QSet<QString> eventIdsToRemove = existingEventIds.subtract(eventIdsToKeep);
477 // delete events including entries from referencing tables
478 QList<QString> tables = {"link", "event_room", "event_person"};
479 for(const QString& eventId: eventIdsToRemove) {
480 for(const QString& table: tables) {
481 query.prepare(QString("DELETE FROM %1 WHERE xid_conference = ? AND xid_event = ?").arg(table));
482 query.bindValue(0, conferenceId);
483 query.bindValue(1, eventId);
484 success &= query.exec();
485 emitSqlQueryError(query);
487 query.prepare("DELETE FROM event WHERE xid_conference = ? AND id = ?");
488 query.bindValue(0, conferenceId);
489 query.bindValue(1, eventId);
490 success &= query.exec();
491 emitSqlQueryError(query);
498 void SqlEngine::emitSqlQueryError(const QSqlQuery &query) {
499 QSqlError error = query.lastError();
500 if (error.type() == QSqlError::NoError) return;
501 emit dbError(error.text());