source: src/sql/sqlengine.cpp @ 4693fa6

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

changed 'Activity' -> 'Track'

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