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)
43 SqlEngine::~SqlEngine()
47 QString SqlEngine::login(const QString &aDatabaseType, const QString &aDatabaseName)
49 QSqlDatabase database = QSqlDatabase::addDatabase(aDatabaseType);
50 database.setDatabaseName(aDatabaseName);
53 if(!QFile::exists(aDatabaseName)) // the DB (tables) doesn't exists, and so we have to create one
56 if (!database.open()) qDebug() << "Could not open database" << database.lastError();
57 QFile file(":/create_tables.sql");
58 file.open(QIODevice::ReadOnly | QIODevice::Text);
59 QString allSqlStatements = file.readAll();
60 foreach(QString sql, allSqlStatements.split(";")) {
61 if (sql.trimmed().length() == 0) // do not execute empty queries like the last character from create_tables.sql
63 QSqlQuery query(database);
64 if (!query.exec(sql)) qDebug() << "Could not execute query '" << sql << "' error:" << query.lastError();
72 //LOG_INFO(QString("Opening '%1' database '%2'").arg(aDatabaseType).arg(aDatabaseName));
74 return result ? QString() : database.lastError().text();
77 void SqlEngine::initialize()
81 dataDirName = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
82 QDir dataDir = QDir(dataDirName).absolutePath();
84 dataDir.mkpath(dataDirName);
85 databaseName = dataDirName + "/ConfClerk.sqlite";
86 login("QSQLITE",databaseName);
89 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference, int conferenceId)
91 QSqlDatabase db = QSqlDatabase::database();
93 if (db.isValid() && db.isOpen())
96 // When city is empty, assign a dummy value. We probably want to find a way to change the database scheme ...
98 if (aConference["city"].isEmpty()) aConference["city"] = "n/a";
101 if (conferenceId <= 0) // insert conference
103 query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,days,"
104 "day_change,timeslot_duration,active) "
105 " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,:days,"
106 ":day_change,:timeslot_duration,:active)");
107 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city" << "days")) {
108 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
110 query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
111 query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
112 query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
113 query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
114 query.bindValue(":active", 1);
115 if (!query.exec()) qDebug() << "Could not execute query to insert a conference:" << query.lastError();
116 aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
118 else // update conference
120 query.prepare("UPDATE CONFERENCE set title=:title, url=:url, subtitle=:subtitle, venue=:venue, city=:city, start=:start, end=:end, days=:days,"
121 "day_change=:day_change, timeslot_duration=:timeslot_duration, active=:active "
123 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city" << "days")) {
124 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
126 query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
127 query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
128 query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
129 query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
130 query.bindValue(":active", 1);
131 query.bindValue(":id", conferenceId);
132 if (!query.exec()) qDebug() << "Could not execute query to update a conference:" << query.lastError();
133 aConference["id"] = conferenceId;
138 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent)
140 QSqlDatabase db = QSqlDatabase::database();
142 if (db.isValid() && db.isOpen())
144 //insert event track to table and get track id
145 int conference = aEvent["conference_id"].toInt();
146 QString name = aEvent["track"];
151 track = Track::retrieveByName(conference, name);
152 trackId = track.id();
154 catch (OrmNoObjectException &e) {
155 track.setConference(conference);
157 trackId = track.insert();
159 QDateTime startDateTime;
160 startDateTime.setTimeSpec(Qt::UTC);
161 startDateTime = QDateTime(QDate::fromString(aEvent["date"],DATE_FORMAT),QTime::fromString(aEvent["start"],TIME_FORMAT),Qt::UTC);
163 bool event_exists = false;
165 QSqlQuery check_event_query;
166 check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
167 check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
168 check_event_query.bindValue(":id", aEvent["id"]);
169 if (!check_event_query.exec()) {
170 qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
171 << "event id:" << aEvent["id"]
172 << "error:" << check_event_query.lastError()
176 if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
183 result.prepare("UPDATE EVENT SET"
185 ", duration = :duration"
186 ", xid_track = :xid_track"
188 ", language = :language"
191 ", subtitle = :subtitle"
192 ", abstract = :abstract"
193 ", description = :description"
194 " WHERE id = :id AND xid_conference = :xid_conference");
196 result.prepare("INSERT INTO EVENT "
197 " (xid_conference, id, start, duration, xid_track, type, "
198 " language, tag, title, subtitle, abstract, description) "
199 " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
200 ":language, :tag, :title, :subtitle, :abstract, :description)");
202 result.bindValue(":xid_conference", aEvent["conference_id"]);
203 result.bindValue(":start", QString::number(startDateTime.toTime_t()));
204 result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
205 result.bindValue(":xid_track", trackId);
206 static const QList<QString> props = QList<QString>()
207 << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
208 foreach (QString prop_name, props) {
209 result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
211 if (!result.exec()) {
212 qWarning() << "event insert/update failed:" << result.lastError();
217 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson)
219 QSqlDatabase db = QSqlDatabase::database();
221 if (db.isValid() && db.isOpen())
224 query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)");
225 query.bindValue(":xid_conference", aPerson["conference_id"]);
226 query.bindValue(":id", aPerson["id"]);
227 query.bindValue(":name", aPerson["name"]);
228 query.exec(); // some queries fail due to the unique key constraint
229 // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError();
231 query = QSqlQuery(db);
232 query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)");
233 query.bindValue(":xid_conference", aPerson["conference_id"]);
234 query.bindValue(":xid_event", aPerson["event_id"]);
235 query.bindValue(":xid_person", aPerson["id"]);
236 query.exec(); // some queries fail due to the unique key constraint
237 // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError();
241 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
243 QSqlDatabase db = QSqlDatabase::database();
245 if (db.isValid() && db.isOpen())
248 query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
249 query.bindValue(":conference_id", aRoom["conference_id"]);
250 query.bindValue(":name", aRoom["name"]);
251 if (!query.exec()) qDebug() << "Could not execute select room query: " << query.lastError();
252 // now we have to check whether ROOM record with 'name' exists or not,
253 // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
254 // and assign autoincremented 'id' to aRoom
255 // - if it exists, then we need to get its 'id' and assign it to aRoom
257 if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
259 aRoom["id"] = query.value(0).toString();
261 else // ROOM record doesn't exist yet, need to create it
263 query = QSqlQuery(db);
264 query.prepare("INSERT INTO ROOM (xid_conference,name,picture) VALUES (:xid_conference, :name, '')");
265 query.bindValue(":xid_conference", aRoom["conference_id"]);
266 query.bindValue(":xid_name", aRoom["name"]);
267 if (!query.exec()) qDebug() << "Could not execute 'insert into room ...' query." << query.lastError();
268 aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
269 //LOG_AUTOTEST(query);
272 // remove previous conference/room records; room names might have changed
273 query = QSqlQuery(db);
274 query.prepare("DELETE FROM EVENT_ROOM WHERE xid_conference=:conference_id AND xid_event=:event_id");
275 query.bindValue(":conference_id", aRoom["conference_id"]);
276 query.bindValue(":event_id", aRoom["event_id"]);
277 if (!query.exec()) qDebug() << "Could not execute SELECT * FROM EVENT_ROOM' query:" << query.lastError();
278 // and insert new ones
279 query = QSqlQuery(db);
280 query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
281 query.bindValue(":conference_id", aRoom["conference_id"]);
282 query.bindValue(":event_id", aRoom["event_id"]);
283 query.bindValue(":room_id", aRoom["id"]);
284 if (!query.exec()) qDebug() << "Could not 'execute insert into event_room' query:" << query.lastError();
288 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
290 QSqlDatabase db = QSqlDatabase::database();
292 //TODO: check if the link doesn't exist before inserting
293 if (db.isValid() && db.isOpen())
296 query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
297 query.bindValue(":xid_event", aLink["event_id"]);
298 query.bindValue(":xid_conference", aLink["conference_id"]);
299 query.bindValue(":name", aLink["name"]);
300 query.bindValue(":url", aLink["url"]);
301 if (!query.exec()) qDebug() << "Error executing 'insert into link' query: " << query.lastError();
305 int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword)
307 QSqlDatabase db = QSqlDatabase::database();
309 if ( !db.isValid() || !db.isOpen())
312 if (aColumns.empty()) return -1;
315 execQuery( db, "DROP TABLE IF EXISTS SEARCH_EVENT");
317 execQuery( db, "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL )");
319 QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
320 "SELECT DISTINCT EVENT.xid_conference, EVENT.id FROM EVENT ");
321 if( aColumns.contains("ROOM") ){
322 sql += "LEFT JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
323 sql += "LEFT JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
325 if( aColumns.contains("PERSON") ){
326 sql += "LEFT JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
327 sql += "LEFT JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
329 sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
331 QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
332 QStringList whereAnd;
333 for (int i=0; i < searchKeywords.count(); i++) {
335 foreach (QString table, aColumns.uniqueKeys()) {
336 foreach (QString column, aColumns.values(table)){
337 whereOr.append(QString("%1.%2 LIKE '\%' || :%1%2%3 || '\%'").arg(table).arg(column).arg(i));
340 whereAnd.append(whereOr.join(" OR "));
342 sql += whereAnd.join(") AND (");
347 for (int i = 0; i != searchKeywords.size(); ++i) {
348 QString keyword = searchKeywords[i];
349 foreach (QString table, aColumns.uniqueKeys()) {
350 foreach (QString column, aColumns.values(table)) {
351 query.bindValue(QString(":%1%2%3").arg(table).arg(column).arg(i), keyword );
357 qDebug() << "Could not execute search query: " << query.lastError().text();
364 bool SqlEngine::beginTransaction()
366 QSqlDatabase db = QSqlDatabase::database();
368 return execQuery(db, "BEGIN IMMEDIATE TRANSACTION");
371 bool SqlEngine::commitTransaction()
373 QSqlDatabase db = QSqlDatabase::database();
375 return execQuery(db, "COMMIT");
378 void SqlEngine::deleteConference(int id)
380 QSqlDatabase db = QSqlDatabase::database();
382 if ( !db.isValid() || !db.isOpen()) {
388 QHash<QString, QVariant> params;
389 params["xid_conference"] = id;
390 execQueryWithParameter(db, "DELETE FROM LINK WHERE xid_conference = :xid_conference", params);
391 execQueryWithParameter(db, "DELETE FROM EVENT_ROOM WHERE xid_conference = :xid_conference", params);
392 execQueryWithParameter(db, "DELETE FROM EVENT_PERSON WHERE xid_conference = :xid_conference", params);
393 execQueryWithParameter(db, "DELETE FROM EVENT WHERE xid_conference = :xid_conference", params);
394 execQueryWithParameter(db, "DELETE FROM ROOM WHERE xid_conference = :xid_conference", params);
395 execQueryWithParameter(db, "DELETE FROM PERSON WHERE xid_conference = :xid_conference", params);
396 execQueryWithParameter(db, "DELETE FROM TRACK WHERE xid_conference = :xid_conference", params);
397 execQueryWithParameter(db, "DELETE FROM CONFERENCE WHERE id = :xid_conference", params);
402 bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
404 QSqlQuery sqlQuery(aDatabase);
405 if( !sqlQuery.exec(aQuery) ){
406 qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
412 bool SqlEngine::execQueryWithParameter(QSqlDatabase &aDatabase, const QString &aQuery, const QHash<QString, QVariant>& params)
414 QSqlQuery sqlQuery(aDatabase);
415 sqlQuery.prepare(aQuery);
416 foreach (QString param_key, params.keys()) {
417 sqlQuery.bindValue(param_key, params[param_key]);
419 if( !sqlQuery.exec() ){
420 qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();