source: src/sql/sqlengine.cpp @ cf385cd

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

Removed many of the qDebug() output lines (see ticket #10).

  • Property mode set to 100644
File size: 16.4 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    QSqlDatabase db = QSqlDatabase::database();
136
137    if (db.isValid() && db.isOpen())
138    {
139        //insert event track to table and get track id
140        int conference = aEvent["conference_id"].toInt();
141        QString name = aEvent["track"];
142        Track track;
143        int trackId;
144        try
145        {
146            track = Track::retrieveByName(conference, name);
147            trackId = track.id();
148        }
149        catch (OrmNoObjectException &e) {
150            track.setConference(conference);
151            track.setName(name);
152            trackId = track.insert();
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
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        QSqlQuery query(db);
219        query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)");
220        query.bindValue(":xid_conference", aPerson["conference_id"]);
221        query.bindValue(":id", aPerson["id"]);
222        query.bindValue(":name", aPerson["name"]);
223        query.exec(); // some queries fail due to the unique key constraint
224        // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError();
225
226        query = QSqlQuery(db);
227        query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)");
228        query.bindValue(":xid_conference", aPerson["conference_id"]);
229        query.bindValue(":xid_event", aPerson["event_id"]);
230        query.bindValue(":xid_person", aPerson["id"]);
231        query.exec(); // some queries fail due to the unique key constraint
232        // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError();
233    }
234}
235
236void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
237{
238    QSqlDatabase db = QSqlDatabase::database();
239
240    if (db.isValid() && db.isOpen())
241    {
242        QSqlQuery query(db);
243        query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
244        query.bindValue(":conference_id", aRoom["conference_id"]);
245        query.bindValue(":name", aRoom["name"]);
246        if (!query.exec()) qDebug() << "Could not execute select room query: " << query.lastError();
247        // now we have to check whether ROOM record with 'name' exists or not,
248        // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
249        //   and assign autoincremented 'id' to aRoom
250        // - if it exists, then we need to get its 'id' and assign it to aRoom
251        aRoom["id"] = "";
252        if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
253        {
254            aRoom["id"] = query.value(0).toString();
255        }
256        else // ROOM record doesn't exist yet, need to create it
257        {
258            query = QSqlQuery(db);
259            query.prepare("INSERT INTO ROOM (xid_conference,name,picture) VALUES (:xid_conference, :name, :picture)");
260            query.bindValue(":xid_conference", aRoom["conference_id"]);
261            query.bindValue(":xid_name", aRoom["name"]);
262            query.bindValue(":xid_picture", aRoom["picture"]);
263            if (!query.exec()) qDebug() << "Could not execute 'insert into room ...' query." << query.lastError();
264            aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
265            //LOG_AUTOTEST(query);
266        }
267        query = QSqlQuery(db);
268        query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
269        query.bindValue(":conference_id", aRoom["conference_id"]);
270        query.bindValue(":event_id", aRoom["event_id"]);
271        query.bindValue(":room_id", aRoom["id"]);
272        if (!query.exec()) qDebug() << "Could not 'execute insert into event_room' query:" << query.lastError();
273    }
274}
275
276void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
277{
278    QSqlDatabase db = QSqlDatabase::database();
279
280    //TODO: check if the link doesn't exist before inserting
281    if (db.isValid() && db.isOpen())
282    {
283        QSqlQuery query(db);
284        query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
285        query.bindValue(":xid_event", aLink["event_id"]);
286        query.bindValue(":xid_conference", aLink["conference_id"]);
287        query.bindValue(":name", aLink["name"]);
288        query.bindValue(":url", aLink["url"]);
289        if (!query.exec()) qDebug() << "Error executing 'insert into link' query: " << query.lastError();
290    }
291}
292
293int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword)
294{
295    QSqlDatabase db = QSqlDatabase::database();
296
297    if ( !db.isValid() || !db.isOpen())
298        return -1;
299
300    if (aColumns.empty()) return -1;
301
302    // DROP
303    execQuery( db, "DROP TABLE IF EXISTS SEARCH_EVENT");
304    // CREATE
305    execQuery( db, "CREATE TABLE SEARCH_EVENT ( xid_conference INTEGER  NOT NULL, id INTEGER NOT NULL )");
306    // INSERT
307    QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
308                "SELECT EVENT.xid_conference, EVENT.id FROM EVENT ");
309    if( aColumns.contains("ROOM") ){
310        sql += "INNER JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
311        sql += "INNER JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
312    }
313    if( aColumns.contains("PERSON") ){
314        sql += "INNER JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
315        sql += "INNER JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
316    }
317    sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
318
319    foreach (QString table, aColumns.uniqueKeys()){
320        foreach (QString column, aColumns.values(table)){
321            sql += QString("%1.%2 LIKE '\%' || :%1%2 || '\%' OR ").arg( table, column );
322        }
323    }
324    sql.chop( QString(" OR ").length() );
325    sql += QString(")");
326
327    QSqlQuery query(db);
328    query.prepare(sql);
329    foreach (QString table, aColumns.uniqueKeys()){
330        foreach (QString column, aColumns.values(table)){
331            query.bindValue(QString(":%1%2").arg(table, column), aKeyword );
332        }
333    }
334
335    if( !query.exec() ){
336       qDebug() << "Could not execute search query: " << query.lastError().text();
337       return -1;
338    }
339
340    return 1;
341}
342
343bool SqlEngine::beginTransaction()
344{
345    QSqlDatabase db = QSqlDatabase::database();
346
347    return execQuery(db, "BEGIN IMMEDIATE TRANSACTION");
348}
349
350bool SqlEngine::commitTransaction()
351{
352    QSqlDatabase db = QSqlDatabase::database();
353
354    return execQuery(db, "COMMIT");
355}
356
357void SqlEngine::deleteConference(int id)
358{
359    QSqlDatabase db = QSqlDatabase::database();
360
361    if ( !db.isValid() || !db.isOpen()) {
362        return;
363    }
364
365    beginTransaction();
366
367    QHash<QString, QVariant> params;
368    params["xid_conference"] = id;
369    execQueryWithParameter(db, "DELETE FROM LINK WHERE xid_conference = :xid_conference", params);
370    execQueryWithParameter(db, "DELETE FROM EVENT_ROOM WHERE xid_conference = :xid_conference", params);
371    execQueryWithParameter(db, "DELETE FROM EVENT_PERSON WHERE xid_conference = :xid_conference", params);
372    execQueryWithParameter(db, "DELETE FROM EVENT WHERE xid_conference = :xid_conference", params);
373    execQueryWithParameter(db, "DELETE FROM ROOM WHERE xid_conference = :xid_conference", params);
374    execQueryWithParameter(db, "DELETE FROM PERSON WHERE xid_conference = :xid_conference", params);
375    execQueryWithParameter(db, "DELETE FROM TRACK WHERE xid_conference = :xid_conference", params);
376    execQueryWithParameter(db, "DELETE FROM CONFERENCE WHERE id = :xid_conference", params);
377
378    commitTransaction();
379}
380
381bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &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    return true;
389}
390
391bool SqlEngine::execQueryWithParameter(QSqlDatabase &aDatabase, const QString &aQuery, const QHash<QString, QVariant>& params)
392{
393    QSqlQuery sqlQuery(aDatabase);
394    sqlQuery.prepare(aQuery);
395    foreach (QString param_key, params.keys()) {
396        sqlQuery.bindValue(param_key, params[param_key]);
397    }
398    if( !sqlQuery.exec() ){
399       qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
400       return false;
401    }
402    return true;
403}
404
405void SqlEngine::checkConferenceMap(QSqlDatabase &aDatabase)
406{
407    QSqlQuery sqlQuery(aDatabase);
408    sqlQuery.prepare("SELECT map FROM conference");
409    if (!sqlQuery.exec()) {
410        qWarning() << "column conference.map is missing; adding";
411        execQuery(aDatabase, "ALTER TABLE conference ADD COLUMN map VARCHAR");
412    }
413}
Note: See TracBrowser for help on using the repository browser.