source: src/sql/sqlengine.cpp @ 68b2df2

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

Add copyright to source.

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