temp commit for search tab
[toast/confclerk.git] / src / sql / sqlengine.cpp
1
2 #include <QSqlError>
3 #include <QSqlQuery>
4 #include <QSqlRecord>
5 #include <QVariant>
6 #include <QDateTime>
7
8 #include <QDir>
9 #include "sqlengine.h"
10
11 #include <QDebug>
12
13 const QString DATE_FORMAT ("yyyy-MM-dd");
14 const QString TIME_FORMAT ("hh:mm");
15
16 SqlEngine::SqlEngine(QObject *aParent)
17     : QObject(aParent)
18 {
19 }
20
21 SqlEngine::~SqlEngine()
22 {
23 }
24
25 QString SqlEngine::login(const QString &aDatabaseType, const QString &aDatabaseName)
26 {
27     QSqlDatabase database = QSqlDatabase::addDatabase(aDatabaseType);
28     database.setDatabaseName(aDatabaseName);
29
30     bool result = false;
31     if(!QFile::exists(aDatabaseName)) // the DB (tables) doesn't exists, and so we have to create one
32     {
33         // creating empty DB + tables
34         // ??? what is the best way of creating new empty DB ???
35         // we can either:
36         //  - create new DB + tables by issuing corresponding queries (used solution)
37         //  - create new DB from resource, which contains empty DB with tables
38         result = createTables(database);
39     }
40
41     database.open();
42
43     //LOG_INFO(QString("Opening '%1' database '%2'").arg(aDatabaseType).arg(aDatabaseName));
44
45     return result ? QString() : database.lastError().text();
46 }
47
48 void SqlEngine::initialize()
49 {
50     QString databaseName;
51     if(!QDir::home().exists(".fosdem"))
52         QDir::home().mkdir(".fosdem");
53     databaseName = QDir::homePath() + "/.fosdem/" + "fosdem.sqlite";
54     login("QSQLITE",databaseName);
55 }
56
57 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference)
58 {
59     QSqlDatabase db = QSqlDatabase::database();
60
61     if (db.isValid() && db.isOpen())
62     {
63         QString values = QString("'%1', '%2', '%3', '%4', '%5', '%6', '%7', '%8', '%9', '%10'") \
64                          .arg(aConference["id"]) \
65                          .arg(aConference["title"]) \
66                          .arg(aConference["subtitle"]) \
67                          .arg(aConference["venue"]) \
68                          .arg(aConference["city"]) \
69                          .arg(QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t()) \
70                          .arg(QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t()) \
71                          .arg(aConference["days"]) \
72                          .arg(-QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0))) \
73                          .arg(-QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
74
75         QString query = QString("INSERT INTO CONFERENCE (id,title,subtitle,venue,city,start,end,days,day_change,timeslot_duration) VALUES (%1)").arg(values);
76         QSqlQuery result (query, db);
77         //LOG_AUTOTEST(query);
78     }
79 }
80
81 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent)
82 {
83     //LOG_DEBUG(QString("Adding event '%1' to DB").arg(*aEvent));
84
85     QSqlDatabase db = QSqlDatabase::database();
86
87     if (db.isValid() && db.isOpen())
88     {
89         // The items of the Event are divided into the two tables EVENT and VIRTUAL_EVENT
90         // VIRTUAL_EVENT is for Full-Text-Serach Support
91         QDateTime startDateTime = QDateTime(QDate::fromString(aEvent["date"],DATE_FORMAT),QTime::fromString(aEvent["start"],TIME_FORMAT));
92         QString values = QString("'%1', '%2', '%3', '%4', '%5', '%6', '%7', '%8', '%9'") \
93                          .arg(aEvent["conference_id"]) \
94                          .arg(aEvent["id"]) \
95                          .arg(QString::number(startDateTime.toTime_t())) \
96                          .arg(-QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0))) \
97                          .arg("123456") \
98                          .arg(aEvent["type"]) \
99                          .arg(aEvent["language"]) \
100                          .arg("0") \
101                          .arg("0");
102
103         QString query = QString("INSERT INTO EVENT (xid_conference, id, start, duration, xid_activity, type, language, favourite, alarm) VALUES (%1)").arg(values);
104         QSqlQuery result (query, db);
105         //LOG_AUTOTEST(query);
106
107         // add some(text related) Event's items to VIRTUAL_EVENT table
108         QString values2 = QString("'%1', '%2', '%3', ? , ? , ? , ? ") \
109                           .arg(aEvent["conference_id"]) \
110                           .arg(aEvent["id"]) \
111                           .arg(aEvent["tag"]);
112
113         QString query2 = QString("INSERT INTO VIRTUAL_EVENT (xid_conference, id, tag, title, subtitle, abstract, description) VALUES (%1)").arg(values2);
114
115         QSqlQuery result2;
116         result2.prepare(query2);
117         result2.bindValue(0,aEvent["title"]);
118         result2.bindValue(1,aEvent["subtitle"]);
119         result2.bindValue(2,aEvent["abstract"]);
120         result2.bindValue(3,aEvent["description"]);
121         result2.exec();
122         //LOG_AUTOTEST(query2);
123     }
124 }
125
126
127 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson)
128 {
129     QSqlDatabase db = QSqlDatabase::database();
130
131     //TODO: check if the person doesn't exist before inserting
132     if (db.isValid() && db.isOpen())
133     {
134         QString values = QString("'%1', '%2'").arg(aPerson["id"],aPerson["name"]);
135         QString query = QString("INSERT INTO PERSON (id,name) VALUES (%1)").arg(values);
136         QSqlQuery result (query, db);
137         //LOG_AUTOTEST(query);
138
139         values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["event_id"],aPerson["id"]);
140         query = QString("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (%1)").arg(values);
141         QSqlQuery resultEventPerson (query, db);
142         //LOG_AUTOTEST(query);
143     }
144 }
145
146 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
147 {
148     QSqlDatabase db = QSqlDatabase::database();
149
150     if (db.isValid() && db.isOpen())
151     {
152         QString queryExist = QString("SELECT id FROM ROOM WHERE name='%1'").arg(aRoom["name"]);
153         QSqlQuery resultExist(queryExist,db);
154         // now we have to check whether ROOM record with 'name' exists or not,
155         // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
156         //   and assign autoincremented 'id' to aRoom
157         // - if it exists, then we need to get its 'id' and assign it to aRoom
158         int roomId = -1;
159         if(resultExist.next()) // ROOM record with 'name' already exists: we need to get its 'id'
160         {
161             roomId = resultExist.value(0).toInt();
162         }
163         else // ROOM record doesn't exist yet, need to create it
164         {
165             QString values = QString("'%1', '%2'").arg(aRoom["name"],aRoom["picture"]);
166             QString query = QString("INSERT INTO ROOM (name,picture) VALUES (%1)").arg(values);
167             QSqlQuery result (query, db);
168             roomId = result.lastInsertId().toInt(); // 'id' is assigned automatically
169             //LOG_AUTOTEST(query);
170         }
171
172         QString values = QString("'%1', '%2', '%3'").arg(aRoom["conference_id"],aRoom["event_id"],QString::number(roomId));
173         QString query = QString("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (%1)").arg(values);
174         QSqlQuery result (query, db);
175         //LOG_AUTOTEST(query);
176     }
177 }
178
179 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
180 {
181     QSqlDatabase db = QSqlDatabase::database();
182
183     //TODO: check if the link doesn't exist before inserting
184     if (db.isValid() && db.isOpen())
185     {
186         QString values = QString("'%1', '%2', '%3', '%4'").arg(aLink["event_id"],aLink["conference_id"],aLink["name"],aLink["url"]);
187         QString query = QString("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (%1)").arg(values);
188         QSqlQuery result(query, db);
189         //LOG_AUTOTEST(query);
190     }
191 }
192
193 bool SqlEngine::createTables(QSqlDatabase &aDatabase)
194 {
195     bool result = aDatabase.open();
196
197     if (aDatabase.isValid() && aDatabase.isOpen())
198     {
199         QSqlQuery query(aDatabase);
200
201         query.exec("CREATE TABLE CONFERENCE ( \
202             id INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL , \
203             title VARCHAR NOT NULL , \
204             subtitle VARCHAR, \
205             venue VARCHAR, \
206             city VARCHAR NOT NULL , \
207             start INTEGER NOT NULL , \
208             end INTEGER NOT NULL , \
209             days INTEGER, \
210             day_change INTEGER, \
211             timeslot_duration INTEGER)");
212
213         query.exec("CREATE TABLE ACTIVITY ( \
214             id INTEGER  PRIMARY KEY AUTOINCREMENT  NOT NULL , \
215             name VARCHAR NOT NULL )");
216
217         query.exec("CREATE TABLE ROOM ( \
218             id INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL , \
219             name VARCHAR NOT NULL , \
220             picture VARCHAR NOT NULL)");
221
222         query.exec("CREATE TABLE PERSON ( \
223             id INTEGER PRIMARY KEY  NOT NULL , \
224             name VARCHAR NOT NULL)");
225
226         query.exec("CREATE TABLE EVENT ( \
227             xid_conference INTEGER  NOT NULL, \
228             id INTEGER NOT NULL , \
229             start INTEGER NOT NULL , \
230             duration INTEGER NOT NULL , \
231             xid_activity INTEGER NOT NULL REFERENCES ACTIVITY(id), \
232             type VARCHAR, \
233             language VARCHAR, \
234             favourite INTEGER DEFAULT 0, \
235             alarm INTEGER DEFAULT 0, \
236             PRIMARY KEY (xid_conference,id), \
237             FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id) \
238             FOREIGN KEY(xid_activity) REFERENCES ACTIVITY(id))");
239
240 #ifdef MAEMO
241         // TBD: MAEMO Virtual tables compatibility (waiting for Marek).
242         // MAEMO sqlite Qt driver doesn't provide FTS support by default - use the following HACK
243         query.exec("CREATE TABLE VIRTUAL_EVENT ( \
244             xid_conference INTEGER  NOT NULL, \
245             id INTEGER NOT NULL , \
246             tag VARCHAR,title VARCHAR NOT NULL , \
247             subtitle VARCHAR, \
248             abstract VARCHAR, \
249             description VARCHAR, \
250             PRIMARY KEY (xid_conference,id))");
251 #else
252         query.exec("CREATE VIRTUAL TABLE VIRTUAL_EVENT using fts3 ( \
253             xid_conference INTEGER  NOT NULL, \
254             id INTEGER NOT NULL , \
255             tag VARCHAR,title VARCHAR NOT NULL , \
256             subtitle VARCHAR, \
257             abstract VARCHAR, \
258             description VARCHAR, \
259             PRIMARY KEY (xid_conference,id))");
260 #endif
261
262         query.exec("CREATE TABLE EVENT_PERSON ( \
263             xid_conference INTEGER NOT NULL , \
264             xid_event INTEGER NOT NULL , \
265             xid_person INTEGER NOT NULL, \
266             FOREIGN KEY(xid_conference, xid_event) REFERENCES EVENT(xid_conference, id), \
267             FOREIGN KEY(xid_person) REFERENCES PERSON(id))");
268
269         query.exec("CREATE TABLE EVENT_ROOM ( \
270             xid_conference INTEGER NOT NULL , \
271             xid_event INTEGER NOT NULL , \
272             xid_room INTEGER NOT NULL, \
273             FOREIGN KEY(xid_conference, xid_event) REFERENCES EVENT(xid_conference, id), \
274             FOREIGN KEY(xid_room) REFERENCES ROOM(id))");
275
276         query.exec("CREATE TABLE LINK ( \
277             id INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL, \
278             xid_conference INTEGER NOT NULL, \
279             xid_event INTEGER NOT NULL, \
280             name VARCHAR, \
281             url VARCHAR NOT NULL, \
282             FOREIGN KEY(xid_conference, xid_event) REFERENCES EVENT(xid_conference, id))");
283     }
284     else
285     {
286         //LOG_WARNING("Database is not opened");
287     }
288
289     return result;
290 }
291
292 int SqlEngine::searchEvent(int aConferenceId, const QList<QString> &aColumns, const QString &aKeyword)
293 {
294     QSqlDatabase db = QSqlDatabase::database();
295
296     if ( !db.isValid() || !db.isOpen())
297         return -1;
298
299     QString query = QString(
300         "DROP TABLE IF EXISTS SEARCH_EVENT;"
301         "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER  NOT NULL, id INTEGER NOT NULL );"
302         "INSERT INTO SEARCH_EVENT ( xid_conference, id) "
303             "SELECT xid_conference, id FROM EVENT AS e INNER JOIN VIRTUAL_EVENT AS ve USING (xid_conference, id) "
304             "WHERE xid_conference = %1 AND (").arg( aConferenceId );
305
306     int i = 0;
307     foreach (QString str, aColumns){
308         query += QString("%1 LIKE '\%%2\%' OR ").arg( aColumns.at(i++), aKeyword );
309     }
310     query.chop( QString(" OR ").length() );
311     query += QString(");");
312
313     qDebug() << "\nSQL: " << query;
314
315     db.exec();
316
317     if( db.lastError().isValid() && db.lastError().number() != 0 ){
318         qDebug() << "SQL ERR: " << db.lastError().number() << ", " << db.lastError().text();
319         return 0;
320     }
321     else{
322         qDebug() << "SQL OK.\n";
323         return 1;
324     }
325
326 }