2 * Copyright (C) 2010 Ixonos Plc.
3 * Copyright (C) 2011-2017 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 const QString DATE_FORMAT ("yyyy-MM-dd");
41 const QString TIME_FORMAT ("hh:mm");
43 SqlEngine::SqlEngine(QObject *aParent): QObject(aParent) {
44 #if QT_VERSION >= 0x050000
45 QDir dbPath(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
47 QDir dbPath(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
49 dbFilename = dbPath.absoluteFilePath("ConfClerk.sqlite");
53 SqlEngine::~SqlEngine() {
57 void SqlEngine::open() {
58 // we may have to create the directory of the database
59 QFileInfo dbFilenameInfo(dbFilename);
61 cwd.mkpath(dbFilenameInfo.absolutePath());
62 // We don't have to handle errors because in worst case, opening the database will fail
63 // and db.isOpen() returns false.
64 db = QSqlDatabase::addDatabase("QSQLITE");
65 db.setDatabaseName(dbFilename);
70 int SqlEngine::dbSchemaVersion() {
72 if (!query.exec("PRAGMA user_version")) {
73 emitSqlQueryError(query);
77 int version = query.value(0).toInt();
79 // check whether the tables are existing
80 if (!query.exec("select count(*) from sqlite_master where name='CONFERENCE'")) {
81 emitSqlQueryError(query);
85 if (query.value(0).toInt() == 1) return 0; // tables are existing
86 return -1; // database seems to be empty (or has other tables)
92 bool SqlEngine::updateDbSchemaVersion000To001() {
93 return applySqlFile(":/dbschema000to001.sql");
97 bool SqlEngine::createCurrentDbSchema() {
98 return applySqlFile(":/dbschema001.sql");
102 bool SqlEngine::createOrUpdateDbSchema() {
103 int version = dbSchemaVersion();
106 // the error has already been emitted by the previous function
110 return createCurrentDbSchema();
112 // db schema version 0
113 return updateDbSchemaVersion000To001();
118 // unsupported schema
119 emit dbError(tr("Unsupported database schema version %1.").arg(version));
125 bool SqlEngine::applySqlFile(const QString sqlFile) {
127 file.open(QIODevice::ReadOnly | QIODevice::Text);
128 QString allSqlStatements = file.readAll();
130 foreach(QString sql, allSqlStatements.split(";")) {
131 if (sql.trimmed().isEmpty()) // do not execute empty queries like the last character from create_tables.sql
133 if (!query.exec(sql)) {
134 emitSqlQueryError(query);
142 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference, int conferenceId) {
144 if (conferenceId <= 0) // insert conference
146 query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,"
147 "day_change,timeslot_duration,active) "
148 " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,"
149 ":day_change,:timeslot_duration,:active)");
150 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) {
151 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
153 query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
154 query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
155 query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
156 query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
157 query.bindValue(":active", 1);
159 emitSqlQueryError(query);
160 aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
162 else // update conference
164 query.prepare("UPDATE CONFERENCE set title=:title, url=:url, subtitle=:subtitle, venue=:venue, city=:city, start=:start, end=:end,"
165 "day_change=:day_change, timeslot_duration=:timeslot_duration, active=:active "
167 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) {
168 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
170 query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
171 query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
172 query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
173 query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
174 query.bindValue(":active", 1);
175 query.bindValue(":id", conferenceId);
177 emitSqlQueryError(query);
178 aConference["id"] = QVariant(conferenceId).toString();
183 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent) {
184 int conferenceId = aEvent["conference_id"].toInt();
185 Conference conference = Conference::getById(conferenceId);
187 // insert event track to table and get track id
190 QString trackName = aEvent["track"];
191 if (trackName.isEmpty()) trackName = tr("No track");
194 track = Track::retrieveByName(conferenceId, trackName);
195 trackId = track.id();
197 catch (OrmNoObjectException &e) {
198 track.setConference(conferenceId);
199 track.setName(trackName);
200 trackId = track.insert();
202 QDate startDate = QDate::fromString(aEvent["date"], DATE_FORMAT);
203 QTime startTime = QTime::fromString(aEvent["start"], TIME_FORMAT);
204 // consider day_change (note that if day_change is e.g. at 04:00 AM, an event starting at 02:00 AM has the previous date in the XML file)
205 if (startTime < conference.dayChangeTime()) startDate = startDate.addDays(1);
206 QDateTime startDateTime;
207 startDateTime.setTimeSpec(Qt::UTC);
208 startDateTime = QDateTime(startDate, startTime, Qt::UTC);
210 bool event_exists = false;
212 QSqlQuery check_event_query;
213 check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
214 check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
215 check_event_query.bindValue(":id", aEvent["id"]);
216 if (!check_event_query.exec()) {
217 qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
218 << "event id:" << aEvent["id"]
219 << "error:" << check_event_query.lastError()
223 if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
230 result.prepare("UPDATE EVENT SET"
232 ", duration = :duration"
233 ", xid_track = :xid_track"
235 ", language = :language"
238 ", subtitle = :subtitle"
239 ", abstract = :abstract"
240 ", description = :description"
241 " WHERE id = :id AND xid_conference = :xid_conference");
243 result.prepare("INSERT INTO EVENT "
244 " (xid_conference, id, start, duration, xid_track, type, "
245 " language, tag, title, subtitle, abstract, description) "
246 " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
247 ":language, :tag, :title, :subtitle, :abstract, :description)");
249 result.bindValue(":xid_conference", aEvent["conference_id"]);
250 result.bindValue(":start", QString::number(startDateTime.toTime_t()));
251 result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
252 result.bindValue(":xid_track", trackId);
253 static const QList<QString> props = QList<QString>()
254 << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
255 foreach (QString prop_name, props) {
256 result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
258 if (!result.exec()) {
259 qWarning() << "event insert/update failed:" << result.lastError();
264 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson) {
266 query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)");
267 query.bindValue(":xid_conference", aPerson["conference_id"]);
268 query.bindValue(":id", aPerson["id"]);
269 query.bindValue(":name", aPerson["name"]);
270 query.exec(); // TODO some queries fail due to the unique key constraint
271 // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError();
273 query = QSqlQuery(db);
274 query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)");
275 query.bindValue(":xid_conference", aPerson["conference_id"]);
276 query.bindValue(":xid_event", aPerson["event_id"]);
277 query.bindValue(":xid_person", aPerson["id"]);
278 query.exec(); // TODO some queries fail due to the unique key constraint
279 // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError();
283 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom) {
285 query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
286 query.bindValue(":conference_id", aRoom["conference_id"]);
287 query.bindValue(":name", aRoom["name"]);
289 emitSqlQueryError(query);
290 // now we have to check whether ROOM record with 'name' exists or not,
291 // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
292 // and assign autoincremented 'id' to aRoom
293 // - if it exists, then we need to get its 'id' and assign it to aRoom
295 if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
297 aRoom["id"] = query.value(0).toString();
299 else // ROOM record doesn't exist yet, need to create it
301 query = QSqlQuery(db);
302 query.prepare("INSERT INTO ROOM (xid_conference,name) VALUES (:xid_conference, :name)");
303 query.bindValue(":xid_conference", aRoom["conference_id"]);
304 query.bindValue(":name", aRoom["name"]);
306 emitSqlQueryError(query);
307 aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
308 //LOG_AUTOTEST(query);
311 // remove previous conference/room records; room names might have changed
312 query = QSqlQuery(db);
313 query.prepare("DELETE FROM EVENT_ROOM WHERE xid_conference=:conference_id AND xid_event=:event_id");
314 query.bindValue(":conference_id", aRoom["conference_id"]);
315 query.bindValue(":event_id", aRoom["event_id"]);
317 emitSqlQueryError(query);
318 // and insert new ones
319 query = QSqlQuery(db);
320 query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
321 query.bindValue(":conference_id", aRoom["conference_id"]);
322 query.bindValue(":event_id", aRoom["event_id"]);
323 query.bindValue(":room_id", aRoom["id"]);
325 emitSqlQueryError(query);
329 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink) {
330 //TODO: check if the link doesn't exist before inserting
332 query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
333 query.bindValue(":xid_event", aLink["event_id"]);
334 query.bindValue(":xid_conference", aLink["conference_id"]);
335 query.bindValue(":name", aLink["name"]);
336 query.bindValue(":url", aLink["url"]);
338 emitSqlQueryError(query);
342 bool SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword) {
343 if (aColumns.empty()) return false;
347 query.exec("DROP TABLE IF EXISTS SEARCH_EVENT");
348 emitSqlQueryError(query);
351 query.exec("CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL )");
352 emitSqlQueryError(query);
355 QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
356 "SELECT DISTINCT EVENT.xid_conference, EVENT.id FROM EVENT ");
357 if( aColumns.contains("ROOM") ){
358 sql += "LEFT JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
359 sql += "LEFT JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
361 if( aColumns.contains("PERSON") ){
362 sql += "LEFT JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
363 sql += "LEFT JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
365 sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
367 QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
368 QStringList whereAnd;
369 for (int i=0; i < searchKeywords.count(); i++) {
371 foreach (QString table, aColumns.uniqueKeys()) {
372 foreach (QString column, aColumns.values(table)){
373 whereOr.append(QString("%1.%2 LIKE '\%' || :%1%2%3 || '\%'").arg(table).arg(column).arg(i));
376 whereAnd.append(whereOr.join(" OR "));
378 sql += whereAnd.join(") AND (");
382 for (int i = 0; i != searchKeywords.size(); ++i) {
383 QString keyword = searchKeywords[i];
384 foreach (QString table, aColumns.uniqueKeys()) {
385 foreach (QString column, aColumns.values(table)) {
386 query.bindValue(QString(":%1%2%3").arg(table).arg(column).arg(i), keyword );
391 bool success = query.exec();
392 emitSqlQueryError(query);
397 bool SqlEngine::beginTransaction() {
399 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
400 emitSqlQueryError(query);
405 bool SqlEngine::commitTransaction() {
407 bool success = query.exec("COMMIT");
408 emitSqlQueryError(query);
413 bool SqlEngine::deleteConference(int id) {
415 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
416 emitSqlQueryError(query);
419 sqlList << "DELETE FROM LINK WHERE xid_conference = ?"
420 << "DELETE FROM EVENT_ROOM WHERE xid_conference = ?"
421 << "DELETE FROM EVENT_PERSON WHERE xid_conference = ?"
422 << "DELETE FROM EVENT WHERE xid_conference = ?"
423 << "DELETE FROM ROOM WHERE xid_conference = ?"
424 << "DELETE FROM PERSON WHERE xid_conference = ?"
425 << "DELETE FROM TRACK WHERE xid_conference = ?"
426 << "DELETE FROM CONFERENCE WHERE id = ?";
428 foreach (const QString& sql, sqlList) {
430 query.bindValue(0, id);
431 success &= query.exec();
432 emitSqlQueryError(query);
435 success &= query.exec("COMMIT");
436 emitSqlQueryError(query);
442 void SqlEngine::emitSqlQueryError(const QSqlQuery &query) {
443 QSqlError error = query.lastError();
444 if (error.type() == QSqlError::NoError) return;
445 emit dbError(error.text());