source: src/sql/sqlengine.cpp @ 926f106

qt5
Last change on this file since 926f106 was 926f106, checked in by pavelpa <pavelpa@…>, 12 years ago

parsing activity from xml

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