source: src/sql/sqlengine.cpp @ c8b84e1

qt5
Last change on this file since c8b84e1 was c8b84e1, checked in by Philipp Spitzer <philipp@…>, 10 years ago

Persons are deleted now when a conference is removed.

  • Property mode set to 100644
File size: 15.7 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            if (!query.exec()) qDebug() << "Could not execute query to insert a conference:" << query.lastError();
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    if (db.isValid() && db.isOpen())
214    {
215        // TODO: SQL Injection!!!
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        // TODO: SQL Injection!!!
222        values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["event_id"],aPerson["id"]);
223        query = QString("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (%1)").arg(values);
224        QSqlQuery resultEventPerson (query, db);
225        //LOG_AUTOTEST(query);
226    }
227}
228
229void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
230{
231    QSqlDatabase db = QSqlDatabase::database();
232
233    if (db.isValid() && db.isOpen())
234    {
235        QSqlQuery query(db);
236        query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
237        query.bindValue(":conference_id", aRoom["conference_id"]);
238        query.bindValue(":name", aRoom["name"]);
239        if (!query.exec()) qDebug() << "Could not execute select room query: " << query.lastError();
240        // now we have to check whether ROOM record with 'name' exists or not,
241        // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
242        //   and assign autoincremented 'id' to aRoom
243        // - if it exists, then we need to get its 'id' and assign it to aRoom
244        int roomId = -1;
245        if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
246        {
247            roomId = query.value(0).toInt();
248        }
249        else // ROOM record doesn't exist yet, need to create it
250        {
251            // TODO: SQL Injection!!!
252            QString values = QString("'%1', '%2', '%3'").arg(aRoom["conference_id"],aRoom["name"],aRoom["picture"]);
253            QString query = QString("INSERT INTO ROOM (xid_conference,name,picture) VALUES (%1)").arg(values);
254            QSqlQuery result (query, db);
255            roomId = result.lastInsertId().toInt(); // 'id' is assigned automatically
256            //LOG_AUTOTEST(query);
257        }
258        query = QSqlQuery(db);
259        query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :roomId)");
260        query.bindValue(":conference_id", aRoom["conference_id"]);
261        query.bindValue(":event_id", aRoom["event_id"]);
262        query.bindValue(":roomId", roomId);
263        if (!query.exec()) qDebug() << "Could not execute insert into event_room query:" << query.lastError();
264        //LOG_AUTOTEST(query);
265    }
266}
267
268void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
269{
270    QSqlDatabase db = QSqlDatabase::database();
271
272    //TODO: check if the link doesn't exist before inserting
273    if (db.isValid() && db.isOpen())
274    {
275        // TODO: SQL Injection!!!
276        QString values = QString("'%1', '%2', '%3', '%4'").arg(aLink["event_id"],aLink["conference_id"],aLink["name"],aLink["url"]);
277        QString query = QString("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (%1)").arg(values);
278        QSqlQuery result(query, db);
279        //LOG_AUTOTEST(query);
280    }
281}
282
283int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,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 TEMP 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 EVENT.xid_conference, EVENT.id FROM EVENT ");
298    if( aColumns.contains("ROOM") ){
299        query += "INNER JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
300        query += "INNER JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
301    }
302    if( aColumns.contains("PERSON") ){
303        query += "INNER JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
304        query += "INNER JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
305    }
306    query += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
307
308    foreach (QString table, aColumns.uniqueKeys()){
309        foreach (QString column, aColumns.values(table)){
310            query += QString("%1.%2 LIKE '\%%3\%' OR ").arg( table, column, aKeyword );
311        }
312    }
313    query.chop( QString(" OR ").length() );
314    query += QString(");");
315
316    execQuery( db, query );
317
318    return 1;
319}
320
321bool SqlEngine::beginTransaction()
322{
323    QSqlDatabase db = QSqlDatabase::database();
324
325    return execQuery(db, "BEGIN IMMEDIATE TRANSACTION");
326}
327
328bool SqlEngine::commitTransaction()
329{
330    QSqlDatabase db = QSqlDatabase::database();
331
332    return execQuery(db, "COMMIT");
333}
334
335void SqlEngine::deleteConference(int id)
336{
337    QSqlDatabase db = QSqlDatabase::database();
338
339    if ( !db.isValid() || !db.isOpen()) {
340        return;
341    }
342
343    beginTransaction();
344
345    QHash<QString, QVariant> params;
346    params["xid_conference"] = id;
347    execQueryWithParameter(db, "DELETE FROM LINK WHERE xid_conference = :xid_conference", params);
348    execQueryWithParameter(db, "DELETE FROM EVENT_ROOM WHERE xid_conference = :xid_conference", params);
349    execQueryWithParameter(db, "DELETE FROM EVENT_PERSON WHERE xid_conference = :xid_conference", params);
350    execQueryWithParameter(db, "DELETE FROM EVENT WHERE xid_conference = :xid_conference", params);
351    execQueryWithParameter(db, "DELETE FROM ROOM WHERE xid_conference = :xid_conference", params);
352    execQueryWithParameter(db, "DELETE FROM PERSON WHERE xid_conference = :xid_conference", params);
353    execQueryWithParameter(db, "DELETE FROM TRACK WHERE xid_conference = :xid_conference", params);
354    execQueryWithParameter(db, "DELETE FROM CONFERENCE WHERE id = :xid_conference", params);
355
356    commitTransaction();
357}
358
359bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
360{
361    //qDebug() << "\nSQL: " << aQuery;
362
363    QSqlQuery sqlQuery(aDatabase);
364    if( !sqlQuery.exec(aQuery) ){
365       qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
366       return false;
367    }
368    else{
369       //qDebug() << "SQL OK.\n";
370       return true;
371    }
372}
373
374bool SqlEngine::execQueryWithParameter(QSqlDatabase &aDatabase, const QString &aQuery, const QHash<QString, QVariant>& params)
375{
376    qDebug() << "SQL:" << aQuery << "params:" << params;
377
378    QSqlQuery sqlQuery(aDatabase);
379    sqlQuery.prepare(aQuery);
380    foreach (QString param_key, params.keys()) {
381        sqlQuery.bindValue(param_key, params[param_key]);
382    }
383    if( !sqlQuery.exec() ){
384       qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
385       return false;
386    }
387    else{
388       //qDebug() << "SQL OK.\n";
389       return true;
390    }
391}
392
393void SqlEngine::checkConferenceMap(QSqlDatabase &aDatabase)
394{
395    QSqlQuery sqlQuery(aDatabase);
396    sqlQuery.prepare("SELECT map FROM conference");
397    if (!sqlQuery.exec()) {
398        qWarning() << "column conference.map is missing; adding";
399        execQuery(aDatabase, "ALTER TABLE conference ADD COLUMN map VARCHAR")
400         and execQuery(aDatabase, "UPDATE conference SET map = ':/maps/campus.png' WHERE title = 'FOSDEM 2010'");
401    }
402}
Note: See TracBrowser for help on using the repository browser.