c210b84352a4b71e1481260731a8898b6f59ec5d
[toast/confclerk.git] / src / sql / sqlengine.cpp
1 /*
2  * Copyright (C) 2010 Ixonos Plc.
3  * Copyright (C) 2011-2012 Philipp Spitzer, gregor herrmann, Stefan Stahl
4  *
5  * This file is part of ConfClerk.
6  *
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)
10  * any later version.
11  *
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
15  * more details.
16  *
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/>.
19  */
20
21 #include <QSqlError>
22 #include <QSqlQuery>
23 #include <QSqlRecord>
24 #include <QVariant>
25 #include <QDateTime>
26
27 #include <QDir>
28 #include <QDesktopServices>
29 #include "sqlengine.h"
30 #include "track.h"
31 #include "conference.h"
32
33 #include <QDebug>
34
35 const QString DATE_FORMAT ("yyyy-MM-dd");
36 const QString TIME_FORMAT ("hh:mm");
37
38 SqlEngine::SqlEngine(QObject *aParent)
39     : QObject(aParent)
40 {
41 }
42
43 SqlEngine::~SqlEngine()
44 {
45 }
46
47 QString SqlEngine::login(const QString &aDatabaseType, const QString &aDatabaseName)
48 {
49     QSqlDatabase database = QSqlDatabase::addDatabase(aDatabaseType);
50     database.setDatabaseName(aDatabaseName);
51
52     bool result = false;
53     if(!QFile::exists(aDatabaseName)) // the DB (tables) doesn't exists, and so we have to create one
54     {
55         // create Db
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
62                 continue;
63             QSqlQuery query(database);
64             if (!query.exec(sql)) qDebug() << "Could not execute query '" << sql << "' error:" << query.lastError();
65         }
66     }
67     else
68     {
69         database.open();
70     }
71
72     //LOG_INFO(QString("Opening '%1' database '%2'").arg(aDatabaseType).arg(aDatabaseName));
73
74     return result ? QString() : database.lastError().text();
75 }
76
77 void SqlEngine::initialize()
78 {
79     QString databaseName;
80     QString dataDirName;
81     dataDirName = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
82     QDir dataDir = QDir(dataDirName).absolutePath();
83     if(!dataDir.exists())
84         dataDir.mkpath(dataDirName);
85     databaseName = dataDirName + "/ConfClerk.sqlite";
86     login("QSQLITE",databaseName);
87 }
88
89 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference, int conferenceId)
90 {
91     QSqlDatabase db = QSqlDatabase::database();
92
93     if (db.isValid() && db.isOpen())
94     {
95         // HACK
96         // When city is empty, assign a dummy value. We probably want to find a way to change the database scheme ...
97         // cf. #32
98         if (aConference["city"].isEmpty()) aConference["city"] = "n/a";
99
100         QSqlQuery query(db);
101         if (conferenceId <= 0) // insert conference
102         {
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]);
109             }
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
117         }
118         else // update conference
119         {
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 "
122                           "WHERE id=:id");
123             foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city" << "days")) {
124                 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
125             }
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;
134         }
135     }
136 }
137
138 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent)
139 {
140     QSqlDatabase db = QSqlDatabase::database();
141
142     if (db.isValid() && db.isOpen())
143     {
144         //insert event track to table and get track id
145         int conference = aEvent["conference_id"].toInt();
146         QString name = aEvent["track"];
147         Track track;
148         int trackId;
149         try
150         {
151             track = Track::retrieveByName(conference, name);
152             trackId = track.id();
153         }
154         catch (OrmNoObjectException &e) {
155             track.setConference(conference);
156             track.setName(name);
157             trackId = track.insert();
158         }
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);
162
163         bool event_exists = false;
164         {
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()
173                         ;
174                 return;
175             }
176             if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
177                 event_exists = true;
178             }
179         }
180
181         QSqlQuery result;
182         if (event_exists) {
183             result.prepare("UPDATE EVENT SET"
184                             " start = :start"
185                             ", duration = :duration"
186                             ", xid_track = :xid_track"
187                             ", type = :type"
188                             ", language = :language"
189                             ", tag = :tag"
190                             ", title = :title"
191                             ", subtitle = :subtitle"
192                             ", abstract = :abstract"
193                             ", description = :description"
194                                 " WHERE id = :id AND xid_conference = :xid_conference");
195         } else {
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)");
201         }
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]);
210         }
211         if (!result.exec()) {
212             qWarning() << "event insert/update failed:" << result.lastError();
213         }
214     }
215 }
216
217 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson)
218 {
219     QSqlDatabase db = QSqlDatabase::database();
220
221     if (db.isValid() && db.isOpen())
222     {
223         QSqlQuery query(db);
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();
230
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();
238     }
239 }
240
241 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
242 {
243     QSqlDatabase db = QSqlDatabase::database();
244
245     if (db.isValid() && db.isOpen())
246     {
247         QSqlQuery query(db);
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
256         aRoom["id"] = "";
257         if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
258         {
259             aRoom["id"] = query.value(0).toString();
260         }
261         else // ROOM record doesn't exist yet, need to create it
262         {
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);
270         }
271         
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();
285     }
286 }
287
288 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
289 {
290     QSqlDatabase db = QSqlDatabase::database();
291
292     //TODO: check if the link doesn't exist before inserting
293     if (db.isValid() && db.isOpen())
294     {
295         QSqlQuery query(db);
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();
302     }
303 }
304
305 int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword)
306 {
307     QSqlDatabase db = QSqlDatabase::database();
308
309     if ( !db.isValid() || !db.isOpen())
310         return -1;
311
312     if (aColumns.empty()) return -1;
313
314     // DROP
315     execQuery( db, "DROP TABLE IF EXISTS SEARCH_EVENT");
316     // CREATE
317     execQuery( db, "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER  NOT NULL, id INTEGER NOT NULL )");
318     // INSERT
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 ) ";
324     }
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 ) ";
328     }
329     sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
330
331     QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
332     QStringList whereAnd;
333     for (int i=0; i < searchKeywords.count(); i++) {
334         QStringList whereOr;
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));
338             }
339         }
340         whereAnd.append(whereOr.join(" OR "));
341     }
342     sql += whereAnd.join(") AND (");
343     sql += QString(")");
344
345     QSqlQuery query(db);
346     query.prepare(sql);
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 );
352             }
353         }
354     }
355
356     if( !query.exec() ){
357        qDebug() << "Could not execute search query: " << query.lastError().text();
358        return -1;
359     }
360
361     return 1;
362 }
363
364 bool SqlEngine::beginTransaction()
365 {
366     QSqlDatabase db = QSqlDatabase::database();
367
368     return execQuery(db, "BEGIN IMMEDIATE TRANSACTION");
369 }
370
371 bool SqlEngine::commitTransaction()
372 {
373     QSqlDatabase db = QSqlDatabase::database();
374
375     return execQuery(db, "COMMIT");
376 }
377
378 void SqlEngine::deleteConference(int id)
379 {
380     QSqlDatabase db = QSqlDatabase::database();
381
382     if ( !db.isValid() || !db.isOpen()) {
383         return;
384     }
385
386     beginTransaction();
387
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);
398
399     commitTransaction();
400 }
401
402 bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
403 {
404     QSqlQuery sqlQuery(aDatabase);
405     if( !sqlQuery.exec(aQuery) ){
406        qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
407        return false;
408     }
409     return true;
410 }
411
412 bool SqlEngine::execQueryWithParameter(QSqlDatabase &aDatabase, const QString &aQuery, const QHash<QString, QVariant>& params)
413 {
414     QSqlQuery sqlQuery(aDatabase);
415     sqlQuery.prepare(aQuery);
416     foreach (QString param_key, params.keys()) {
417         sqlQuery.bindValue(param_key, params[param_key]);
418     }
419     if( !sqlQuery.exec() ){
420        qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
421        return false;
422     }
423     return true;
424 }