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();
159 QString values = QString("'%1', '%2', '%3', '%4', '%5', '%6', '%7', ? , ? , ? , ? , ? , '%8', '%9'") \
160 .arg(aEvent["conference_id"]) \
162 .arg(QString::number(startDateTime.toTime_t())) \
163 .arg(-QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0))) \
165 .arg(aEvent["type"]) \
166 .arg(aEvent["language"]) \
171 QString("INSERT INTO EVENT (xid_conference, id, start, duration, xid_track, type, language, tag, title, subtitle, abstract, description, favourite, alarm) VALUES (%1)")
176 result.prepare(query);
177 result.bindValue(0,aEvent["tag"]);
178 result.bindValue(1,aEvent["title"]);
179 result.bindValue(2,aEvent["subtitle"]);
180 result.bindValue(3,aEvent["abstract"]);
181 result.bindValue(4,aEvent["description"]);
186 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson)
188 QSqlDatabase db = QSqlDatabase::database();
190 //TODO: check if the person doesn't exist before inserting
191 if (db.isValid() && db.isOpen())
193 QString values = QString("'%1', '%2'").arg(aPerson["id"],aPerson["name"]);
194 QString query = QString("INSERT INTO PERSON (id,name) VALUES (%1)").arg(values);
195 QSqlQuery result (query, db);
196 //LOG_AUTOTEST(query);
198 values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["event_id"],aPerson["id"]);
199 query = QString("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (%1)").arg(values);
200 QSqlQuery resultEventPerson (query, db);
201 //LOG_AUTOTEST(query);
205 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
207 QSqlDatabase db = QSqlDatabase::database();
209 if (db.isValid() && db.isOpen())
211 QString queryExist = QString("SELECT id FROM ROOM WHERE name='%1'").arg(aRoom["name"]);
212 QSqlQuery resultExist(queryExist,db);
213 // now we have to check whether ROOM record with 'name' exists or not,
214 // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
215 // and assign autoincremented 'id' to aRoom
216 // - if it exists, then we need to get its 'id' and assign it to aRoom
218 if(resultExist.next()) // ROOM record with 'name' already exists: we need to get its 'id'
220 roomId = resultExist.value(0).toInt();
222 else // ROOM record doesn't exist yet, need to create it
224 QString values = QString("'%1', '%2'").arg(aRoom["name"],aRoom["picture"]);
225 QString query = QString("INSERT INTO ROOM (name,picture) VALUES (%1)").arg(values);
226 QSqlQuery result (query, db);
227 roomId = result.lastInsertId().toInt(); // 'id' is assigned automatically
228 //LOG_AUTOTEST(query);
231 QString values = QString("'%1', '%2', '%3'").arg(aRoom["conference_id"],aRoom["event_id"],QString::number(roomId));
232 QString query = QString("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (%1)").arg(values);
233 QSqlQuery result (query, db);
234 //LOG_AUTOTEST(query);
238 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
240 QSqlDatabase db = QSqlDatabase::database();
242 //TODO: check if the link doesn't exist before inserting
243 if (db.isValid() && db.isOpen())
245 QString values = QString("'%1', '%2', '%3', '%4'").arg(aLink["event_id"],aLink["conference_id"],aLink["name"],aLink["url"]);
246 QString query = QString("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (%1)").arg(values);
247 QSqlQuery result(query, db);
248 //LOG_AUTOTEST(query);
252 bool SqlEngine::createTables(QSqlDatabase &aDatabase)
254 bool result = aDatabase.open();
256 if (aDatabase.isValid() && aDatabase.isOpen())
258 QSqlQuery query(aDatabase);
260 query.exec("CREATE TABLE CONFERENCE ( "
261 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
262 "title VARCHAR UNIQUE NOT NULL, "
265 "city VARCHAR NOT NULL, "
266 "start INTEGER NOT NULL, "
267 "end INTEGER NOT NULL, "
269 "day_change INTEGER, "
270 "timeslot_duration INTEGER, "
271 "active INTEGER DEFAULT 0);");
273 query.exec("CREATE TABLE TRACK ( "
274 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
275 "name VARCHAR UNIQUE NOT NULL );");
277 query.exec("CREATE TABLE ROOM ( "
278 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
279 "name VARCHAR UNIQUE NOT NULL, "
280 "picture VARCHAR NOT NULL);");
282 query.exec("CREATE TABLE PERSON ( "
283 "id INTEGER PRIMARY KEY NOT NULL, "
284 "name VARCHAR UNIQUE NOT NULL);");
286 query.exec("CREATE TABLE EVENT ( "
287 "xid_conference INTEGER NOT NULL, "
288 "id INTEGER NOT NULL, "
289 "start INTEGER NOT NULL, "
290 "duration INTEGER NOT NULL, "
291 "xid_track INTEGER NOT NULL REFERENCES TRACK(id), "
294 "tag VARCHAR,title VARCHAR NOT NULL, "
297 "description VARCHAR, "
298 "favourite INTEGER DEFAULT 0, "
299 "alarm INTEGER DEFAULT 0, "
300 "PRIMARY KEY (xid_conference,id) ON CONFLICT REPLACE, "
301 "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
302 "FOREIGN KEY(xid_track) REFERENCES TRACK(id));");
304 query.exec("CREATE TABLE EVENT_PERSON ( "
305 "xid_conference INTEGER NOT NULL, "
306 "xid_event INTEGER NOT NULL, "
307 "xid_person INTEGER NOT NULL, "
308 "UNIQUE ( xid_conference, xid_event, xid_person ) ON CONFLICT REPLACE, "
309 "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
310 "FOREIGN KEY(xid_event) REFERENCES EVENT(id), "
311 "FOREIGN KEY(xid_person) REFERENCES PERSON(id));");
313 query.exec("CREATE TABLE EVENT_ROOM ( "
314 "xid_conference INTEGER NOT NULL, "
315 "xid_event INTEGER NOT NULL, "
316 "xid_room INTEGER NOT NULL, "
317 "UNIQUE ( xid_conference, xid_event, xid_room ) ON CONFLICT REPLACE, "
318 "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
319 "FOREIGN KEY(xid_event) REFERENCES EVENT(id), "
320 "FOREIGN KEY(xid_room) REFERENCES ROOM(id));");
322 query.exec("CREATE TABLE LINK ( "
323 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
324 "xid_conference INTEGER NOT NULL, "
325 "xid_event INTEGER NOT NULL, "
327 "url VARCHAR NOT NULL, "
328 "UNIQUE ( xid_conference, xid_event, url ) ON CONFLICT REPLACE, "
329 "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
330 "FOREIGN KEY(xid_event) REFERENCES EVENT(id));");
334 //LOG_WARNING("Database is not opened");
340 int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword)
342 QSqlDatabase db = QSqlDatabase::database();
344 if ( !db.isValid() || !db.isOpen())
349 execQuery( db, "DROP TABLE IF EXISTS SEARCH_EVENT;");
351 execQuery( db, "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL );");
353 QString query = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
354 "SELECT EVENT.xid_conference, EVENT.id FROM EVENT ");
355 if( aColumns.contains("ROOM") ){
356 query += "INNER JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
357 query += "INNER JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
359 if( aColumns.contains("PERSON") ){
360 query += "INNER JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
361 query += "INNER JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
363 query += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
365 foreach (QString table, aColumns.uniqueKeys()){
366 foreach (QString column, aColumns.values(table)){
367 query += QString("%1.%2 LIKE '\%%3\%' OR ").arg( table, column, aKeyword );
370 query.chop( QString(" OR ").length() );
371 query += QString(");");
373 execQuery( db, query );
378 bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
380 //qDebug() << "\nSQL: " << aQuery;
382 QSqlQuery sqlQuery(aDatabase);
383 if( !sqlQuery.exec(aQuery) ){
384 qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
388 //qDebug() << "SQL OK.\n";