2 * Copyright (C) 2010 Ixonos Plc.
4 * This file is part of fosdem-schedule.
6 * fosdem-schedule is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the Free
8 * Software Foundation, either version 2 of the License, or (at your option)
11 * fosdem-schedule is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 * You should have received a copy of the GNU General Public License along with
17 * fosdem-schedule. If not, see <http://www.gnu.org/licenses/>.
27 #include "sqlengine.h"
29 #include <conference.h>
33 const QString DATE_FORMAT ("yyyy-MM-dd");
34 const QString TIME_FORMAT ("hh:mm");
36 SqlEngine::SqlEngine(QObject *aParent)
41 SqlEngine::~SqlEngine()
45 QString SqlEngine::login(const QString &aDatabaseType, const QString &aDatabaseName)
47 QSqlDatabase database = QSqlDatabase::addDatabase(aDatabaseType);
48 database.setDatabaseName(aDatabaseName);
51 if(!QFile::exists(aDatabaseName)) // the DB (tables) doesn't exists, and so we have to create one
54 if (!database.open()) qDebug() << "Could not open database" << database.lastError();
55 QFile file(":/create_tables.sql");
56 file.open(QIODevice::ReadOnly | QIODevice::Text);
57 QString allSqlStatements = file.readAll();
58 foreach(QString sql, allSqlStatements.split(";")) {
59 QSqlQuery query(database);
60 if (!query.exec(sql)) qDebug() << "Could not execute query" << query.lastError();
68 checkConferenceMap(database);
70 //LOG_INFO(QString("Opening '%1' database '%2'").arg(aDatabaseType).arg(aDatabaseName));
72 return result ? QString() : database.lastError().text();
75 void SqlEngine::initialize()
78 if(!QDir::home().exists(".fosdem"))
79 QDir::home().mkdir(".fosdem");
80 databaseName = QDir::homePath() + "/.fosdem/" + "fosdem.sqlite";
81 login("QSQLITE",databaseName);
84 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference)
86 QSqlDatabase db = QSqlDatabase::database();
88 if (db.isValid() && db.isOpen())
91 QList<Conference> confsList = Conference::getAll();
94 QListIterator<Conference> i(confsList);
97 Conference conf = i.next();
98 if( aConference["title"] == conf.title() )
101 aConference["id"] = QString::number(confId);
107 if(!confId) // conference 'aConference' isn't in the table => insert
110 query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,days,"
111 "day_change,timeslot_duration,active) "
112 " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,:days,"
113 ":day_change,:timeslot_duration,:active)");
114 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city" << "days")) {
115 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
117 query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
118 query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
119 query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
120 query.bindValue(":day_change", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
121 query.bindValue(":active", confsList.count() > 0 ? 0 : 1);
122 if (!query.exec()) qDebug() << "Could not execute query to insert a conference:" << query.lastError();
123 aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
128 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent)
130 //LOG_DEBUG(QString("Adding event '%1' to DB").arg(*aEvent));
132 QSqlDatabase db = QSqlDatabase::database();
134 if (db.isValid() && db.isOpen())
136 //insert event track to table and get track id
137 int conference = aEvent["conference_id"].toInt();
138 QString name = aEvent["track"];
143 track = Track::retrieveByName(name);
144 trackId = track.id();
145 /*qDebug() << QString("DEBUG: Track %1 in DB").arg(name);*/
147 catch (OrmNoObjectException &e) {
148 track.setConference(conference);
150 trackId = track.insert();
151 /*qDebug() << QString("DEBUG: Track %1 added to DB").arg(name);*/
153 QDateTime startDateTime;
154 startDateTime.setTimeSpec(Qt::UTC);
155 startDateTime = QDateTime(QDate::fromString(aEvent["date"],DATE_FORMAT),QTime::fromString(aEvent["start"],TIME_FORMAT),Qt::UTC);
156 qDebug() << "startDateTime: " << startDateTime.toString();
158 bool event_exists = false;
160 QSqlQuery check_event_query;
161 check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
162 check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
163 check_event_query.bindValue(":id", aEvent["id"]);
164 if (!check_event_query.exec()) {
165 qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
166 << "event id:" << aEvent["id"]
167 << "error:" << check_event_query.lastError()
171 if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
178 result.prepare("UPDATE EVENT SET"
180 ", duration = :duration"
181 ", xid_track = :xid_track"
183 ", language = :language"
186 ", subtitle = :subtitle"
187 ", abstract = :abstract"
188 ", description = :description"
189 " WHERE id = :id AND xid_conference = :xid_conference");
191 result.prepare("INSERT INTO EVENT "
192 " (xid_conference, id, start, duration, xid_track, type, "
193 " language, tag, title, subtitle, abstract, description) "
194 " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
195 ":language, :tag, :title, :subtitle, :abstract, :description)");
197 result.bindValue(":xid_conference", aEvent["conference_id"]);
198 result.bindValue(":start", QString::number(startDateTime.toTime_t()));
199 result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
200 result.bindValue(":xid_track", trackId);
201 static const QList<QString> props = QList<QString>()
202 << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
203 foreach (QString prop_name, props) {
204 result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
206 if (!result.exec()) {
207 qWarning() << "event insert/update failed:" << result.lastError();
212 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson)
214 QSqlDatabase db = QSqlDatabase::database();
216 if (db.isValid() && db.isOpen())
218 // TODO: SQL Injection!!!
219 QString values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["id"],aPerson["name"]);
220 QString query = QString("INSERT INTO PERSON (xid_conference,id,name) VALUES (%1)").arg(values);
221 QSqlQuery result (query, db);
222 //LOG_AUTOTEST(query);
224 // TODO: SQL Injection!!!
225 values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["event_id"],aPerson["id"]);
226 query = QString("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (%1)").arg(values);
227 QSqlQuery resultEventPerson (query, db);
228 //LOG_AUTOTEST(query);
232 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
234 QSqlDatabase db = QSqlDatabase::database();
236 if (db.isValid() && db.isOpen())
239 query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
240 query.bindValue(":conference_id", aRoom["conference_id"]);
241 query.bindValue(":name", aRoom["name"]);
242 if (!query.exec()) qDebug() << "Could not execute select room query: " << query.lastError();
243 // now we have to check whether ROOM record with 'name' exists or not,
244 // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
245 // and assign autoincremented 'id' to aRoom
246 // - if it exists, then we need to get its 'id' and assign it to aRoom
248 if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
250 roomId = query.value(0).toInt();
252 else // ROOM record doesn't exist yet, need to create it
254 // TODO: SQL Injection!!!
255 QString values = QString("'%1', '%2', '%3'").arg(aRoom["conference_id"],aRoom["name"],aRoom["picture"]);
256 QString query = QString("INSERT INTO ROOM (xid_conference,name,picture) VALUES (%1)").arg(values);
257 QSqlQuery result (query, db);
258 roomId = result.lastInsertId().toInt(); // 'id' is assigned automatically
259 //LOG_AUTOTEST(query);
261 query = QSqlQuery(db);
262 query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :roomId)");
263 query.bindValue(":conference_id", aRoom["conference_id"]);
264 query.bindValue(":event_id", aRoom["event_id"]);
265 query.bindValue(":roomId", roomId);
266 if (!query.exec()) qDebug() << "Could not execute insert into event_room query:" << query.lastError();
267 //LOG_AUTOTEST(query);
271 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
273 QSqlDatabase db = QSqlDatabase::database();
275 //TODO: check if the link doesn't exist before inserting
276 if (db.isValid() && db.isOpen())
278 // TODO: SQL Injection!!!
279 QString values = QString("'%1', '%2', '%3', '%4'").arg(aLink["event_id"],aLink["conference_id"],aLink["name"],aLink["url"]);
280 QString query = QString("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (%1)").arg(values);
281 QSqlQuery result(query, db);
282 //LOG_AUTOTEST(query);
286 int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword)
288 QSqlDatabase db = QSqlDatabase::database();
290 if ( !db.isValid() || !db.isOpen())
295 execQuery( db, "DROP TABLE IF EXISTS SEARCH_EVENT");
297 execQuery( db, "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL )");
299 QString query = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
300 "SELECT EVENT.xid_conference, EVENT.id FROM EVENT ");
301 if( aColumns.contains("ROOM") ){
302 query += "INNER JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
303 query += "INNER JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
305 if( aColumns.contains("PERSON") ){
306 query += "INNER JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
307 query += "INNER JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
309 query += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
311 foreach (QString table, aColumns.uniqueKeys()){
312 foreach (QString column, aColumns.values(table)){
313 query += QString("%1.%2 LIKE '\%%3\%' OR ").arg( table, column, aKeyword );
316 query.chop( QString(" OR ").length() );
317 query += QString(");");
319 execQuery( db, query );
324 bool SqlEngine::beginTransaction()
326 QSqlDatabase db = QSqlDatabase::database();
328 return execQuery(db, "BEGIN IMMEDIATE TRANSACTION");
331 bool SqlEngine::commitTransaction()
333 QSqlDatabase db = QSqlDatabase::database();
335 return execQuery(db, "COMMIT");
338 void SqlEngine::deleteConference(int id)
340 QSqlDatabase db = QSqlDatabase::database();
342 if ( !db.isValid() || !db.isOpen()) {
348 QHash<QString, QVariant> params;
349 params["xid_conference"] = id;
350 execQueryWithParameter(db, "DELETE FROM LINK WHERE xid_conference = :xid_conference", params);
351 execQueryWithParameter(db, "DELETE FROM EVENT_ROOM WHERE xid_conference = :xid_conference", params);
352 execQueryWithParameter(db, "DELETE FROM EVENT_PERSON WHERE xid_conference = :xid_conference", params);
353 execQueryWithParameter(db, "DELETE FROM EVENT WHERE xid_conference = :xid_conference", params);
354 execQueryWithParameter(db, "DELETE FROM ROOM WHERE xid_conference = :xid_conference", params);
355 execQueryWithParameter(db, "DELETE FROM PERSON WHERE xid_conference = :xid_conference", params);
356 execQueryWithParameter(db, "DELETE FROM TRACK WHERE xid_conference = :xid_conference", params);
357 execQueryWithParameter(db, "DELETE FROM CONFERENCE WHERE id = :xid_conference", params);
362 bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
364 //qDebug() << "\nSQL: " << aQuery;
366 QSqlQuery sqlQuery(aDatabase);
367 if( !sqlQuery.exec(aQuery) ){
368 qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
372 //qDebug() << "SQL OK.\n";
377 bool SqlEngine::execQueryWithParameter(QSqlDatabase &aDatabase, const QString &aQuery, const QHash<QString, QVariant>& params)
379 qDebug() << "SQL:" << aQuery << "params:" << params;
381 QSqlQuery sqlQuery(aDatabase);
382 sqlQuery.prepare(aQuery);
383 foreach (QString param_key, params.keys()) {
384 sqlQuery.bindValue(param_key, params[param_key]);
386 if( !sqlQuery.exec() ){
387 qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
391 //qDebug() << "SQL OK.\n";
396 void SqlEngine::checkConferenceMap(QSqlDatabase &aDatabase)
398 QSqlQuery sqlQuery(aDatabase);
399 sqlQuery.prepare("SELECT map FROM conference");
400 if (!sqlQuery.exec()) {
401 qWarning() << "column conference.map is missing; adding";
402 execQuery(aDatabase, "ALTER TABLE conference ADD COLUMN map VARCHAR")
403 and execQuery(aDatabase, "UPDATE conference SET map = ':/maps/campus.png' WHERE title = 'FOSDEM 2010'");