source: src/sql/sqlengine.cpp @ 0bb39f5

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

removed appsettings

  • created 'active' column in 'conference' table
  • 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        // 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    }
42    else
43    {
44        database.open();
45    }
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    {
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)));
96                             values.append(QString(", '%1'").arg(confsList.count()>0?"0":"1"));
97
98            QString query = QString("INSERT INTO CONFERENCE (title,subtitle,venue,city,start,end,days,day_change,timeslot_duration,active) VALUES (%1)").arg(values);
99            QSqlQuery result (query, db);
100            aConference["id"] = result.lastInsertId().toString(); // 'id' is assigned automatically
101        }
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    {
113        //insert event track to table and get track id
114        QString name = aEvent["track"];
115        Track track;
116        int trackId;
117        try
118        {
119            track = Track::retrieveByName(name);
120            trackId = track.id();
121            /*qDebug() << QString("DEBUG: Track %1 in DB").arg(name);*/
122        }
123        catch (OrmNoObjectException &e) {
124            track.setName(name);
125            trackId = track.insert();
126            /*qDebug() << QString("DEBUG: Track %1 added to DB").arg(name);*/
127        }
128        QDateTime startDateTime = QDateTime(QDate::fromString(aEvent["date"],DATE_FORMAT),QTime::fromString(aEvent["start"],TIME_FORMAT));
129        QString values = QString("'%1', '%2', '%3', '%4', '%5', '%6', '%7', ? , ? , ? , ? , ? , '%8', '%9'") \
130                         .arg(aEvent["conference_id"]) \
131                         .arg(aEvent["id"]) \
132                         .arg(QString::number(startDateTime.toTime_t())) \
133                         .arg(-QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0))) \
134                         .arg(trackId) \
135                         .arg(aEvent["type"]) \
136                         .arg(aEvent["language"]) \
137                         .arg("0") \
138                         .arg("0");
139
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();
152    }
153}
154
155
156void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson)
157{
158    QSqlDatabase db = QSqlDatabase::database();
159
160    //TODO: check if the person doesn't exist before inserting
161    if (db.isValid() && db.isOpen())
162    {
163        QString values = QString("'%1', '%2'").arg(aPerson["id"],aPerson["name"]);
164        QString query = QString("INSERT INTO PERSON (id,name) VALUES (%1)").arg(values);
165        QSqlQuery result (query, db);
166        //LOG_AUTOTEST(query);
167
168        values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["event_id"],aPerson["id"]);
169        query = QString("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (%1)").arg(values);
170        QSqlQuery resultEventPerson (query, db);
171        //LOG_AUTOTEST(query);
172    }
173}
174
175void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
176{
177    QSqlDatabase db = QSqlDatabase::database();
178
179    if (db.isValid() && db.isOpen())
180    {
181        QString queryExist = QString("SELECT id FROM ROOM WHERE name='%1'").arg(aRoom["name"]);
182        QSqlQuery resultExist(queryExist,db);
183        // now we have to check whether ROOM record with 'name' exists or not,
184        // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
185        //   and assign autoincremented 'id' to aRoom
186        // - if it exists, then we need to get its 'id' and assign it to aRoom
187        int roomId = -1;
188        if(resultExist.next()) // ROOM record with 'name' already exists: we need to get its 'id'
189        {
190            roomId = resultExist.value(0).toInt();
191        }
192        else // ROOM record doesn't exist yet, need to create it
193        {
194            QString values = QString("'%1', '%2'").arg(aRoom["name"],aRoom["picture"]);
195            QString query = QString("INSERT INTO ROOM (name,picture) VALUES (%1)").arg(values);
196            QSqlQuery result (query, db);
197            roomId = result.lastInsertId().toInt(); // 'id' is assigned automatically
198            //LOG_AUTOTEST(query);
199        }
200
201        QString values = QString("'%1', '%2', '%3'").arg(aRoom["conference_id"],aRoom["event_id"],QString::number(roomId));
202        QString query = QString("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (%1)").arg(values);
203        QSqlQuery result (query, db);
204        //LOG_AUTOTEST(query);
205    }
206}
207
208void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
209{
210    QSqlDatabase db = QSqlDatabase::database();
211
212    //TODO: check if the link doesn't exist before inserting
213    if (db.isValid() && db.isOpen())
214    {
215        QString values = QString("'%1', '%2', '%3', '%4'").arg(aLink["event_id"],aLink["conference_id"],aLink["name"],aLink["url"]);
216        QString query = QString("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (%1)").arg(values);
217        QSqlQuery result(query, db);
218        //LOG_AUTOTEST(query);
219    }
220}
221
222bool SqlEngine::createTables(QSqlDatabase &aDatabase)
223{
224    bool result = aDatabase.open();
225
226    if (aDatabase.isValid() && aDatabase.isOpen())
227    {
228        QSqlQuery query(aDatabase);
229
230        query.exec("CREATE TABLE CONFERENCE ( "
231            "id INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL, "
232            "title VARCHAR UNIQUE NOT NULL, "
233            "subtitle VARCHAR, "
234            "venue VARCHAR, "
235            "city VARCHAR NOT NULL, "
236            "start INTEGER NOT NULL, "
237            "end INTEGER NOT NULL, "
238            "days INTEGER, "
239            "day_change INTEGER, "
240            "timeslot_duration INTEGER, "
241            "active INTEGER DEFAULT 0);");
242
243        query.exec("CREATE TABLE TRACK ( "
244            "id INTEGER  PRIMARY KEY AUTOINCREMENT  NOT NULL, "
245            "name VARCHAR UNIQUE NOT NULL );");
246
247        query.exec("CREATE TABLE ROOM ( "
248            "id INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL, "
249            "name VARCHAR UNIQUE NOT NULL, "
250            "picture VARCHAR NOT NULL);");
251
252        query.exec("CREATE TABLE PERSON ( "
253            "id INTEGER PRIMARY KEY  NOT NULL, "
254            "name VARCHAR UNIQUE NOT NULL);");
255
256        query.exec("CREATE TABLE EVENT ( "
257            "xid_conference INTEGER  NOT NULL, "
258            "id INTEGER NOT NULL, "
259            "start INTEGER NOT NULL, "
260            "duration INTEGER NOT NULL, "
261            "xid_track INTEGER NOT NULL REFERENCES TRACK(id), "
262            "type VARCHAR, "
263            "language VARCHAR, "
264            "tag VARCHAR,title VARCHAR NOT NULL, "
265            "subtitle VARCHAR, "
266            "abstract VARCHAR, "
267            "description VARCHAR, "
268            "favourite INTEGER DEFAULT 0, "
269            "alarm INTEGER DEFAULT 0, "
270            "PRIMARY KEY (xid_conference,id), "
271            "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
272            "FOREIGN KEY(xid_track) REFERENCES TRACK(id));");
273
274        query.exec("CREATE TABLE EVENT_PERSON ( "
275            "xid_conference INTEGER NOT NULL, "
276            "xid_event INTEGER NOT NULL, "
277            "xid_person INTEGER NOT NULL, "
278            "UNIQUE ( xid_conference, xid_event, xid_person ) ON CONFLICT IGNORE, "
279            "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
280            "FOREIGN KEY(xid_event) REFERENCES EVENT(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            "UNIQUE ( xid_conference, xid_event, xid_room ) ON CONFLICT IGNORE, "
288            "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
289            "FOREIGN KEY(xid_event) REFERENCES EVENT(id), "
290            "FOREIGN KEY(xid_room) REFERENCES ROOM(id));");
291
292        query.exec("CREATE TABLE EVENT_CONFLICT ( "
293            "xid_conference INTEGER NOT NULL, "
294            "xid_event INTEGER NOT NULL, "
295            "conflict_event INTEGER NOT NULL, "
296            "UNIQUE ( xid_conference, xid_event, conflict_event ) ON CONFLICT IGNORE, "
297            "FOREIGN KEY(xid_conference) REFERENCES CONFERENCE(id), "
298            "FOREIGN KEY(xid_event) REFERENCES EVENT(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.