source: src/sql/sqlengine.cpp @ 005e2b7

qt5
Last change on this file since 005e2b7 was 005e2b7, checked in by korrco <korrco@…>, 12 years ago

caching removed

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