2 * Copyright (C) 2010 Ixonos Plc.
3 * Copyright (C) 2011-2012 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 emit dbError("Upgrade 0 -> 1 not implemented yet");
89 bool SqlEngine::createCurrentDbSchema() {
90 QFile file(":/dbschema001.sql");
91 file.open(QIODevice::ReadOnly | QIODevice::Text);
92 QString allSqlStatements = file.readAll();
94 foreach(QString sql, allSqlStatements.split(";")) {
95 if (sql.trimmed().isEmpty()) // do not execute empty queries like the last character from create_tables.sql
97 if (!query.exec(sql)) {
98 emitSqlQueryError(query);
106 bool SqlEngine::createOrUpdateDbSchema() {
107 int version = dbSchemaVersion();
110 // the error has already been emitted by the previous function
114 return createCurrentDbSchema();
116 // db schema version 0
117 return updateDbSchemaVersion000To001();
122 // unsupported schema
123 emit dbError(tr("Unsupported database schema version %1.").arg(version));
129 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference, int conferenceId) {
131 if (conferenceId <= 0) // insert conference
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]);
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
148 else // update conference
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 "
153 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city" << "days")) {
154 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
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;
168 void 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"];
176 track = Track::retrieveByName(conference, name);
177 trackId = track.id();
179 catch (OrmNoObjectException &e) {
180 track.setConference(conference);
182 trackId = track.insert();
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);
188 bool event_exists = false;
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()
201 if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
208 result.prepare("UPDATE EVENT SET"
210 ", duration = :duration"
211 ", xid_track = :xid_track"
213 ", language = :language"
216 ", subtitle = :subtitle"
217 ", abstract = :abstract"
218 ", description = :description"
219 " WHERE id = :id AND xid_conference = :xid_conference");
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)");
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]);
236 if (!result.exec()) {
237 qWarning() << "event insert/update failed:" << result.lastError();
242 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson) {
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();
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();
261 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom) {
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
272 if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
274 aRoom["id"] = query.value(0).toString();
276 else // ROOM record doesn't exist yet, need to create it
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);
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);
303 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink) {
304 //TODO: check if the link doesn't exist before inserting
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);
315 bool SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword) {
316 if (aColumns.empty()) return false;
320 query.exec("DROP TABLE IF EXISTS SEARCH_EVENT");
321 emitSqlQueryError(query);
324 query.exec("CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL )");
325 emitSqlQueryError(query);
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 ) ";
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 ) ";
338 sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
340 QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
341 QStringList whereAnd;
342 for (int i=0; i < searchKeywords.count(); i++) {
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));
349 whereAnd.append(whereOr.join(" OR "));
351 sql += whereAnd.join(") AND (");
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 );
364 bool success = query.exec();
365 emitSqlQueryError(query);
370 bool SqlEngine::beginTransaction() {
372 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
373 emitSqlQueryError(query);
378 bool SqlEngine::commitTransaction() {
380 bool success = query.exec("COMMIT");
381 emitSqlQueryError(query);
386 bool SqlEngine::deleteConference(int id) {
388 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
389 emitSqlQueryError(query);
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 = ?";
401 foreach (const QString& sql, sqlList) {
403 query.bindValue(0, id);
404 success &= query.exec();
405 emitSqlQueryError(query);
408 success &= query.exec("COMMIT");
409 emitSqlQueryError(query);
415 void SqlEngine::emitSqlQueryError(const QSqlQuery &query) {
416 QSqlError error = query.lastError();
417 if (error.type() == QSqlError::NoError) return;
418 emit dbError(error.text());