2 * Copyright (C) 2010 Ixonos Plc.
3 * Copyright (C) 2011 Philipp Spitzer, gregor herrmann
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 "sqlengine.h"
30 #include <conference.h>
34 const QString DATE_FORMAT ("yyyy-MM-dd");
35 const QString TIME_FORMAT ("hh:mm");
37 SqlEngine::SqlEngine(QObject *aParent)
42 SqlEngine::~SqlEngine()
46 QString SqlEngine::login(const QString &aDatabaseType, const QString &aDatabaseName)
48 QSqlDatabase database = QSqlDatabase::addDatabase(aDatabaseType);
49 database.setDatabaseName(aDatabaseName);
52 if(!QFile::exists(aDatabaseName)) // the DB (tables) doesn't exists, and so we have to create one
55 if (!database.open()) qDebug() << "Could not open database" << database.lastError();
56 QFile file(":/create_tables.sql");
57 file.open(QIODevice::ReadOnly | QIODevice::Text);
58 QString allSqlStatements = file.readAll();
59 foreach(QString sql, allSqlStatements.split(";")) {
60 QSqlQuery query(database);
61 if (!query.exec(sql)) qDebug() << "Could not execute query" << query.lastError();
69 checkConferenceMap(database);
71 //LOG_INFO(QString("Opening '%1' database '%2'").arg(aDatabaseType).arg(aDatabaseName));
73 return result ? QString() : database.lastError().text();
76 void SqlEngine::initialize()
79 if(!QDir::home().exists(".fosdem"))
80 QDir::home().mkdir(".fosdem");
81 databaseName = QDir::homePath() + "/.fosdem/" + "fosdem.sqlite";
82 login("QSQLITE",databaseName);
85 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference)
87 QSqlDatabase db = QSqlDatabase::database();
89 if (db.isValid() && db.isOpen())
92 QList<Conference> confsList = Conference::getAll();
95 QListIterator<Conference> i(confsList);
98 Conference conf = i.next();
99 if( aConference["title"] == conf.title() )
102 aConference["id"] = QString::number(confId);
108 if(!confId) // conference 'aConference' isn't in the table => insert
111 query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,days,"
112 "day_change,timeslot_duration,active) "
113 " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,:days,"
114 ":day_change,:timeslot_duration,:active)");
115 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city" << "days")) {
116 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
118 query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
119 query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
120 query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
121 query.bindValue(":day_change", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
122 query.bindValue(":active", confsList.count() > 0 ? 0 : 1);
123 if (!query.exec()) qDebug() << "Could not execute query to insert a conference:" << query.lastError();
124 aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
129 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent)
131 //LOG_DEBUG(QString("Adding event '%1' to DB").arg(*aEvent));
133 QSqlDatabase db = QSqlDatabase::database();
135 if (db.isValid() && db.isOpen())
137 //insert event track to table and get track id
138 int conference = aEvent["conference_id"].toInt();
139 QString name = aEvent["track"];
144 track = Track::retrieveByName(conference, name);
145 trackId = track.id();
146 /*qDebug() << QString("DEBUG: Track %1 in DB").arg(name);*/
148 catch (OrmNoObjectException &e) {
149 track.setConference(conference);
151 trackId = track.insert();
152 /*qDebug() << QString("DEBUG: Track %1 added to DB").arg(name);*/
154 QDateTime startDateTime;
155 startDateTime.setTimeSpec(Qt::UTC);
156 startDateTime = QDateTime(QDate::fromString(aEvent["date"],DATE_FORMAT),QTime::fromString(aEvent["start"],TIME_FORMAT),Qt::UTC);
157 // qDebug() << "startDateTime: " << startDateTime.toString();
159 bool event_exists = false;
161 QSqlQuery check_event_query;
162 check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
163 check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
164 check_event_query.bindValue(":id", aEvent["id"]);
165 if (!check_event_query.exec()) {
166 qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
167 << "event id:" << aEvent["id"]
168 << "error:" << check_event_query.lastError()
172 if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
179 result.prepare("UPDATE EVENT SET"
181 ", duration = :duration"
182 ", xid_track = :xid_track"
184 ", language = :language"
187 ", subtitle = :subtitle"
188 ", abstract = :abstract"
189 ", description = :description"
190 " WHERE id = :id AND xid_conference = :xid_conference");
192 result.prepare("INSERT INTO EVENT "
193 " (xid_conference, id, start, duration, xid_track, type, "
194 " language, tag, title, subtitle, abstract, description) "
195 " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
196 ":language, :tag, :title, :subtitle, :abstract, :description)");
198 result.bindValue(":xid_conference", aEvent["conference_id"]);
199 result.bindValue(":start", QString::number(startDateTime.toTime_t()));
200 result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
201 result.bindValue(":xid_track", trackId);
202 static const QList<QString> props = QList<QString>()
203 << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
204 foreach (QString prop_name, props) {
205 result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
207 if (!result.exec()) {
208 qWarning() << "event insert/update failed:" << result.lastError();
213 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson)
215 QSqlDatabase db = QSqlDatabase::database();
217 if (db.isValid() && db.isOpen())
219 // TODO: SQL Injection!!!
220 QString values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["id"],aPerson["name"]);
221 QString query = QString("INSERT INTO PERSON (xid_conference,id,name) VALUES (%1)").arg(values);
222 QSqlQuery result (query, db);
223 //LOG_AUTOTEST(query);
225 // TODO: SQL Injection!!!
226 values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["event_id"],aPerson["id"]);
227 query = QString("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (%1)").arg(values);
228 QSqlQuery resultEventPerson (query, db);
229 //LOG_AUTOTEST(query);
233 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
235 QSqlDatabase db = QSqlDatabase::database();
237 if (db.isValid() && db.isOpen())
240 query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
241 query.bindValue(":conference_id", aRoom["conference_id"]);
242 query.bindValue(":name", aRoom["name"]);
243 if (!query.exec()) qDebug() << "Could not execute select room query: " << query.lastError();
244 // now we have to check whether ROOM record with 'name' exists or not,
245 // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
246 // and assign autoincremented 'id' to aRoom
247 // - if it exists, then we need to get its 'id' and assign it to aRoom
249 if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
251 aRoom["id"] = query.value(0).toString();
253 else // ROOM record doesn't exist yet, need to create it
255 query = QSqlQuery(db);
256 query.prepare("INSERT INTO ROOM (xid_conference,name,picture) VALUES (:xid_conference, :name, :picture)");
257 query.bindValue(":xid_conference", aRoom["conference_id"]);
258 query.bindValue(":xid_name", aRoom["name"]);
259 query.bindValue(":xid_picture", aRoom["picture"]);
260 if (!query.exec()) qDebug() << "Could not execute 'insert into room ...' query." << query.lastError();
261 aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
262 //LOG_AUTOTEST(query);
264 query = QSqlQuery(db);
265 query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
266 query.bindValue(":conference_id", aRoom["conference_id"]);
267 query.bindValue(":event_id", aRoom["event_id"]);
268 query.bindValue(":room_id", aRoom["id"]);
269 if (!query.exec()) qDebug() << "Could not 'execute insert into event_room' query:" << query.lastError();
270 //LOG_AUTOTEST(query);
274 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
276 QSqlDatabase db = QSqlDatabase::database();
278 //TODO: check if the link doesn't exist before inserting
279 if (db.isValid() && db.isOpen())
282 query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
283 query.bindValue(":xid_event", aLink["event_id"]);
284 query.bindValue(":xid_conference", aLink["conference_id"]);
285 query.bindValue(":name", aLink["name"]);
286 query.bindValue(":url", aLink["url"]);
287 if (!query.exec()) qDebug() << "Error executing 'insert into link' query: " << query.lastError();
288 //LOG_AUTOTEST(query);
292 int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword)
294 QSqlDatabase db = QSqlDatabase::database();
296 if ( !db.isValid() || !db.isOpen())
299 if (aColumns.empty()) return -1;
302 execQuery( db, "DROP TABLE IF EXISTS SEARCH_EVENT");
304 execQuery( db, "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL )");
306 QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
307 "SELECT EVENT.xid_conference, EVENT.id FROM EVENT ");
308 if( aColumns.contains("ROOM") ){
309 sql += "INNER JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
310 sql += "INNER JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
312 if( aColumns.contains("PERSON") ){
313 sql += "INNER JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
314 sql += "INNER JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
316 sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
318 foreach (QString table, aColumns.uniqueKeys()){
319 foreach (QString column, aColumns.values(table)){
320 sql += QString("%1.%2 LIKE '\%' || :%1%2 || '\%' OR ").arg( table, column );
323 sql.chop( QString(" OR ").length() );
328 foreach (QString table, aColumns.uniqueKeys()){
329 foreach (QString column, aColumns.values(table)){
330 query.bindValue(QString(":%1%2").arg(table, column), aKeyword );
335 qDebug() << "Could not execute search query: " << query.lastError().text();
342 bool SqlEngine::beginTransaction()
344 QSqlDatabase db = QSqlDatabase::database();
346 return execQuery(db, "BEGIN IMMEDIATE TRANSACTION");
349 bool SqlEngine::commitTransaction()
351 QSqlDatabase db = QSqlDatabase::database();
353 return execQuery(db, "COMMIT");
356 void SqlEngine::deleteConference(int id)
358 QSqlDatabase db = QSqlDatabase::database();
360 if ( !db.isValid() || !db.isOpen()) {
366 QHash<QString, QVariant> params;
367 params["xid_conference"] = id;
368 execQueryWithParameter(db, "DELETE FROM LINK WHERE xid_conference = :xid_conference", params);
369 execQueryWithParameter(db, "DELETE FROM EVENT_ROOM WHERE xid_conference = :xid_conference", params);
370 execQueryWithParameter(db, "DELETE FROM EVENT_PERSON WHERE xid_conference = :xid_conference", params);
371 execQueryWithParameter(db, "DELETE FROM EVENT WHERE xid_conference = :xid_conference", params);
372 execQueryWithParameter(db, "DELETE FROM ROOM WHERE xid_conference = :xid_conference", params);
373 execQueryWithParameter(db, "DELETE FROM PERSON WHERE xid_conference = :xid_conference", params);
374 execQueryWithParameter(db, "DELETE FROM TRACK WHERE xid_conference = :xid_conference", params);
375 execQueryWithParameter(db, "DELETE FROM CONFERENCE WHERE id = :xid_conference", params);
380 bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
382 //qDebug() << "\nSQL: " << aQuery;
384 QSqlQuery sqlQuery(aDatabase);
385 if( !sqlQuery.exec(aQuery) ){
386 qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
390 //qDebug() << "SQL OK.\n";
395 bool SqlEngine::execQueryWithParameter(QSqlDatabase &aDatabase, const QString &aQuery, const QHash<QString, QVariant>& params)
397 qDebug() << "SQL:" << aQuery << "params:" << params;
399 QSqlQuery sqlQuery(aDatabase);
400 sqlQuery.prepare(aQuery);
401 foreach (QString param_key, params.keys()) {
402 sqlQuery.bindValue(param_key, params[param_key]);
404 if( !sqlQuery.exec() ){
405 qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
409 //qDebug() << "SQL OK.\n";
414 void SqlEngine::checkConferenceMap(QSqlDatabase &aDatabase)
416 QSqlQuery sqlQuery(aDatabase);
417 sqlQuery.prepare("SELECT map FROM conference");
418 if (!sqlQuery.exec()) {
419 qWarning() << "column conference.map is missing; adding";
420 execQuery(aDatabase, "ALTER TABLE conference ADD COLUMN map VARCHAR")
421 and execQuery(aDatabase, "UPDATE conference SET map = ':/maps/campus.png' WHERE title = 'FOSDEM 2010'");