source: src/sql/sqlengine.cpp @ 4b8ce66

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

The database is now created from the program. We don't need to copy or provide fosdem.sqlite anymore.

  • Property mode set to 100644
File size: 15.8 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        // create Db
54        if (!database.open()) qDebug() << "Could not open database" << database.lastError();
55        QFile file(":/create_tables.sql");
56        file.open(QIODevice::ReadOnly | QIODevice::Text);
57        QString allSqlStatements = file.readAll();
58        foreach(QString sql, allSqlStatements.split(";")) {
59            QSqlQuery query(database);
60            if (!query.exec(sql)) qDebug() << "Could not execute query" << query.lastError();
61        }
62    }
63    else
64    {
65        database.open();
66    }
67
68    checkConferenceMap(database);
69
70    //LOG_INFO(QString("Opening '%1' database '%2'").arg(aDatabaseType).arg(aDatabaseName));
71
72    return result ? QString() : database.lastError().text();
73}
74
75void SqlEngine::initialize()
76{
77    QString databaseName;
78    if(!QDir::home().exists(".fosdem"))
79        QDir::home().mkdir(".fosdem");
80    databaseName = QDir::homePath() + "/.fosdem/" + "fosdem.sqlite";
81    login("QSQLITE",databaseName);
82}
83
84void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference)
85{
86    QSqlDatabase db = QSqlDatabase::database();
87
88    if (db.isValid() && db.isOpen())
89    {
90        int confId = 0;
91        QList<Conference> confsList = Conference::getAll();
92        if(confsList.count())
93        {
94            QListIterator<Conference> i(confsList);
95            while (i.hasNext())
96            {
97                Conference conf = i.next();
98                if( aConference["title"] == conf.title() )
99                {
100                    confId = conf.id();
101                    aConference["id"] = QString::number(confId);
102                    break;
103                }
104            }
105        }
106
107        if(!confId) // conference 'aConference' isn't in the table => insert
108        {
109            QSqlQuery query(db);
110            query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,days,"
111                                                    "day_change,timeslot_duration,active) "
112                            " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,:days,"
113                                                    ":day_change,:timeslot_duration,:active)");
114            foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city" << "days")) {
115                query.bindValue(QString(":") + prop_name, aConference[prop_name]);
116            }
117            query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
118            query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
119            query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
120            query.bindValue(":day_change", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
121            query.bindValue(":active", confsList.count() > 0 ? 0 : 1);
122            if (!query.exec()) qDebug() << "Could not execute query to insert a conference:" << query.lastError();
123            aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
124        }
125    }
126}
127
128void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent)
129{
130    //LOG_DEBUG(QString("Adding event '%1' to DB").arg(*aEvent));
131
132    QSqlDatabase db = QSqlDatabase::database();
133
134    if (db.isValid() && db.isOpen())
135    {
136        //insert event track to table and get track id
137        int conference = aEvent["conference_id"].toInt();
138        QString name = aEvent["track"];
139        Track track;
140        int trackId;
141        try
142        {
143            track = Track::retrieveByName(name);
144            trackId = track.id();
145            /*qDebug() << QString("DEBUG: Track %1 in DB").arg(name);*/
146        }
147        catch (OrmNoObjectException &e) {
148            track.setConference(conference);
149            track.setName(name);
150            trackId = track.insert();
151            /*qDebug() << QString("DEBUG: Track %1 added to DB").arg(name);*/
152        }
153        QDateTime startDateTime;
154        startDateTime.setTimeSpec(Qt::UTC);
155        startDateTime = QDateTime(QDate::fromString(aEvent["date"],DATE_FORMAT),QTime::fromString(aEvent["start"],TIME_FORMAT),Qt::UTC);
156        qDebug() << "startDateTime: " << startDateTime.toString();
157
158        bool event_exists = false;
159        {
160            QSqlQuery check_event_query;
161            check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
162            check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
163            check_event_query.bindValue(":id", aEvent["id"]);
164            if (!check_event_query.exec()) {
165                qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
166                        << "event id:" << aEvent["id"]
167                        << "error:" << check_event_query.lastError()
168                        ;
169                return;
170            }
171            if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
172                event_exists = true;
173            }
174        }
175
176        QSqlQuery result;
177        if (event_exists) {
178            result.prepare("UPDATE EVENT SET"
179                            " start = :start"
180                            ", duration = :duration"
181                            ", xid_track = :xid_track"
182                            ", type = :type"
183                            ", language = :language"
184                            ", tag = :tag"
185                            ", title = :title"
186                            ", subtitle = :subtitle"
187                            ", abstract = :abstract"
188                            ", description = :description"
189                                " WHERE id = :id AND xid_conference = :xid_conference");
190        } else {
191            result.prepare("INSERT INTO EVENT "
192                            " (xid_conference, id, start, duration, xid_track, type, "
193                                " language, tag, title, subtitle, abstract, description) "
194                            " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
195                                ":language, :tag, :title, :subtitle, :abstract, :description)");
196        }
197        result.bindValue(":xid_conference", aEvent["conference_id"]);
198        result.bindValue(":start", QString::number(startDateTime.toTime_t()));
199        result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
200        result.bindValue(":xid_track", trackId);
201        static const QList<QString> props = QList<QString>()
202            << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
203        foreach (QString prop_name, props) {
204            result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
205        }
206        if (!result.exec()) {
207            qWarning() << "event insert/update failed:" << result.lastError();
208        }
209    }
210}
211
212void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson)
213{
214    QSqlDatabase db = QSqlDatabase::database();
215
216    if (db.isValid() && db.isOpen())
217    {
218        // TODO: SQL Injection!!!
219        QString values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["id"],aPerson["name"]);
220        QString query = QString("INSERT INTO PERSON (xid_conference,id,name) VALUES (%1)").arg(values);
221        QSqlQuery result (query, db);
222        //LOG_AUTOTEST(query);
223
224        // TODO: SQL Injection!!!
225        values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["event_id"],aPerson["id"]);
226        query = QString("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (%1)").arg(values);
227        QSqlQuery resultEventPerson (query, db);
228        //LOG_AUTOTEST(query);
229    }
230}
231
232void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
233{
234    QSqlDatabase db = QSqlDatabase::database();
235
236    if (db.isValid() && db.isOpen())
237    {
238        QSqlQuery query(db);
239        query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
240        query.bindValue(":conference_id", aRoom["conference_id"]);
241        query.bindValue(":name", aRoom["name"]);
242        if (!query.exec()) qDebug() << "Could not execute select room query: " << query.lastError();
243        // now we have to check whether ROOM record with 'name' exists or not,
244        // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
245        //   and assign autoincremented 'id' to aRoom
246        // - if it exists, then we need to get its 'id' and assign it to aRoom
247        int roomId = -1;
248        if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
249        {
250            roomId = query.value(0).toInt();
251        }
252        else // ROOM record doesn't exist yet, need to create it
253        {
254            // TODO: SQL Injection!!!
255            QString values = QString("'%1', '%2', '%3'").arg(aRoom["conference_id"],aRoom["name"],aRoom["picture"]);
256            QString query = QString("INSERT INTO ROOM (xid_conference,name,picture) VALUES (%1)").arg(values);
257            QSqlQuery result (query, db);
258            roomId = result.lastInsertId().toInt(); // 'id' is assigned automatically
259            //LOG_AUTOTEST(query);
260        }
261        query = QSqlQuery(db);
262        query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :roomId)");
263        query.bindValue(":conference_id", aRoom["conference_id"]);
264        query.bindValue(":event_id", aRoom["event_id"]);
265        query.bindValue(":roomId", roomId);
266        if (!query.exec()) qDebug() << "Could not execute insert into event_room query:" << query.lastError();
267        //LOG_AUTOTEST(query);
268    }
269}
270
271void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
272{
273    QSqlDatabase db = QSqlDatabase::database();
274
275    //TODO: check if the link doesn't exist before inserting
276    if (db.isValid() && db.isOpen())
277    {
278        // TODO: SQL Injection!!!
279        QString values = QString("'%1', '%2', '%3', '%4'").arg(aLink["event_id"],aLink["conference_id"],aLink["name"],aLink["url"]);
280        QString query = QString("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (%1)").arg(values);
281        QSqlQuery result(query, db);
282        //LOG_AUTOTEST(query);
283    }
284}
285
286int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword)
287{
288    QSqlDatabase db = QSqlDatabase::database();
289
290    if ( !db.isValid() || !db.isOpen())
291        return -1;
292
293
294    // DROP
295    execQuery( db, "DROP TABLE IF EXISTS SEARCH_EVENT");
296    // CREATE
297    execQuery( db, "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER  NOT NULL, id INTEGER NOT NULL )");
298    // INSERT
299    QString query = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
300                "SELECT EVENT.xid_conference, EVENT.id FROM EVENT ");
301    if( aColumns.contains("ROOM") ){
302        query += "INNER JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
303        query += "INNER JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
304    }
305    if( aColumns.contains("PERSON") ){
306        query += "INNER JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
307        query += "INNER JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
308    }
309    query += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
310
311    foreach (QString table, aColumns.uniqueKeys()){
312        foreach (QString column, aColumns.values(table)){
313            query += QString("%1.%2 LIKE '\%%3\%' OR ").arg( table, column, aKeyword );
314        }
315    }
316    query.chop( QString(" OR ").length() );
317    query += QString(");");
318
319    execQuery( db, query );
320
321    return 1;
322}
323
324bool SqlEngine::beginTransaction()
325{
326    QSqlDatabase db = QSqlDatabase::database();
327
328    return execQuery(db, "BEGIN IMMEDIATE TRANSACTION");
329}
330
331bool SqlEngine::commitTransaction()
332{
333    QSqlDatabase db = QSqlDatabase::database();
334
335    return execQuery(db, "COMMIT");
336}
337
338void SqlEngine::deleteConference(int id)
339{
340    QSqlDatabase db = QSqlDatabase::database();
341
342    if ( !db.isValid() || !db.isOpen()) {
343        return;
344    }
345
346    beginTransaction();
347
348    QHash<QString, QVariant> params;
349    params["xid_conference"] = id;
350    execQueryWithParameter(db, "DELETE FROM LINK WHERE xid_conference = :xid_conference", params);
351    execQueryWithParameter(db, "DELETE FROM EVENT_ROOM WHERE xid_conference = :xid_conference", params);
352    execQueryWithParameter(db, "DELETE FROM EVENT_PERSON WHERE xid_conference = :xid_conference", params);
353    execQueryWithParameter(db, "DELETE FROM EVENT WHERE xid_conference = :xid_conference", params);
354    execQueryWithParameter(db, "DELETE FROM ROOM WHERE xid_conference = :xid_conference", params);
355    execQueryWithParameter(db, "DELETE FROM PERSON WHERE xid_conference = :xid_conference", params);
356    execQueryWithParameter(db, "DELETE FROM TRACK WHERE xid_conference = :xid_conference", params);
357    execQueryWithParameter(db, "DELETE FROM CONFERENCE WHERE id = :xid_conference", params);
358
359    commitTransaction();
360}
361
362bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
363{
364    //qDebug() << "\nSQL: " << aQuery;
365
366    QSqlQuery sqlQuery(aDatabase);
367    if( !sqlQuery.exec(aQuery) ){
368       qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
369       return false;
370    }
371    else{
372       //qDebug() << "SQL OK.\n";
373       return true;
374    }
375}
376
377bool SqlEngine::execQueryWithParameter(QSqlDatabase &aDatabase, const QString &aQuery, const QHash<QString, QVariant>& params)
378{
379    qDebug() << "SQL:" << aQuery << "params:" << params;
380
381    QSqlQuery sqlQuery(aDatabase);
382    sqlQuery.prepare(aQuery);
383    foreach (QString param_key, params.keys()) {
384        sqlQuery.bindValue(param_key, params[param_key]);
385    }
386    if( !sqlQuery.exec() ){
387       qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
388       return false;
389    }
390    else{
391       //qDebug() << "SQL OK.\n";
392       return true;
393    }
394}
395
396void SqlEngine::checkConferenceMap(QSqlDatabase &aDatabase)
397{
398    QSqlQuery sqlQuery(aDatabase);
399    sqlQuery.prepare("SELECT map FROM conference");
400    if (!sqlQuery.exec()) {
401        qWarning() << "column conference.map is missing; adding";
402        execQuery(aDatabase, "ALTER TABLE conference ADD COLUMN map VARCHAR")
403         and execQuery(aDatabase, "UPDATE conference SET map = ':/maps/campus.png' WHERE title = 'FOSDEM 2010'");
404    }
405}
Note: See TracBrowser for help on using the repository browser.