2 * Copyright (C) 2010 Ixonos Plc.
3 * Copyright (C) 2011-2013 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/>.
28 #include <QDesktopServices>
29 #include "sqlengine.h"
31 #include "conference.h"
35 const QString DATE_FORMAT ("yyyy-MM-dd");
36 const QString TIME_FORMAT ("hh:mm");
38 SqlEngine::SqlEngine(QObject *aParent): QObject(aParent) {
39 QDir dbPath(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
40 dbFilename = dbPath.absoluteFilePath("ConfClerk.sqlite");
44 SqlEngine::~SqlEngine() {
48 void SqlEngine::open() {
49 // we may have to create the directory of the database
50 QFileInfo dbFilenameInfo(dbFilename);
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);
61 int SqlEngine::dbSchemaVersion() {
63 if (!query.exec("PRAGMA user_version")) {
64 emitSqlQueryError(query);
68 int version = query.value(0).toInt();
70 // check whether the tables are existing
71 if (!query.exec("select count(*) from sqlite_master where name='CONFERENCE'")) {
72 emitSqlQueryError(query);
76 if (query.value(0).toInt() == 1) return 0; // tables are existing
77 return -1; // database seems to be empty (or has other tables)
83 bool SqlEngine::updateDbSchemaVersion000To001() {
84 return applySqlFile(":/dbschema000to001.sql");
88 bool SqlEngine::createCurrentDbSchema() {
89 return applySqlFile(":/dbschema001.sql");
93 bool SqlEngine::createOrUpdateDbSchema() {
94 int version = dbSchemaVersion();
97 // the error has already been emitted by the previous function
101 return createCurrentDbSchema();
103 // db schema version 0
104 return updateDbSchemaVersion000To001();
109 // unsupported schema
110 emit dbError(tr("Unsupported database schema version %1.").arg(version));
116 bool SqlEngine::applySqlFile(const QString sqlFile) {
118 file.open(QIODevice::ReadOnly | QIODevice::Text);
119 QString allSqlStatements = file.readAll();
121 foreach(QString sql, allSqlStatements.split(";")) {
122 if (sql.trimmed().isEmpty()) // do not execute empty queries like the last character from create_tables.sql
124 if (!query.exec(sql)) {
125 emitSqlQueryError(query);
133 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference, int conferenceId) {
135 if (conferenceId <= 0) // insert conference
137 query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,"
138 "day_change,timeslot_duration,active) "
139 " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,"
140 ":day_change,:timeslot_duration,:active)");
141 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) {
142 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
144 query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
145 query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
146 query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
147 query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
148 query.bindValue(":active", 1);
150 emitSqlQueryError(query);
151 aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
153 else // update conference
155 query.prepare("UPDATE CONFERENCE set title=:title, url=:url, subtitle=:subtitle, venue=:venue, city=:city, start=:start, end=:end,"
156 "day_change=:day_change, timeslot_duration=:timeslot_duration, active=:active "
158 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) {
159 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
161 query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
162 query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
163 query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
164 query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
165 query.bindValue(":active", 1);
166 query.bindValue(":id", conferenceId);
168 emitSqlQueryError(query);
169 aConference["id"] = QVariant(conferenceId).toString();
174 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent) {
175 //insert event track to table and get track id
176 int conference = aEvent["conference_id"].toInt();
177 QString name = aEvent["track"];
182 track = Track::retrieveByName(conference, name);
183 trackId = track.id();
185 catch (OrmNoObjectException &e) {
186 track.setConference(conference);
188 trackId = track.insert();
190 QDateTime startDateTime;
191 startDateTime.setTimeSpec(Qt::UTC);
192 startDateTime = QDateTime(QDate::fromString(aEvent["date"],DATE_FORMAT),QTime::fromString(aEvent["start"],TIME_FORMAT),Qt::UTC);
194 bool event_exists = false;
196 QSqlQuery check_event_query;
197 check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
198 check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
199 check_event_query.bindValue(":id", aEvent["id"]);
200 if (!check_event_query.exec()) {
201 qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
202 << "event id:" << aEvent["id"]
203 << "error:" << check_event_query.lastError()
207 if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
214 result.prepare("UPDATE EVENT SET"
216 ", duration = :duration"
217 ", xid_track = :xid_track"
219 ", language = :language"
222 ", subtitle = :subtitle"
223 ", abstract = :abstract"
224 ", description = :description"
225 " WHERE id = :id AND xid_conference = :xid_conference");
227 result.prepare("INSERT INTO EVENT "
228 " (xid_conference, id, start, duration, xid_track, type, "
229 " language, tag, title, subtitle, abstract, description) "
230 " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
231 ":language, :tag, :title, :subtitle, :abstract, :description)");
233 result.bindValue(":xid_conference", aEvent["conference_id"]);
234 result.bindValue(":start", QString::number(startDateTime.toTime_t()));
235 result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
236 result.bindValue(":xid_track", trackId);
237 static const QList<QString> props = QList<QString>()
238 << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
239 foreach (QString prop_name, props) {
240 result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
242 if (!result.exec()) {
243 qWarning() << "event insert/update failed:" << result.lastError();
248 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson) {
250 query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)");
251 query.bindValue(":xid_conference", aPerson["conference_id"]);
252 query.bindValue(":id", aPerson["id"]);
253 query.bindValue(":name", aPerson["name"]);
254 query.exec(); // TODO some queries fail due to the unique key constraint
255 // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError();
257 query = QSqlQuery(db);
258 query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)");
259 query.bindValue(":xid_conference", aPerson["conference_id"]);
260 query.bindValue(":xid_event", aPerson["event_id"]);
261 query.bindValue(":xid_person", aPerson["id"]);
262 query.exec(); // TODO some queries fail due to the unique key constraint
263 // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError();
267 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom) {
269 query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
270 query.bindValue(":conference_id", aRoom["conference_id"]);
271 query.bindValue(":name", aRoom["name"]);
273 emitSqlQueryError(query);
274 // now we have to check whether ROOM record with 'name' exists or not,
275 // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
276 // and assign autoincremented 'id' to aRoom
277 // - if it exists, then we need to get its 'id' and assign it to aRoom
279 if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
281 aRoom["id"] = query.value(0).toString();
283 else // ROOM record doesn't exist yet, need to create it
285 query = QSqlQuery(db);
286 query.prepare("INSERT INTO ROOM (xid_conference,name) VALUES (:xid_conference, :name)");
287 query.bindValue(":xid_conference", aRoom["conference_id"]);
288 query.bindValue(":xid_name", aRoom["name"]);
290 emitSqlQueryError(query);
291 aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
292 //LOG_AUTOTEST(query);
295 // remove previous conference/room records; room names might have changed
296 query = QSqlQuery(db);
297 query.prepare("DELETE FROM EVENT_ROOM WHERE xid_conference=:conference_id AND xid_event=:event_id");
298 query.bindValue(":conference_id", aRoom["conference_id"]);
299 query.bindValue(":event_id", aRoom["event_id"]);
301 emitSqlQueryError(query);
302 // and insert new ones
303 query = QSqlQuery(db);
304 query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
305 query.bindValue(":conference_id", aRoom["conference_id"]);
306 query.bindValue(":event_id", aRoom["event_id"]);
307 query.bindValue(":room_id", aRoom["id"]);
309 emitSqlQueryError(query);
313 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink) {
314 //TODO: check if the link doesn't exist before inserting
316 query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
317 query.bindValue(":xid_event", aLink["event_id"]);
318 query.bindValue(":xid_conference", aLink["conference_id"]);
319 query.bindValue(":name", aLink["name"]);
320 query.bindValue(":url", aLink["url"]);
322 emitSqlQueryError(query);
326 bool SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword) {
327 if (aColumns.empty()) return false;
331 query.exec("DROP TABLE IF EXISTS SEARCH_EVENT");
332 emitSqlQueryError(query);
335 query.exec("CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL )");
336 emitSqlQueryError(query);
339 QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
340 "SELECT DISTINCT EVENT.xid_conference, EVENT.id FROM EVENT ");
341 if( aColumns.contains("ROOM") ){
342 sql += "LEFT JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
343 sql += "LEFT JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
345 if( aColumns.contains("PERSON") ){
346 sql += "LEFT JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
347 sql += "LEFT JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
349 sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
351 QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
352 QStringList whereAnd;
353 for (int i=0; i < searchKeywords.count(); i++) {
355 foreach (QString table, aColumns.uniqueKeys()) {
356 foreach (QString column, aColumns.values(table)){
357 whereOr.append(QString("%1.%2 LIKE '\%' || :%1%2%3 || '\%'").arg(table).arg(column).arg(i));
360 whereAnd.append(whereOr.join(" OR "));
362 sql += whereAnd.join(") AND (");
366 for (int i = 0; i != searchKeywords.size(); ++i) {
367 QString keyword = searchKeywords[i];
368 foreach (QString table, aColumns.uniqueKeys()) {
369 foreach (QString column, aColumns.values(table)) {
370 query.bindValue(QString(":%1%2%3").arg(table).arg(column).arg(i), keyword );
375 bool success = query.exec();
376 emitSqlQueryError(query);
381 bool SqlEngine::beginTransaction() {
383 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
384 emitSqlQueryError(query);
389 bool SqlEngine::commitTransaction() {
391 bool success = query.exec("COMMIT");
392 emitSqlQueryError(query);
397 bool SqlEngine::deleteConference(int id) {
399 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
400 emitSqlQueryError(query);
403 sqlList << "DELETE FROM LINK WHERE xid_conference = ?"
404 << "DELETE FROM EVENT_ROOM WHERE xid_conference = ?"
405 << "DELETE FROM EVENT_PERSON WHERE xid_conference = ?"
406 << "DELETE FROM EVENT WHERE xid_conference = ?"
407 << "DELETE FROM ROOM WHERE xid_conference = ?"
408 << "DELETE FROM PERSON WHERE xid_conference = ?"
409 << "DELETE FROM TRACK WHERE xid_conference = ?"
410 << "DELETE FROM CONFERENCE WHERE id = ?";
412 foreach (const QString& sql, sqlList) {
414 query.bindValue(0, id);
415 success &= query.exec();
416 emitSqlQueryError(query);
419 success &= query.exec("COMMIT");
420 emitSqlQueryError(query);
426 void SqlEngine::emitSqlQueryError(const QSqlQuery &query) {
427 QSqlError error = query.lastError();
428 if (error.type() == QSqlError::NoError) return;
429 emit dbError(error.text());