source: src/sql/sqlengine.cpp @ b4e9936

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

changed permissions for the db

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