source: src/sql/sqlengine.cpp @ bcf67d6

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

search fixed

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