source: confclerk_git/src/sql/sqlengine.cpp @ a9f56bb

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

.isEmpty() feels more Qtish then == ""

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