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 QFileInfo dbFilenameInfo(dbFilename);
50 dbFilenameInfo.absoluteDir().mkpath(""); // TODO ...
51 db = QSqlDatabase::addDatabase("QSQLITE");
52 db.setDatabaseName(dbFilename);
57 int SqlEngine::dbSchemaVersion() {
59 if (!query.exec("PRAGMA user_version")) {
60 emitSqlQueryError(query);
64 int version = query.value(0).toInt();
66 // check whether the tables are existing
67 if (!query.exec("select count(*) from sqlite_master where name='CONFERENCE'")) {
68 emitSqlQueryError(query);
72 if (query.value(0).toInt() == 1) return 0; // tables are existing
73 return -1; // database seems to be empty (or has other tables)
79 bool SqlEngine::updateDbSchemaVersion000To001() {
80 emit dbError("Upgrade 0 -> 1 not implemented yet");
85 bool SqlEngine::createCurrentDbSchema() {
86 QFile file(":/dbschema001.sql");
87 file.open(QIODevice::ReadOnly | QIODevice::Text);
88 QString allSqlStatements = file.readAll();
90 foreach(QString sql, allSqlStatements.split(";")) {
91 if (sql.trimmed().isEmpty()) // do not execute empty queries like the last character from create_tables.sql
93 if (!query.exec(sql)) {
94 emitSqlQueryError(query);
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 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference, int conferenceId) {
127 // When city is empty, assign a dummy value. We probably want to find a way to change the database scheme ...
129 if (aConference["city"].isEmpty()) aConference["city"] = "n/a";
132 if (conferenceId <= 0) // insert conference
134 query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,days,"
135 "day_change,timeslot_duration,active) "
136 " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,:days,"
137 ":day_change,:timeslot_duration,:active)");
138 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city" << "days")) {
139 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
141 query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
142 query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
143 query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
144 query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
145 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, days=:days,"
152 "day_change=:day_change, timeslot_duration=:timeslot_duration, active=:active "
154 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city" << "days")) {
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);
163 emitSqlQueryError(query);
164 aConference["id"] = conferenceId;
169 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent) {
170 //insert event track to table and get track id
171 int conference = aEvent["conference_id"].toInt();
172 QString name = aEvent["track"];
177 track = Track::retrieveByName(conference, name);
178 trackId = track.id();
180 catch (OrmNoObjectException &e) {
181 track.setConference(conference);
183 trackId = track.insert();
185 QDateTime startDateTime;
186 startDateTime.setTimeSpec(Qt::UTC);
187 startDateTime = QDateTime(QDate::fromString(aEvent["date"],DATE_FORMAT),QTime::fromString(aEvent["start"],TIME_FORMAT),Qt::UTC);
189 bool event_exists = false;
191 QSqlQuery check_event_query;
192 check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
193 check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
194 check_event_query.bindValue(":id", aEvent["id"]);
195 if (!check_event_query.exec()) {
196 qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
197 << "event id:" << aEvent["id"]
198 << "error:" << check_event_query.lastError()
202 if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
209 result.prepare("UPDATE EVENT SET"
211 ", duration = :duration"
212 ", xid_track = :xid_track"
214 ", language = :language"
217 ", subtitle = :subtitle"
218 ", abstract = :abstract"
219 ", description = :description"
220 " WHERE id = :id AND xid_conference = :xid_conference");
222 result.prepare("INSERT INTO EVENT "
223 " (xid_conference, id, start, duration, xid_track, type, "
224 " language, tag, title, subtitle, abstract, description) "
225 " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
226 ":language, :tag, :title, :subtitle, :abstract, :description)");
228 result.bindValue(":xid_conference", aEvent["conference_id"]);
229 result.bindValue(":start", QString::number(startDateTime.toTime_t()));
230 result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
231 result.bindValue(":xid_track", trackId);
232 static const QList<QString> props = QList<QString>()
233 << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
234 foreach (QString prop_name, props) {
235 result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
237 if (!result.exec()) {
238 qWarning() << "event insert/update failed:" << result.lastError();
243 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson) {
245 query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)");
246 query.bindValue(":xid_conference", aPerson["conference_id"]);
247 query.bindValue(":id", aPerson["id"]);
248 query.bindValue(":name", aPerson["name"]);
249 query.exec(); // TODO some queries fail due to the unique key constraint
250 // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError();
252 query = QSqlQuery(db);
253 query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)");
254 query.bindValue(":xid_conference", aPerson["conference_id"]);
255 query.bindValue(":xid_event", aPerson["event_id"]);
256 query.bindValue(":xid_person", aPerson["id"]);
257 query.exec(); // TODO some queries fail due to the unique key constraint
258 // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError();
262 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom) {
264 query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
265 query.bindValue(":conference_id", aRoom["conference_id"]);
266 query.bindValue(":name", aRoom["name"]);
267 emitSqlQueryError(query);
268 // now we have to check whether ROOM record with 'name' exists or not,
269 // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
270 // and assign autoincremented 'id' to aRoom
271 // - if it exists, then we need to get its 'id' and assign it to aRoom
273 if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
275 aRoom["id"] = query.value(0).toString();
277 else // ROOM record doesn't exist yet, need to create it
279 query = QSqlQuery(db);
280 query.prepare("INSERT INTO ROOM (xid_conference,name,picture) VALUES (:xid_conference, :name, '')");
281 query.bindValue(":xid_conference", aRoom["conference_id"]);
282 query.bindValue(":xid_name", aRoom["name"]);
283 emitSqlQueryError(query);
284 aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
285 //LOG_AUTOTEST(query);
288 // remove previous conference/room records; room names might have changed
289 query = QSqlQuery(db);
290 query.prepare("DELETE FROM EVENT_ROOM WHERE xid_conference=:conference_id AND xid_event=:event_id");
291 query.bindValue(":conference_id", aRoom["conference_id"]);
292 query.bindValue(":event_id", aRoom["event_id"]);
293 emitSqlQueryError(query);
294 // and insert new ones
295 query = QSqlQuery(db);
296 query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
297 query.bindValue(":conference_id", aRoom["conference_id"]);
298 query.bindValue(":event_id", aRoom["event_id"]);
299 query.bindValue(":room_id", aRoom["id"]);
300 emitSqlQueryError(query);
304 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink) {
305 //TODO: check if the link doesn't exist before inserting
307 query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
308 query.bindValue(":xid_event", aLink["event_id"]);
309 query.bindValue(":xid_conference", aLink["conference_id"]);
310 query.bindValue(":name", aLink["name"]);
311 query.bindValue(":url", aLink["url"]);
312 emitSqlQueryError(query);
316 bool SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword) {
317 if (aColumns.empty()) return false;
321 query.exec("DROP TABLE IF EXISTS SEARCH_EVENT");
322 emitSqlQueryError(query);
325 query.exec("CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL )");
326 emitSqlQueryError(query);
329 QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
330 "SELECT DISTINCT EVENT.xid_conference, EVENT.id FROM EVENT ");
331 if( aColumns.contains("ROOM") ){
332 sql += "LEFT JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
333 sql += "LEFT JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
335 if( aColumns.contains("PERSON") ){
336 sql += "LEFT JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
337 sql += "LEFT JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
339 sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
341 QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
342 QStringList whereAnd;
343 for (int i=0; i < searchKeywords.count(); i++) {
345 foreach (QString table, aColumns.uniqueKeys()) {
346 foreach (QString column, aColumns.values(table)){
347 whereOr.append(QString("%1.%2 LIKE '\%' || :%1%2%3 || '\%'").arg(table).arg(column).arg(i));
350 whereAnd.append(whereOr.join(" OR "));
352 sql += whereAnd.join(") AND (");
356 for (int i = 0; i != searchKeywords.size(); ++i) {
357 QString keyword = searchKeywords[i];
358 foreach (QString table, aColumns.uniqueKeys()) {
359 foreach (QString column, aColumns.values(table)) {
360 query.bindValue(QString(":%1%2%3").arg(table).arg(column).arg(i), keyword );
365 bool success = query.exec();
366 emitSqlQueryError(query);
371 bool SqlEngine::beginTransaction() {
373 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
374 emitSqlQueryError(query);
379 bool SqlEngine::commitTransaction() {
381 bool success = query.exec("COMMIT");
382 emitSqlQueryError(query);
387 bool SqlEngine::deleteConference(int id) {
389 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
390 emitSqlQueryError(query);
393 sqlList << "DELETE FROM LINK WHERE xid_conference = ?"
394 << "DELETE FROM EVENT_ROOM WHERE xid_conference = ?"
395 << "DELETE FROM EVENT_PERSON WHERE xid_conference = ?"
396 << "DELETE FROM EVENT WHERE xid_conference = ?"
397 << "DELETE FROM ROOM WHERE xid_conference = ?"
398 << "DELETE FROM PERSON WHERE xid_conference = ?"
399 << "DELETE FROM TRACK WHERE xid_conference = ?"
400 << "DELETE FROM CONFERENCE WHERE id = ?";
402 foreach (const QString& sql, sqlList) {
404 query.bindValue(0, id);
405 success &= query.exec();
406 emitSqlQueryError(query);
409 success &= query.exec("COMMIT");
410 emitSqlQueryError(query);
416 void SqlEngine::emitSqlQueryError(const QSqlQuery &query) {
417 QSqlError error = query.lastError();
418 if (error.type() == QSqlError::NoError) return;
419 emit dbError(error.text());