source: src/sql/sqlengine.cpp @ 89ff5f2

qt5
Last change on this file since 89ff5f2 was 89ff5f2, checked in by timkoma <timkoma@…>, 12 years ago

unique constraints added into sql

  • Property mode set to 100644
File size: 13.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 UNIQUE 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 UNIQUE NOT NULL, "
252            "picture VARCHAR NOT NULL);");
253
254        query.exec("CREATE TABLE PERSON ( "
255            "id INTEGER PRIMARY KEY  NOT NULL, "
256            "name VARCHAR UNIQUE 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            "UNIQUE ( xid_conference, xid_event, xid_person ) ON CONFLICT IGNORE, "
281            "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
282            "FOREIGN KEY(xid_event) REFERENCES EVENT(id), "
283            "FOREIGN KEY(xid_person) REFERENCES PERSON(id));");
284
285        query.exec("CREATE TABLE EVENT_ROOM ( "
286            "xid_conference INTEGER NOT NULL, "
287            "xid_event INTEGER NOT NULL, "
288            "xid_room INTEGER NOT NULL, "
289            "UNIQUE ( xid_conference, xid_event, xid_room ) ON CONFLICT IGNORE, "
290            "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
291            "FOREIGN KEY(xid_event) REFERENCES EVENT(id), "
292            "FOREIGN KEY(xid_room) REFERENCES ROOM(id));");
293
294        query.exec("CREATE TABLE LINK ( "
295            "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
296            "xid_conference INTEGER NOT NULL, "
297            "xid_event INTEGER NOT NULL, "
298            "name VARCHAR, "
299            "url VARCHAR NOT NULL, "
300            "UNIQUE ( xid_conference, xid_event, url ) ON CONFLICT IGNORE, "
301            "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
302            "FOREIGN KEY(xid_event) REFERENCES EVENT(id));");
303    }
304    else
305    {
306        //LOG_WARNING("Database is not opened");
307    }
308
309    return result;
310}
311
312int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword)
313{
314    QSqlDatabase db = QSqlDatabase::database();
315
316    if ( !db.isValid() || !db.isOpen())
317        return -1;
318
319
320    // DROP
321    execQuery( db, "DROP TABLE IF EXISTS SEARCH_EVENT;");
322    // CREATE
323    execQuery( db, "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER  NOT NULL, id INTEGER NOT NULL );");
324    // INSERT
325    QString query = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id) "
326                "SELECT EVENT.xid_conference, EVENT.id FROM EVENT ");
327    if( aColumns.contains("ROOM") ){
328        query += "INNER JOIN EVENT_ROOM ON (EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
329        query += "INNER JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
330    }
331    if( aColumns.contains("PERSON") ){
332        query += "INNER JOIN EVENT_PERSON ON (EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
333        query += "INNER JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
334    }
335    query += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
336
337    foreach (QString table, aColumns.uniqueKeys()){
338        foreach (QString column, aColumns.values(table)){
339            query += QString("%1.%2 LIKE '\%%3\%' OR ").arg( table, column, aKeyword );
340        }
341    }
342    query.chop( QString(" OR ").length() );
343    query += QString(");");
344
345    execQuery( db, query );
346
347    //TODO: retun number of rows from SEARCH_EVENT
348    return 1;
349}
350
351bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
352{
353    qDebug() << "\nSQL: " << aQuery;
354
355    QSqlQuery sqlQuery(aDatabase);
356    if( !sqlQuery.exec(aQuery) ){
357       qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
358       return false;
359    }
360    else{
361       qDebug() << "SQL OK.\n";
362       return true;
363    }
364}
Note: See TracBrowser for help on using the repository browser.