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,"
134 "day_change,timeslot_duration,active) "
135 " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,"
136 ":day_change,:timeslot_duration,:active)");
137 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) {
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);
146 emitSqlQueryError(query);
147 aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
149 else // update conference
151 query.prepare("UPDATE CONFERENCE set title=:title, url=:url, subtitle=:subtitle, venue=:venue, city=:city, start=:start, end=:end,"
152 "day_change=:day_change, timeslot_duration=:timeslot_duration, active=:active "
154 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) {
155 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
157 query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
158 query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
159 query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
160 query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
161 query.bindValue(":active", 1);
162 query.bindValue(":id", conferenceId);
164 emitSqlQueryError(query);
165 aConference["id"] = conferenceId;
170 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent) {
171 //insert event track to table and get track id
172 int conference = aEvent["conference_id"].toInt();
173 QString name = aEvent["track"];
178 track = Track::retrieveByName(conference, name);
179 trackId = track.id();
181 catch (OrmNoObjectException &e) {
182 track.setConference(conference);
184 trackId = track.insert();
186 QDateTime startDateTime;
187 startDateTime.setTimeSpec(Qt::UTC);
188 startDateTime = QDateTime(QDate::fromString(aEvent["date"],DATE_FORMAT),QTime::fromString(aEvent["start"],TIME_FORMAT),Qt::UTC);
190 bool event_exists = false;
192 QSqlQuery check_event_query;
193 check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
194 check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
195 check_event_query.bindValue(":id", aEvent["id"]);
196 if (!check_event_query.exec()) {
197 qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
198 << "event id:" << aEvent["id"]
199 << "error:" << check_event_query.lastError()
203 if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
210 result.prepare("UPDATE EVENT SET"
212 ", duration = :duration"
213 ", xid_track = :xid_track"
215 ", language = :language"
218 ", subtitle = :subtitle"
219 ", abstract = :abstract"
220 ", description = :description"
221 " WHERE id = :id AND xid_conference = :xid_conference");
223 result.prepare("INSERT INTO EVENT "
224 " (xid_conference, id, start, duration, xid_track, type, "
225 " language, tag, title, subtitle, abstract, description) "
226 " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
227 ":language, :tag, :title, :subtitle, :abstract, :description)");
229 result.bindValue(":xid_conference", aEvent["conference_id"]);
230 result.bindValue(":start", QString::number(startDateTime.toTime_t()));
231 result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
232 result.bindValue(":xid_track", trackId);
233 static const QList<QString> props = QList<QString>()
234 << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
235 foreach (QString prop_name, props) {
236 result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
238 if (!result.exec()) {
239 qWarning() << "event insert/update failed:" << result.lastError();
244 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson) {
246 query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)");
247 query.bindValue(":xid_conference", aPerson["conference_id"]);
248 query.bindValue(":id", aPerson["id"]);
249 query.bindValue(":name", aPerson["name"]);
250 query.exec(); // TODO some queries fail due to the unique key constraint
251 // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError();
253 query = QSqlQuery(db);
254 query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)");
255 query.bindValue(":xid_conference", aPerson["conference_id"]);
256 query.bindValue(":xid_event", aPerson["event_id"]);
257 query.bindValue(":xid_person", aPerson["id"]);
258 query.exec(); // TODO some queries fail due to the unique key constraint
259 // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError();
263 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom) {
265 query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
266 query.bindValue(":conference_id", aRoom["conference_id"]);
267 query.bindValue(":name", aRoom["name"]);
269 emitSqlQueryError(query);
270 // now we have to check whether ROOM record with 'name' exists or not,
271 // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
272 // and assign autoincremented 'id' to aRoom
273 // - if it exists, then we need to get its 'id' and assign it to aRoom
275 if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
277 aRoom["id"] = query.value(0).toString();
279 else // ROOM record doesn't exist yet, need to create it
281 query = QSqlQuery(db);
282 query.prepare("INSERT INTO ROOM (xid_conference,name) VALUES (:xid_conference, :name)");
283 query.bindValue(":xid_conference", aRoom["conference_id"]);
284 query.bindValue(":xid_name", aRoom["name"]);
286 emitSqlQueryError(query);
287 aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
288 //LOG_AUTOTEST(query);
291 // remove previous conference/room records; room names might have changed
292 query = QSqlQuery(db);
293 query.prepare("DELETE FROM EVENT_ROOM WHERE xid_conference=:conference_id AND xid_event=:event_id");
294 query.bindValue(":conference_id", aRoom["conference_id"]);
295 query.bindValue(":event_id", aRoom["event_id"]);
297 emitSqlQueryError(query);
298 // and insert new ones
299 query = QSqlQuery(db);
300 query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
301 query.bindValue(":conference_id", aRoom["conference_id"]);
302 query.bindValue(":event_id", aRoom["event_id"]);
303 query.bindValue(":room_id", aRoom["id"]);
305 emitSqlQueryError(query);
309 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink) {
310 //TODO: check if the link doesn't exist before inserting
312 query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
313 query.bindValue(":xid_event", aLink["event_id"]);
314 query.bindValue(":xid_conference", aLink["conference_id"]);
315 query.bindValue(":name", aLink["name"]);
316 query.bindValue(":url", aLink["url"]);
318 emitSqlQueryError(query);
322 bool SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword) {
323 if (aColumns.empty()) return false;
327 query.exec("DROP TABLE IF EXISTS SEARCH_EVENT");
328 emitSqlQueryError(query);
331 query.exec("CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL )");
332 emitSqlQueryError(query);
335 QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
336 "SELECT DISTINCT EVENT.xid_conference, EVENT.id FROM EVENT ");
337 if( aColumns.contains("ROOM") ){
338 sql += "LEFT JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
339 sql += "LEFT JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
341 if( aColumns.contains("PERSON") ){
342 sql += "LEFT JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
343 sql += "LEFT JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
345 sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
347 QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
348 QStringList whereAnd;
349 for (int i=0; i < searchKeywords.count(); i++) {
351 foreach (QString table, aColumns.uniqueKeys()) {
352 foreach (QString column, aColumns.values(table)){
353 whereOr.append(QString("%1.%2 LIKE '\%' || :%1%2%3 || '\%'").arg(table).arg(column).arg(i));
356 whereAnd.append(whereOr.join(" OR "));
358 sql += whereAnd.join(") AND (");
362 for (int i = 0; i != searchKeywords.size(); ++i) {
363 QString keyword = searchKeywords[i];
364 foreach (QString table, aColumns.uniqueKeys()) {
365 foreach (QString column, aColumns.values(table)) {
366 query.bindValue(QString(":%1%2%3").arg(table).arg(column).arg(i), keyword );
371 bool success = query.exec();
372 emitSqlQueryError(query);
377 bool SqlEngine::beginTransaction() {
379 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
380 emitSqlQueryError(query);
385 bool SqlEngine::commitTransaction() {
387 bool success = query.exec("COMMIT");
388 emitSqlQueryError(query);
393 bool SqlEngine::deleteConference(int id) {
395 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
396 emitSqlQueryError(query);
399 sqlList << "DELETE FROM LINK WHERE xid_conference = ?"
400 << "DELETE FROM EVENT_ROOM WHERE xid_conference = ?"
401 << "DELETE FROM EVENT_PERSON WHERE xid_conference = ?"
402 << "DELETE FROM EVENT WHERE xid_conference = ?"
403 << "DELETE FROM ROOM WHERE xid_conference = ?"
404 << "DELETE FROM PERSON WHERE xid_conference = ?"
405 << "DELETE FROM TRACK WHERE xid_conference = ?"
406 << "DELETE FROM CONFERENCE WHERE id = ?";
408 foreach (const QString& sql, sqlList) {
410 query.bindValue(0, id);
411 success &= query.exec();
412 emitSqlQueryError(query);
415 success &= query.exec("COMMIT");
416 emitSqlQueryError(query);
422 void SqlEngine::emitSqlQueryError(const QSqlQuery &query) {
423 QSqlError error = query.lastError();
424 if (error.type() == QSqlError::NoError) return;
425 emit dbError(error.text());