source: src/sql/sqlengine.cpp @ 699d5b8

qt5
Last change on this file since 699d5b8 was 7d7659d, checked in by pavelpa <pavelpa@…>, 13 years ago

combined EVENT and VIRTUAL_EVENT => 'EVENT' now

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