source: src/sql/sqlengine.cpp @ 979e5be

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

created resource which contains parsed schedule,
so the user doesn't have to parse it by himself

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