source: src/sql/sqlengine.cpp @ 6df32f2

qt5
Last change on this file since 6df32f2 was 6df32f2, checked in by gregor herrmann <gregoa@…>, 10 years ago

Update GPL blurb in source files.

  • Property mode set to 100644
File size: 16.5 KB
Line 
1/*
2 * Copyright (C) 2010 Ixonos Plc.
3 *
4 * This file is part of ConfClerk.
5 *
6 * ConfClerk 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 * ConfClerk 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 * ConfClerk.  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(conference, 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        aRoom["id"] = "";
248        if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
249        {
250            aRoom["id"] = query.value(0).toString();
251        }
252        else // ROOM record doesn't exist yet, need to create it
253        {
254            query = QSqlQuery(db);
255            query.prepare("INSERT INTO ROOM (xid_conference,name,picture) VALUES (:xid_conference, :name, :picture)");
256            query.bindValue(":xid_conference", aRoom["conference_id"]);
257            query.bindValue(":xid_name", aRoom["name"]);
258            query.bindValue(":xid_picture", aRoom["picture"]);
259            if (!query.exec()) qDebug() << "Could not execute 'insert into room ...' query." << query.lastError();
260            aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
261            //LOG_AUTOTEST(query);
262        }
263        query = QSqlQuery(db);
264        query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
265        query.bindValue(":conference_id", aRoom["conference_id"]);
266        query.bindValue(":event_id", aRoom["event_id"]);
267        query.bindValue(":room_id", aRoom["id"]);
268        if (!query.exec()) qDebug() << "Could not 'execute insert into event_room' query:" << query.lastError();
269        //LOG_AUTOTEST(query);
270    }
271}
272
273void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
274{
275    QSqlDatabase db = QSqlDatabase::database();
276
277    //TODO: check if the link doesn't exist before inserting
278    if (db.isValid() && db.isOpen())
279    {
280        QSqlQuery query(db);
281        query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
282        query.bindValue(":xid_event", aLink["event_id"]);
283        query.bindValue(":xid_conference", aLink["conference_id"]);
284        query.bindValue(":name", aLink["name"]);
285        query.bindValue(":url", aLink["url"]);
286        if (!query.exec()) qDebug() << "Error executing 'insert into link' query: " << query.lastError();
287        //LOG_AUTOTEST(query);
288    }
289}
290
291int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword)
292{
293    QSqlDatabase db = QSqlDatabase::database();
294
295    if ( !db.isValid() || !db.isOpen())
296        return -1;
297
298    if (aColumns.empty()) return -1;
299
300    // DROP
301    execQuery( db, "DROP TABLE IF EXISTS SEARCH_EVENT");
302    // CREATE
303    execQuery( db, "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER  NOT NULL, id INTEGER NOT NULL )");
304    // INSERT
305    QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
306                "SELECT EVENT.xid_conference, EVENT.id FROM EVENT ");
307    if( aColumns.contains("ROOM") ){
308        sql += "INNER JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
309        sql += "INNER JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
310    }
311    if( aColumns.contains("PERSON") ){
312        sql += "INNER JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
313        sql += "INNER JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
314    }
315    sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
316
317    foreach (QString table, aColumns.uniqueKeys()){
318        foreach (QString column, aColumns.values(table)){
319            sql += QString("%1.%2 LIKE '\%' || :%1%2 || '\%' OR ").arg( table, column );
320        }
321    }
322    sql.chop( QString(" OR ").length() );
323    sql += QString(")");
324
325    QSqlQuery query(db);
326    query.prepare(sql);
327    foreach (QString table, aColumns.uniqueKeys()){
328        foreach (QString column, aColumns.values(table)){
329            query.bindValue(QString(":%1%2").arg(table, column), aKeyword );
330        }
331    }
332
333    if( !query.exec() ){
334       qDebug() << "Could not execute search query: " << query.lastError().text();
335       return -1;
336    }
337
338    return 1;
339}
340
341bool SqlEngine::beginTransaction()
342{
343    QSqlDatabase db = QSqlDatabase::database();
344
345    return execQuery(db, "BEGIN IMMEDIATE TRANSACTION");
346}
347
348bool SqlEngine::commitTransaction()
349{
350    QSqlDatabase db = QSqlDatabase::database();
351
352    return execQuery(db, "COMMIT");
353}
354
355void SqlEngine::deleteConference(int id)
356{
357    QSqlDatabase db = QSqlDatabase::database();
358
359    if ( !db.isValid() || !db.isOpen()) {
360        return;
361    }
362
363    beginTransaction();
364
365    QHash<QString, QVariant> params;
366    params["xid_conference"] = id;
367    execQueryWithParameter(db, "DELETE FROM LINK WHERE xid_conference = :xid_conference", params);
368    execQueryWithParameter(db, "DELETE FROM EVENT_ROOM WHERE xid_conference = :xid_conference", params);
369    execQueryWithParameter(db, "DELETE FROM EVENT_PERSON WHERE xid_conference = :xid_conference", params);
370    execQueryWithParameter(db, "DELETE FROM EVENT WHERE xid_conference = :xid_conference", params);
371    execQueryWithParameter(db, "DELETE FROM ROOM WHERE xid_conference = :xid_conference", params);
372    execQueryWithParameter(db, "DELETE FROM PERSON WHERE xid_conference = :xid_conference", params);
373    execQueryWithParameter(db, "DELETE FROM TRACK WHERE xid_conference = :xid_conference", params);
374    execQueryWithParameter(db, "DELETE FROM CONFERENCE WHERE id = :xid_conference", params);
375
376    commitTransaction();
377}
378
379bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
380{
381    //qDebug() << "\nSQL: " << aQuery;
382
383    QSqlQuery sqlQuery(aDatabase);
384    if( !sqlQuery.exec(aQuery) ){
385       qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
386       return false;
387    }
388    else{
389       //qDebug() << "SQL OK.\n";
390       return true;
391    }
392}
393
394bool SqlEngine::execQueryWithParameter(QSqlDatabase &aDatabase, const QString &aQuery, const QHash<QString, QVariant>& params)
395{
396    qDebug() << "SQL:" << aQuery << "params:" << params;
397
398    QSqlQuery sqlQuery(aDatabase);
399    sqlQuery.prepare(aQuery);
400    foreach (QString param_key, params.keys()) {
401        sqlQuery.bindValue(param_key, params[param_key]);
402    }
403    if( !sqlQuery.exec() ){
404       qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
405       return false;
406    }
407    else{
408       //qDebug() << "SQL OK.\n";
409       return true;
410    }
411}
412
413void SqlEngine::checkConferenceMap(QSqlDatabase &aDatabase)
414{
415    QSqlQuery sqlQuery(aDatabase);
416    sqlQuery.prepare("SELECT map FROM conference");
417    if (!sqlQuery.exec()) {
418        qWarning() << "column conference.map is missing; adding";
419        execQuery(aDatabase, "ALTER TABLE conference ADD COLUMN map VARCHAR")
420         and execQuery(aDatabase, "UPDATE conference SET map = ':/maps/campus.png' WHERE title = 'FOSDEM 2010'");
421    }
422}
Note: See TracBrowser for help on using the repository browser.