[svn-upgrade] Integrating new upstream version, fosdem-schedule (0.4.1+ds)
[debian/fosdem-schedule.git] / src / sql / sqlengine.cpp
1 /*
2  * Copyright (C) 2010 Ixonos Plc.
3  *
4  * This file is part of fosdem-schedule.
5  *
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)
9  * any later version.
10  *
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
14  * more details.
15  *
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/>.
18  */
19
20 #include <QSqlError>
21 #include <QSqlQuery>
22 #include <QSqlRecord>
23 #include <QVariant>
24 #include <QDateTime>
25
26 #include <QDir>
27 #include "sqlengine.h"
28 #include <track.h>
29 #include <conference.h>
30
31 #include <QDebug>
32
33 const QString DATE_FORMAT ("yyyy-MM-dd");
34 const QString TIME_FORMAT ("hh:mm");
35
36 SqlEngine::SqlEngine(QObject *aParent)
37     : QObject(aParent)
38 {
39 }
40
41 SqlEngine::~SqlEngine()
42 {
43 }
44
45 QString SqlEngine::login(const QString &aDatabaseType, const QString &aDatabaseName)
46 {
47     QSqlDatabase database = QSqlDatabase::addDatabase(aDatabaseType);
48     database.setDatabaseName(aDatabaseName);
49
50     bool result = false;
51     if(!QFile::exists(aDatabaseName)) // the DB (tables) doesn't exists, and so we have to create one
52     {
53         /*
54         // creating empty DB + tables
55         // ??? what is the best way of creating new empty DB ???
56         // we can either:
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);
60         */
61
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);
67         database.open();
68     }
69     else
70     {
71         database.open();
72     }
73
74     //LOG_INFO(QString("Opening '%1' database '%2'").arg(aDatabaseType).arg(aDatabaseName));
75
76     return result ? QString() : database.lastError().text();
77 }
78
79 void SqlEngine::initialize()
80 {
81     QString databaseName;
82     if(!QDir::home().exists(".fosdem"))
83         QDir::home().mkdir(".fosdem");
84     databaseName = QDir::homePath() + "/.fosdem/" + "fosdem.sqlite";
85     login("QSQLITE",databaseName);
86 }
87
88 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference)
89 {
90     QSqlDatabase db = QSqlDatabase::database();
91
92     if (db.isValid() && db.isOpen())
93     {
94         int confId = 0;
95         QList<Conference> confsList = Conference::getAll();
96         if(confsList.count())
97         {
98             QListIterator<Conference> i(confsList);
99             while (i.hasNext())
100             {
101                 Conference conf = i.next();
102                 if( aConference["title"] == conf.title() )
103                 {
104                     confId = conf.id();
105                     aConference["id"] = QString::number(confId);
106                     break;
107                 }
108             }
109         }
110
111         if(!confId) // conference 'aConference' isn't in the table => insert
112         {
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"));
124
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
128         }
129     }
130 }
131
132 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent)
133 {
134     //LOG_DEBUG(QString("Adding event '%1' to DB").arg(*aEvent));
135
136     QSqlDatabase db = QSqlDatabase::database();
137
138     if (db.isValid() && db.isOpen())
139     {
140         //insert event track to table and get track id
141         QString name = aEvent["track"];
142         Track track;
143         int trackId;
144         try
145         {
146             track = Track::retrieveByName(name);
147             trackId = track.id();
148             /*qDebug() << QString("DEBUG: Track %1 in DB").arg(name);*/
149         }
150         catch (OrmNoObjectException &e) {
151             track.setName(name);
152             trackId = track.insert();
153             /*qDebug() << QString("DEBUG: Track %1 added to DB").arg(name);*/
154         }
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"]) \
161                          .arg(aEvent["id"]) \
162                          .arg(QString::number(startDateTime.toTime_t())) \
163                          .arg(-QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0))) \
164                          .arg(trackId) \
165                          .arg(aEvent["type"]) \
166                          .arg(aEvent["language"]) \
167                          .arg("0") \
168                          .arg("0");
169
170         QString query =
171             QString("INSERT INTO EVENT (xid_conference, id, start, duration, xid_track, type, language, tag, title, subtitle, abstract, description, favourite, alarm) VALUES (%1)")
172             .arg(values);
173
174         qDebug() << query;
175         QSqlQuery result;
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"]);
182         result.exec();
183     }
184 }
185
186 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson)
187 {
188     QSqlDatabase db = QSqlDatabase::database();
189
190     //TODO: check if the person doesn't exist before inserting
191     if (db.isValid() && db.isOpen())
192     {
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);
197
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);
202     }
203 }
204
205 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
206 {
207     QSqlDatabase db = QSqlDatabase::database();
208
209     if (db.isValid() && db.isOpen())
210     {
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
217         int roomId = -1;
218         if(resultExist.next()) // ROOM record with 'name' already exists: we need to get its 'id'
219         {
220             roomId = resultExist.value(0).toInt();
221         }
222         else // ROOM record doesn't exist yet, need to create it
223         {
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);
229         }
230
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);
235     }
236 }
237
238 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
239 {
240     QSqlDatabase db = QSqlDatabase::database();
241
242     //TODO: check if the link doesn't exist before inserting
243     if (db.isValid() && db.isOpen())
244     {
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);
249     }
250 }
251
252 bool SqlEngine::createTables(QSqlDatabase &aDatabase)
253 {
254     bool result = aDatabase.open();
255
256     if (aDatabase.isValid() && aDatabase.isOpen())
257     {
258         QSqlQuery query(aDatabase);
259
260         query.exec("CREATE TABLE CONFERENCE ( "
261             "id INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL, "
262             "title VARCHAR UNIQUE NOT NULL, "
263             "subtitle VARCHAR, "
264             "venue VARCHAR, "
265             "city VARCHAR NOT NULL, "
266             "start INTEGER NOT NULL, "
267             "end INTEGER NOT NULL, "
268             "days INTEGER, "
269             "day_change INTEGER, "
270             "timeslot_duration INTEGER, "
271             "active INTEGER DEFAULT 0);");
272
273         query.exec("CREATE TABLE TRACK ( "
274             "id INTEGER  PRIMARY KEY AUTOINCREMENT  NOT NULL, "
275             "name VARCHAR UNIQUE NOT NULL );");
276
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);");
281
282         query.exec("CREATE TABLE PERSON ( "
283             "id INTEGER PRIMARY KEY  NOT NULL, "
284             "name VARCHAR UNIQUE NOT NULL);");
285
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), "
292             "type VARCHAR, "
293             "language VARCHAR, "
294             "tag VARCHAR,title VARCHAR NOT NULL, "
295             "subtitle VARCHAR, "
296             "abstract VARCHAR, "
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));");
303
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));");
312
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));");
321
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, "
326             "name VARCHAR, "
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));");
331     }
332     else
333     {
334         //LOG_WARNING("Database is not opened");
335     }
336
337     return result;
338 }
339
340 int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword)
341 {
342     QSqlDatabase db = QSqlDatabase::database();
343
344     if ( !db.isValid() || !db.isOpen())
345         return -1;
346
347
348     // DROP
349     execQuery( db, "DROP TABLE IF EXISTS SEARCH_EVENT;");
350     // CREATE
351     execQuery( db, "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER  NOT NULL, id INTEGER NOT NULL );");
352     // INSERT
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 ) ";
358     }
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 ) ";
362     }
363     query += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
364
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 );
368         }
369     }
370     query.chop( QString(" OR ").length() );
371     query += QString(");");
372
373     execQuery( db, query );
374
375     return 1;
376 }
377
378 bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
379 {
380     //qDebug() << "\nSQL: " << aQuery;
381
382     QSqlQuery sqlQuery(aDatabase);
383     if( !sqlQuery.exec(aQuery) ){
384        qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
385        return false;
386     }
387     else{
388        //qDebug() << "SQL OK.\n";
389        return true;
390     }
391 }
392