source: src/sql/sqlengine.cpp @ e662750

qt5
Last change on this file since e662750 was e662750, checked in by timkoma <timkoma@…>, 12 years ago

first working version of the search

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