source: src/sql/sqlengine.cpp @ 72cd3af

qt5
Last change on this file since 72cd3af was 72cd3af, checked in by korrco <korrco@…>, 12 years ago

activities tab implemented

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