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
53 // copy conference Db from resource, instead of creating
54 // empty tables and then parsing the schedule
55 QFile dbFile(aDatabaseName);
56 QFile(":/fosdem.sqlite").copy(aDatabaseName);
57 dbFile.setPermissions(QFile::ReadOwner | QFile::WriteOwner | QFile::ReadGroup | QFile::WriteGroup);
65 checkConferenceMap(database);
67 //LOG_INFO(QString("Opening '%1' database '%2'").arg(aDatabaseType).arg(aDatabaseName));
69 return result ? QString() : database.lastError().text();
72 void SqlEngine::initialize()
75 if(!QDir::home().exists(".fosdem"))
76 QDir::home().mkdir(".fosdem");
77 databaseName = QDir::homePath() + "/.fosdem/" + "fosdem.sqlite";
78 login("QSQLITE",databaseName);
81 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference)
83 QSqlDatabase db = QSqlDatabase::database();
85 if (db.isValid() && db.isOpen())
88 QList<Conference> confsList = Conference::getAll();
91 QListIterator<Conference> i(confsList);
94 Conference conf = i.next();
95 if( aConference["title"] == conf.title() )
98 aConference["id"] = QString::number(confId);
104 if(!confId) // conference 'aConference' isn't in the table => insert
107 query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,days,"
108 "day_change,timeslot_duration,active) "
109 " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,:days,"
110 ":day_change,:timeslot_duration,:active)");
111 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city" << "days")) {
112 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
114 query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
115 query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
116 query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
117 query.bindValue(":day_change", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
118 query.bindValue(":active", confsList.count() > 0 ? 0 : 1);
119 if (!query.exec()) qDebug() << "Could not execute query to insert a conference:" << query.lastError();
120 aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
125 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent)
127 //LOG_DEBUG(QString("Adding event '%1' to DB").arg(*aEvent));
129 QSqlDatabase db = QSqlDatabase::database();
131 if (db.isValid() && db.isOpen())
133 //insert event track to table and get track id
134 int conference = aEvent["conference_id"].toInt();
135 QString name = aEvent["track"];
140 track = Track::retrieveByName(name);
141 trackId = track.id();
142 /*qDebug() << QString("DEBUG: Track %1 in DB").arg(name);*/
144 catch (OrmNoObjectException &e) {
145 track.setConference(conference);
147 trackId = track.insert();
148 /*qDebug() << QString("DEBUG: Track %1 added to DB").arg(name);*/
150 QDateTime startDateTime;
151 startDateTime.setTimeSpec(Qt::UTC);
152 startDateTime = QDateTime(QDate::fromString(aEvent["date"],DATE_FORMAT),QTime::fromString(aEvent["start"],TIME_FORMAT),Qt::UTC);
153 qDebug() << "startDateTime: " << startDateTime.toString();
155 bool event_exists = false;
157 QSqlQuery check_event_query;
158 check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
159 check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
160 check_event_query.bindValue(":id", aEvent["id"]);
161 if (!check_event_query.exec()) {
162 qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
163 << "event id:" << aEvent["id"]
164 << "error:" << check_event_query.lastError()
168 if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
175 result.prepare("UPDATE EVENT SET"
177 ", duration = :duration"
178 ", xid_track = :xid_track"
180 ", language = :language"
183 ", subtitle = :subtitle"
184 ", abstract = :abstract"
185 ", description = :description"
186 " WHERE id = :id AND xid_conference = :xid_conference");
188 result.prepare("INSERT INTO EVENT "
189 " (xid_conference, id, start, duration, xid_track, type, "
190 " language, tag, title, subtitle, abstract, description) "
191 " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
192 ":language, :tag, :title, :subtitle, :abstract, :description)");
194 result.bindValue(":xid_conference", aEvent["conference_id"]);
195 result.bindValue(":start", QString::number(startDateTime.toTime_t()));
196 result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
197 result.bindValue(":xid_track", trackId);
198 static const QList<QString> props = QList<QString>()
199 << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
200 foreach (QString prop_name, props) {
201 result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
203 if (!result.exec()) {
204 qWarning() << "event insert/update failed:" << result.lastError();
209 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson)
211 QSqlDatabase db = QSqlDatabase::database();
213 if (db.isValid() && db.isOpen())
215 // TODO: SQL Injection!!!
216 QString values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["id"],aPerson["name"]);
217 QString query = QString("INSERT INTO PERSON (xid_conference,id,name) VALUES (%1)").arg(values);
218 QSqlQuery result (query, db);
219 //LOG_AUTOTEST(query);
221 // TODO: SQL Injection!!!
222 values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["event_id"],aPerson["id"]);
223 query = QString("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (%1)").arg(values);
224 QSqlQuery resultEventPerson (query, db);
225 //LOG_AUTOTEST(query);
229 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
231 QSqlDatabase db = QSqlDatabase::database();
233 if (db.isValid() && db.isOpen())
236 query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
237 query.bindValue(":conference_id", aRoom["conference_id"]);
238 query.bindValue(":name", aRoom["name"]);
239 if (!query.exec()) qDebug() << "Could not execute select room query: " << query.lastError();
240 // now we have to check whether ROOM record with 'name' exists or not,
241 // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
242 // and assign autoincremented 'id' to aRoom
243 // - if it exists, then we need to get its 'id' and assign it to aRoom
245 if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
247 roomId = query.value(0).toInt();
249 else // ROOM record doesn't exist yet, need to create it
251 // TODO: SQL Injection!!!
252 QString values = QString("'%1', '%2', '%3'").arg(aRoom["conference_id"],aRoom["name"],aRoom["picture"]);
253 QString query = QString("INSERT INTO ROOM (xid_conference,name,picture) VALUES (%1)").arg(values);
254 QSqlQuery result (query, db);
255 roomId = result.lastInsertId().toInt(); // 'id' is assigned automatically
256 //LOG_AUTOTEST(query);
258 query = QSqlQuery(db);
259 query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :roomId)");
260 query.bindValue(":conference_id", aRoom["conference_id"]);
261 query.bindValue(":event_id", aRoom["event_id"]);
262 query.bindValue(":roomId", roomId);
263 if (!query.exec()) qDebug() << "Could not execute insert into event_room query:" << query.lastError();
264 //LOG_AUTOTEST(query);
268 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
270 QSqlDatabase db = QSqlDatabase::database();
272 //TODO: check if the link doesn't exist before inserting
273 if (db.isValid() && db.isOpen())
275 // TODO: SQL Injection!!!
276 QString values = QString("'%1', '%2', '%3', '%4'").arg(aLink["event_id"],aLink["conference_id"],aLink["name"],aLink["url"]);
277 QString query = QString("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (%1)").arg(values);
278 QSqlQuery result(query, db);
279 //LOG_AUTOTEST(query);
283 int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword)
285 QSqlDatabase db = QSqlDatabase::database();
287 if ( !db.isValid() || !db.isOpen())
292 execQuery( db, "DROP TABLE IF EXISTS SEARCH_EVENT");
294 execQuery( db, "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL )");
296 QString query = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
297 "SELECT EVENT.xid_conference, EVENT.id FROM EVENT ");
298 if( aColumns.contains("ROOM") ){
299 query += "INNER JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
300 query += "INNER JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
302 if( aColumns.contains("PERSON") ){
303 query += "INNER JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
304 query += "INNER JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
306 query += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
308 foreach (QString table, aColumns.uniqueKeys()){
309 foreach (QString column, aColumns.values(table)){
310 query += QString("%1.%2 LIKE '\%%3\%' OR ").arg( table, column, aKeyword );
313 query.chop( QString(" OR ").length() );
314 query += QString(");");
316 execQuery( db, query );
321 bool SqlEngine::beginTransaction()
323 QSqlDatabase db = QSqlDatabase::database();
325 return execQuery(db, "BEGIN IMMEDIATE TRANSACTION");
328 bool SqlEngine::commitTransaction()
330 QSqlDatabase db = QSqlDatabase::database();
332 return execQuery(db, "COMMIT");
335 void SqlEngine::deleteConference(int id)
337 QSqlDatabase db = QSqlDatabase::database();
339 if ( !db.isValid() || !db.isOpen()) {
345 QHash<QString, QVariant> params;
346 params["xid_conference"] = id;
347 execQueryWithParameter(db, "DELETE FROM LINK WHERE xid_conference = :xid_conference", params);
348 execQueryWithParameter(db, "DELETE FROM EVENT_ROOM WHERE xid_conference = :xid_conference", params);
349 execQueryWithParameter(db, "DELETE FROM EVENT_PERSON WHERE xid_conference = :xid_conference", params);
350 execQueryWithParameter(db, "DELETE FROM EVENT WHERE xid_conference = :xid_conference", params);
351 execQueryWithParameter(db, "DELETE FROM ROOM WHERE xid_conference = :xid_conference", params);
352 execQueryWithParameter(db, "DELETE FROM PERSON WHERE xid_conference = :xid_conference", params);
353 execQueryWithParameter(db, "DELETE FROM TRACK WHERE xid_conference = :xid_conference", params);
354 execQueryWithParameter(db, "DELETE FROM CONFERENCE WHERE id = :xid_conference", params);
359 bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
361 //qDebug() << "\nSQL: " << aQuery;
363 QSqlQuery sqlQuery(aDatabase);
364 if( !sqlQuery.exec(aQuery) ){
365 qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
369 //qDebug() << "SQL OK.\n";
374 bool SqlEngine::execQueryWithParameter(QSqlDatabase &aDatabase, const QString &aQuery, const QHash<QString, QVariant>& params)
376 qDebug() << "SQL:" << aQuery << "params:" << params;
378 QSqlQuery sqlQuery(aDatabase);
379 sqlQuery.prepare(aQuery);
380 foreach (QString param_key, params.keys()) {
381 sqlQuery.bindValue(param_key, params[param_key]);
383 if( !sqlQuery.exec() ){
384 qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
388 //qDebug() << "SQL OK.\n";
393 void SqlEngine::checkConferenceMap(QSqlDatabase &aDatabase)
395 QSqlQuery sqlQuery(aDatabase);
396 sqlQuery.prepare("SELECT map FROM conference");
397 if (!sqlQuery.exec()) {
398 qWarning() << "column conference.map is missing; adding";
399 execQuery(aDatabase, "ALTER TABLE conference ADD COLUMN map VARCHAR")
400 and execQuery(aDatabase, "UPDATE conference SET map = ':/maps/campus.png' WHERE title = 'FOSDEM 2010'");