source: src/sql/sqlengine.cpp @ 51529bd

qt5
Last change on this file since 51529bd was 51529bd, checked in by gregor herrmann <gregoa@…>, 11 years ago

Insert new field xid_conference into table track, room and person.

  • Property mode set to 100644
File size: 15.1 KB
Line 
1/*
2 * Copyright (C) 2010 Ixonos Plc.
3 *
4 * This file is part of fosdem-schedule.
5 *
6 * fosdem-schedule is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the Free
8 * Software Foundation, either version 2 of the License, or (at your option)
9 * any later version.
10 *
11 * fosdem-schedule is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14 * more details.
15 *
16 * You should have received a copy of the GNU General Public License along with
17 * fosdem-schedule.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include <QSqlError>
21#include <QSqlQuery>
22#include <QSqlRecord>
23#include <QVariant>
24#include <QDateTime>
25
26#include <QDir>
27#include "sqlengine.h"
28#include <track.h>
29#include <conference.h>
30
31#include <QDebug>
32
33const QString DATE_FORMAT ("yyyy-MM-dd");
34const QString TIME_FORMAT ("hh:mm");
35
36SqlEngine::SqlEngine(QObject *aParent)
37    : QObject(aParent)
38{
39}
40
41SqlEngine::~SqlEngine()
42{
43}
44
45QString SqlEngine::login(const QString &aDatabaseType, const QString &aDatabaseName)
46{
47    QSqlDatabase database = QSqlDatabase::addDatabase(aDatabaseType);
48    database.setDatabaseName(aDatabaseName);
49
50    bool result = false;
51    if(!QFile::exists(aDatabaseName)) // the DB (tables) doesn't exists, and so we have to create one
52    {
53        // copy conference Db from resource, instead of creating
54        // empty tables and then parsing the schedule
55        QFile dbFile(aDatabaseName);
56        QFile(":/fosdem.sqlite").copy(aDatabaseName);
57        dbFile.setPermissions(QFile::ReadOwner | QFile::WriteOwner | QFile::ReadGroup | QFile::WriteGroup);
58        database.open();
59    }
60    else
61    {
62        database.open();
63    }
64
65    checkConferenceMap(database);
66
67    //LOG_INFO(QString("Opening '%1' database '%2'").arg(aDatabaseType).arg(aDatabaseName));
68
69    return result ? QString() : database.lastError().text();
70}
71
72void SqlEngine::initialize()
73{
74    QString databaseName;
75    if(!QDir::home().exists(".fosdem"))
76        QDir::home().mkdir(".fosdem");
77    databaseName = QDir::homePath() + "/.fosdem/" + "fosdem.sqlite";
78    login("QSQLITE",databaseName);
79}
80
81void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference)
82{
83    QSqlDatabase db = QSqlDatabase::database();
84
85    if (db.isValid() && db.isOpen())
86    {
87        int confId = 0;
88        QList<Conference> confsList = Conference::getAll();
89        if(confsList.count())
90        {
91            QListIterator<Conference> i(confsList);
92            while (i.hasNext())
93            {
94                Conference conf = i.next();
95                if( aConference["title"] == conf.title() )
96                {
97                    confId = conf.id();
98                    aConference["id"] = QString::number(confId);
99                    break;
100                }
101            }
102        }
103
104        if(!confId) // conference 'aConference' isn't in the table => insert
105        {
106            QSqlQuery query(db);
107            query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,days,"
108                                                    "day_change,timeslot_duration,active) "
109                            " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,:days,"
110                                                    ":day_change,:timeslot_duration,:active)");
111            foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city" << "days")) {
112                query.bindValue(QString(":") + prop_name, aConference[prop_name]);
113            }
114            query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
115            query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
116            query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
117            query.bindValue(":day_change", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
118            query.bindValue(":active", confsList.count() > 0 ? 0 : 1);
119            query.exec();
120            aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
121        }
122    }
123}
124
125void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent)
126{
127    //LOG_DEBUG(QString("Adding event '%1' to DB").arg(*aEvent));
128
129    QSqlDatabase db = QSqlDatabase::database();
130
131    if (db.isValid() && db.isOpen())
132    {
133        //insert event track to table and get track id
134        int conference = aEvent["conference_id"].toInt();
135        QString name = aEvent["track"];
136        Track track;
137        int trackId;
138        try
139        {
140            track = Track::retrieveByName(name);
141            trackId = track.id();
142            /*qDebug() << QString("DEBUG: Track %1 in DB").arg(name);*/
143        }
144        catch (OrmNoObjectException &e) {
145            track.setConference(conference);
146            track.setName(name);
147            trackId = track.insert();
148            /*qDebug() << QString("DEBUG: Track %1 added to DB").arg(name);*/
149        }
150        QDateTime startDateTime;
151        startDateTime.setTimeSpec(Qt::UTC);
152        startDateTime = QDateTime(QDate::fromString(aEvent["date"],DATE_FORMAT),QTime::fromString(aEvent["start"],TIME_FORMAT),Qt::UTC);
153        qDebug() << "startDateTime: " << startDateTime.toString();
154
155        bool event_exists = false;
156        {
157            QSqlQuery check_event_query;
158            check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
159            check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
160            check_event_query.bindValue(":id", aEvent["id"]);
161            if (!check_event_query.exec()) {
162                qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
163                        << "event id:" << aEvent["id"]
164                        << "error:" << check_event_query.lastError()
165                        ;
166                return;
167            }
168            if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
169                event_exists = true;
170            }
171        }
172
173        QSqlQuery result;
174        if (event_exists) {
175            result.prepare("UPDATE EVENT SET"
176                            " start = :start"
177                            ", duration = :duration"
178                            ", xid_track = :xid_track"
179                            ", type = :type"
180                            ", language = :language"
181                            ", tag = :tag"
182                            ", title = :title"
183                            ", subtitle = :subtitle"
184                            ", abstract = :abstract"
185                            ", description = :description"
186                                " WHERE id = :id AND xid_conference = :xid_conference");
187        } else {
188            result.prepare("INSERT INTO EVENT "
189                            " (xid_conference, id, start, duration, xid_track, type, "
190                                " language, tag, title, subtitle, abstract, description) "
191                            " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
192                                ":language, :tag, :title, :subtitle, :abstract, :description)");
193        }
194        result.bindValue(":xid_conference", aEvent["conference_id"]);
195        result.bindValue(":start", QString::number(startDateTime.toTime_t()));
196        result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
197        result.bindValue(":xid_track", trackId);
198        static const QList<QString> props = QList<QString>()
199            << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
200        foreach (QString prop_name, props) {
201            result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
202        }
203        if (!result.exec()) {
204            qWarning() << "event insert/update failed:" << result.lastError();
205        }
206    }
207}
208
209void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson)
210{
211    QSqlDatabase db = QSqlDatabase::database();
212
213    //TODO: check if the person doesn't exist before inserting
214    if (db.isValid() && db.isOpen())
215    {
216        QString values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["id"],aPerson["name"]);
217        QString query = QString("INSERT INTO PERSON (xid_conference,id,name) VALUES (%1)").arg(values);
218        QSqlQuery result (query, db);
219        //LOG_AUTOTEST(query);
220
221        values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["event_id"],aPerson["id"]);
222        query = QString("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (%1)").arg(values);
223        QSqlQuery resultEventPerson (query, db);
224        //LOG_AUTOTEST(query);
225    }
226}
227
228void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
229{
230    QSqlDatabase db = QSqlDatabase::database();
231
232    if (db.isValid() && db.isOpen())
233    {
234        QString queryExist = QString("SELECT id FROM ROOM WHERE name='%1'").arg(aRoom["name"]);
235        QSqlQuery resultExist(queryExist,db);
236        // now we have to check whether ROOM record with 'name' exists or not,
237        // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
238        //   and assign autoincremented 'id' to aRoom
239        // - if it exists, then we need to get its 'id' and assign it to aRoom
240        int roomId = -1;
241        if(resultExist.next()) // ROOM record with 'name' already exists: we need to get its 'id'
242        {
243            roomId = resultExist.value(0).toInt();
244        }
245        else // ROOM record doesn't exist yet, need to create it
246        {
247            QString values = QString("'%1', '%2', '%3'").arg(aRoom["conference_id"],aRoom["name"],aRoom["picture"]);
248            QString query = QString("INSERT INTO ROOM (xid_conference,name,picture) VALUES (%1)").arg(values);
249            QSqlQuery result (query, db);
250            roomId = result.lastInsertId().toInt(); // 'id' is assigned automatically
251            //LOG_AUTOTEST(query);
252        }
253
254        QString values = QString("'%1', '%2', '%3'").arg(aRoom["conference_id"],aRoom["event_id"],QString::number(roomId));
255        QString query = QString("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (%1)").arg(values);
256        QSqlQuery result (query, db);
257        //LOG_AUTOTEST(query);
258    }
259}
260
261void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
262{
263    QSqlDatabase db = QSqlDatabase::database();
264
265    //TODO: check if the link doesn't exist before inserting
266    if (db.isValid() && db.isOpen())
267    {
268        QString values = QString("'%1', '%2', '%3', '%4'").arg(aLink["event_id"],aLink["conference_id"],aLink["name"],aLink["url"]);
269        QString query = QString("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (%1)").arg(values);
270        QSqlQuery result(query, db);
271        //LOG_AUTOTEST(query);
272    }
273}
274
275int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword)
276{
277    QSqlDatabase db = QSqlDatabase::database();
278
279    if ( !db.isValid() || !db.isOpen())
280        return -1;
281
282
283    // DROP
284    execQuery( db, "DROP TABLE IF EXISTS SEARCH_EVENT;");
285    // CREATE
286    execQuery( db, "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER  NOT NULL, id INTEGER NOT NULL );");
287    // INSERT
288    QString query = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
289                "SELECT EVENT.xid_conference, EVENT.id FROM EVENT ");
290    if( aColumns.contains("ROOM") ){
291        query += "INNER JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
292        query += "INNER JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
293    }
294    if( aColumns.contains("PERSON") ){
295        query += "INNER JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
296        query += "INNER JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
297    }
298    query += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
299
300    foreach (QString table, aColumns.uniqueKeys()){
301        foreach (QString column, aColumns.values(table)){
302            query += QString("%1.%2 LIKE '\%%3\%' OR ").arg( table, column, aKeyword );
303        }
304    }
305    query.chop( QString(" OR ").length() );
306    query += QString(");");
307
308    execQuery( db, query );
309
310    return 1;
311}
312
313bool SqlEngine::beginTransaction()
314{
315    QSqlDatabase db = QSqlDatabase::database();
316
317    return execQuery(db, "BEGIN IMMEDIATE TRANSACTION");
318}
319
320bool SqlEngine::commitTransaction()
321{
322    QSqlDatabase db = QSqlDatabase::database();
323
324    return execQuery(db, "COMMIT");
325}
326
327void SqlEngine::deleteConference(int id)
328{
329    QSqlDatabase db = QSqlDatabase::database();
330
331    if ( !db.isValid() || !db.isOpen()) {
332        return;
333    }
334
335    beginTransaction();
336
337    QHash<QString, QVariant> params;
338    params["xid_conference"] = id;
339    execQueryWithParameter(db, "DELETE FROM LINK WHERE xid_conference = :xid_conference", params);
340    execQueryWithParameter(db, "DELETE FROM EVENT_ROOM WHERE xid_conference = :xid_conference", params);
341    execQueryWithParameter(db, "DELETE FROM EVENT_PERSON WHERE xid_conference = :xid_conference", params);
342    execQueryWithParameter(db, "DELETE FROM EVENT WHERE xid_conference = :xid_conference", params);
343    execQueryWithParameter(db, "DELETE FROM CONFERENCE WHERE id = :xid_conference", params);
344    execQuery(db, "DELETE FROM ROOM WHERE NOT EXISTS(SELECT * FROM EVENT_ROOM WHERE xid_room = ROOM.id)");
345    execQuery(db, "DELETE FROM PERSON WHERE NOT EXISTS(SELECT * FROM EVENT_PERSON WHERE xid_person = PERSON.id)");
346
347    commitTransaction();
348}
349
350bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
351{
352    //qDebug() << "\nSQL: " << aQuery;
353
354    QSqlQuery sqlQuery(aDatabase);
355    if( !sqlQuery.exec(aQuery) ){
356       qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
357       return false;
358    }
359    else{
360       //qDebug() << "SQL OK.\n";
361       return true;
362    }
363}
364
365bool SqlEngine::execQueryWithParameter(QSqlDatabase &aDatabase, const QString &aQuery, const QHash<QString, QVariant>& params)
366{
367    qDebug() << "SQL:" << aQuery << "params:" << params;
368
369    QSqlQuery sqlQuery(aDatabase);
370    sqlQuery.prepare(aQuery);
371    foreach (QString param_key, params.keys()) {
372        sqlQuery.bindValue(param_key, params[param_key]);
373    }
374    if( !sqlQuery.exec() ){
375       qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
376       return false;
377    }
378    else{
379       //qDebug() << "SQL OK.\n";
380       return true;
381    }
382}
383
384void SqlEngine::checkConferenceMap(QSqlDatabase &aDatabase)
385{
386    QSqlQuery sqlQuery(aDatabase);
387    sqlQuery.prepare("SELECT map FROM conference");
388    if (!sqlQuery.exec()) {
389        qWarning() << "column conference.map is missing; adding";
390        execQuery(aDatabase, "ALTER TABLE conference ADD COLUMN map VARCHAR")
391         and execQuery(aDatabase, "UPDATE conference SET map = ':/maps/campus.png' WHERE title = 'FOSDEM 2010'");
392    }
393}
Note: See TracBrowser for help on using the repository browser.