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 // creating empty DB + tables
55 // ??? what is the best way of creating new empty DB ???
57 // - create new DB + tables by issuing corresponding queries (used solution)
58 // - create new DB from resource, which contains empty DB with tables
59 result = createTables(database);
62 // copy conference Db from resource, instead of creating
63 // empty tables and then parsing the schedule
64 QFile dbFile(aDatabaseName);
65 QFile(":/fosdem.sqlite").copy(aDatabaseName);
66 dbFile.setPermissions(QFile::ReadOwner | QFile::WriteOwner | QFile::ReadGroup | QFile::WriteGroup);
74 //LOG_INFO(QString("Opening '%1' database '%2'").arg(aDatabaseType).arg(aDatabaseName));
76 return result ? QString() : database.lastError().text();
79 void SqlEngine::initialize()
82 if(!QDir::home().exists(".fosdem"))
83 QDir::home().mkdir(".fosdem");
84 databaseName = QDir::homePath() + "/.fosdem/" + "fosdem.sqlite";
85 login("QSQLITE",databaseName);
88 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference)
90 QSqlDatabase db = QSqlDatabase::database();
92 if (db.isValid() && db.isOpen())
95 QList<Conference> confsList = Conference::getAll();
98 QListIterator<Conference> i(confsList);
101 Conference conf = i.next();
102 if( aConference["title"] == conf.title() )
105 aConference["id"] = QString::number(confId);
111 if(!confId) // conference 'aConference' isn't in the table => insert
113 QString values = QString("'%1', '%2', '%3', '%4', '%5', '%6', '%7', '%8', '%9'") \
114 .arg(aConference["title"]) \
115 .arg(aConference["subtitle"]) \
116 .arg(aConference["venue"]) \
117 .arg(aConference["city"]) \
118 .arg(QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t()) \
119 .arg(QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t()) \
120 .arg(aConference["days"]) \
121 .arg(-QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0))) \
122 .arg(-QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
123 values.append(QString(", '%1'").arg(confsList.count()>0?"0":"1"));
125 QString query = QString("INSERT INTO CONFERENCE (title,subtitle,venue,city,start,end,days,day_change,timeslot_duration,active) VALUES (%1)").arg(values);
126 QSqlQuery result (query, db);
127 aConference["id"] = result.lastInsertId().toString(); // 'id' is assigned automatically
132 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent)
134 //LOG_DEBUG(QString("Adding event '%1' to DB").arg(*aEvent));
136 QSqlDatabase db = QSqlDatabase::database();
138 if (db.isValid() && db.isOpen())
140 //insert event track to table and get track id
141 QString name = aEvent["track"];
146 track = Track::retrieveByName(name);
147 trackId = track.id();
148 /*qDebug() << QString("DEBUG: Track %1 in DB").arg(name);*/
150 catch (OrmNoObjectException &e) {
152 trackId = track.insert();
153 /*qDebug() << QString("DEBUG: Track %1 added to DB").arg(name);*/
155 QDateTime startDateTime;
156 startDateTime.setTimeSpec(Qt::UTC);
157 startDateTime = QDateTime(QDate::fromString(aEvent["date"],DATE_FORMAT),QTime::fromString(aEvent["start"],TIME_FORMAT),Qt::UTC);
158 qDebug() << "startDateTime: " << startDateTime.toString();
160 bool event_exists = false;
162 QSqlQuery check_event_query;
163 check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
164 check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
165 check_event_query.bindValue(":id", aEvent["id"]);
166 if (!check_event_query.exec()) {
167 qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
168 << "event id:" << aEvent["id"]
169 << "error:" << check_event_query.lastError()
173 if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
180 result.prepare("UPDATE EVENT SET"
182 ", duration = :duration"
183 ", xid_track = :xid_track"
185 ", language = :language"
188 ", subtitle = :subtitle"
189 ", abstract = :abstract"
190 ", description = :description"
191 " WHERE id = :id AND xid_conference = :xid_conference");
193 result.prepare("INSERT INTO EVENT "
194 " (xid_conference, id, start, duration, xid_track, type, "
195 " language, tag, title, subtitle, abstract, description) "
196 " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
197 ":language, :tag, :title, :subtitle, :abstract, :description)");
199 result.bindValue(":xid_conference", aEvent["conference_id"]);
200 result.bindValue(":start", QString::number(startDateTime.toTime_t()));
201 result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
202 result.bindValue(":xid_track", trackId);
203 static const QList<QString> props = QList<QString>()
204 << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
205 foreach (QString prop_name, props) {
206 result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
208 if (!result.exec()) {
209 qWarning() << "event insert/update failed:" << result.lastError();
214 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson)
216 QSqlDatabase db = QSqlDatabase::database();
218 //TODO: check if the person doesn't exist before inserting
219 if (db.isValid() && db.isOpen())
221 QString values = QString("'%1', '%2'").arg(aPerson["id"],aPerson["name"]);
222 QString query = QString("INSERT INTO PERSON (id,name) VALUES (%1)").arg(values);
223 QSqlQuery result (query, db);
224 //LOG_AUTOTEST(query);
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())
239 QString queryExist = QString("SELECT id FROM ROOM WHERE name='%1'").arg(aRoom["name"]);
240 QSqlQuery resultExist(queryExist,db);
241 // now we have to check whether ROOM record with 'name' exists or not,
242 // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
243 // and assign autoincremented 'id' to aRoom
244 // - if it exists, then we need to get its 'id' and assign it to aRoom
246 if(resultExist.next()) // ROOM record with 'name' already exists: we need to get its 'id'
248 roomId = resultExist.value(0).toInt();
250 else // ROOM record doesn't exist yet, need to create it
252 QString values = QString("'%1', '%2'").arg(aRoom["name"],aRoom["picture"]);
253 QString query = QString("INSERT INTO ROOM (name,picture) VALUES (%1)").arg(values);
254 QSqlQuery result (query, db);
255 roomId = result.lastInsertId().toInt(); // 'id' is assigned automatically
256 //LOG_AUTOTEST(query);
259 QString values = QString("'%1', '%2', '%3'").arg(aRoom["conference_id"],aRoom["event_id"],QString::number(roomId));
260 QString query = QString("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (%1)").arg(values);
261 QSqlQuery result (query, db);
262 //LOG_AUTOTEST(query);
266 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
268 QSqlDatabase db = QSqlDatabase::database();
270 //TODO: check if the link doesn't exist before inserting
271 if (db.isValid() && db.isOpen())
273 QString values = QString("'%1', '%2', '%3', '%4'").arg(aLink["event_id"],aLink["conference_id"],aLink["name"],aLink["url"]);
274 QString query = QString("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (%1)").arg(values);
275 QSqlQuery result(query, db);
276 //LOG_AUTOTEST(query);
280 bool SqlEngine::createTables(QSqlDatabase &aDatabase)
282 bool result = aDatabase.open();
284 if (aDatabase.isValid() && aDatabase.isOpen())
286 QSqlQuery query(aDatabase);
288 query.exec("CREATE TABLE CONFERENCE ( "
289 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
290 "title VARCHAR UNIQUE NOT NULL, "
293 "city VARCHAR NOT NULL, "
294 "start INTEGER NOT NULL, "
295 "end INTEGER NOT NULL, "
297 "day_change INTEGER, "
298 "timeslot_duration INTEGER, "
299 "active INTEGER DEFAULT 0);");
301 query.exec("CREATE TABLE TRACK ( "
302 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
303 "name VARCHAR UNIQUE NOT NULL );");
305 query.exec("CREATE TABLE ROOM ( "
306 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
307 "name VARCHAR UNIQUE NOT NULL, "
308 "picture VARCHAR NOT NULL);");
310 query.exec("CREATE TABLE PERSON ( "
311 "id INTEGER PRIMARY KEY NOT NULL, "
312 "name VARCHAR UNIQUE NOT NULL);");
314 query.exec("CREATE TABLE EVENT ( "
315 "xid_conference INTEGER NOT NULL, "
316 "id INTEGER NOT NULL, "
317 "start INTEGER NOT NULL, "
318 "duration INTEGER NOT NULL, "
319 "xid_track INTEGER NOT NULL REFERENCES TRACK(id), "
322 "tag VARCHAR,title VARCHAR NOT NULL, "
325 "description VARCHAR, "
326 "favourite INTEGER DEFAULT 0, "
327 "alarm INTEGER DEFAULT 0, "
328 "PRIMARY KEY (xid_conference,id), "
329 "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
330 "FOREIGN KEY(xid_track) REFERENCES TRACK(id));");
332 query.exec("CREATE TABLE EVENT_PERSON ( "
333 "xid_conference INTEGER NOT NULL, "
334 "xid_event INTEGER NOT NULL, "
335 "xid_person INTEGER NOT NULL, "
336 "UNIQUE ( xid_conference, xid_event, xid_person ) ON CONFLICT REPLACE, "
337 "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
338 "FOREIGN KEY(xid_event) REFERENCES EVENT(id), "
339 "FOREIGN KEY(xid_person) REFERENCES PERSON(id));");
341 query.exec("CREATE TABLE EVENT_ROOM ( "
342 "xid_conference INTEGER NOT NULL, "
343 "xid_event INTEGER NOT NULL, "
344 "xid_room INTEGER NOT NULL, "
345 "UNIQUE ( xid_conference, xid_event, xid_room ) ON CONFLICT REPLACE, "
346 "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
347 "FOREIGN KEY(xid_event) REFERENCES EVENT(id), "
348 "FOREIGN KEY(xid_room) REFERENCES ROOM(id));");
350 query.exec("CREATE TABLE LINK ( "
351 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
352 "xid_conference INTEGER NOT NULL, "
353 "xid_event INTEGER NOT NULL, "
355 "url VARCHAR NOT NULL, "
356 "UNIQUE ( xid_conference, xid_event, url ) ON CONFLICT REPLACE, "
357 "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
358 "FOREIGN KEY(xid_event) REFERENCES EVENT(id));");
362 //LOG_WARNING("Database is not opened");
368 int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword)
370 QSqlDatabase db = QSqlDatabase::database();
372 if ( !db.isValid() || !db.isOpen())
377 execQuery( db, "DROP TABLE IF EXISTS SEARCH_EVENT;");
379 execQuery( db, "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL );");
381 QString query = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
382 "SELECT EVENT.xid_conference, EVENT.id FROM EVENT ");
383 if( aColumns.contains("ROOM") ){
384 query += "INNER JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
385 query += "INNER JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
387 if( aColumns.contains("PERSON") ){
388 query += "INNER JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
389 query += "INNER JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
391 query += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
393 foreach (QString table, aColumns.uniqueKeys()){
394 foreach (QString column, aColumns.values(table)){
395 query += QString("%1.%2 LIKE '\%%3\%' OR ").arg( table, column, aKeyword );
398 query.chop( QString(" OR ").length() );
399 query += QString(");");
401 execQuery( db, query );
406 bool SqlEngine::beginTransaction()
408 QSqlDatabase db = QSqlDatabase::database();
410 return execQuery(db, "BEGIN IMMEDIATE TRANSACTION");
413 bool SqlEngine::commitTransaction()
415 QSqlDatabase db = QSqlDatabase::database();
417 return execQuery(db, "COMMIT");
420 bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
422 //qDebug() << "\nSQL: " << aQuery;
424 QSqlQuery sqlQuery(aDatabase);
425 if( !sqlQuery.exec(aQuery) ){
426 qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
430 //qDebug() << "SQL OK.\n";