source: src/sql/sqlengine.cpp @ c7c4369

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

Remove ULB, Campus Solbosch maps.

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