source: src/sql/sqlengine.cpp @ d06ae27

qt5
Last change on this file since d06ae27 was d06ae27, checked in by kirilma <kirilma@…>, 12 years ago

store URL's for conferences

  • use it at update
  • let user update the url before request
  • Property mode set to 100644
File size: 12.9 KB
Line 
1/*
2 * Copyright (C) 2010 Ixonos Plc.
3 *
4 * This file is part of fosdem-schedule.
5 *
6 * fosdem-schedule 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 * fosdem-schedule 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 * fosdem-schedule.  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        // copy conference Db from resource, instead of creating
54        // empty tables and then parsing the schedule
55        QFile dbFile(aDatabaseName);
56        QFile(":/fosdem.sqlite").copy(aDatabaseName);
57        dbFile.setPermissions(QFile::ReadOwner | QFile::WriteOwner | QFile::ReadGroup | QFile::WriteGroup);
58        database.open();
59    }
60    else
61    {
62        database.open();
63    }
64
65    //LOG_INFO(QString("Opening '%1' database '%2'").arg(aDatabaseType).arg(aDatabaseName));
66
67    return result ? QString() : database.lastError().text();
68}
69
70void SqlEngine::initialize()
71{
72    QString databaseName;
73    if(!QDir::home().exists(".fosdem"))
74        QDir::home().mkdir(".fosdem");
75    databaseName = QDir::homePath() + "/.fosdem/" + "fosdem.sqlite";
76    login("QSQLITE",databaseName);
77}
78
79void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference)
80{
81    QSqlDatabase db = QSqlDatabase::database();
82
83    if (db.isValid() && db.isOpen())
84    {
85        int confId = 0;
86        QList<Conference> confsList = Conference::getAll();
87        if(confsList.count())
88        {
89            QListIterator<Conference> i(confsList);
90            while (i.hasNext())
91            {
92                Conference conf = i.next();
93                if( aConference["title"] == conf.title() )
94                {
95                    confId = conf.id();
96                    aConference["id"] = QString::number(confId);
97                    break;
98                }
99            }
100        }
101
102        if(!confId) // conference 'aConference' isn't in the table => insert
103        {
104            QSqlQuery query(db);
105            query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,days,"
106                                                    "day_change,timeslot_duration,active) "
107                            " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,:days,"
108                                                    ":day_change,:timeslot_duration,:active)");
109            foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city" << "days")) {
110                query.bindValue(QString(":") + prop_name, aConference[prop_name]);
111            }
112            query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
113            query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
114            query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
115            query.bindValue(":day_change", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
116            query.bindValue(":active", confsList.count() > 0 ? 0 : 1);
117            query.exec();
118            aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
119        }
120    }
121}
122
123void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent)
124{
125    //LOG_DEBUG(QString("Adding event '%1' to DB").arg(*aEvent));
126
127    QSqlDatabase db = QSqlDatabase::database();
128
129    if (db.isValid() && db.isOpen())
130    {
131        //insert event track to table and get track id
132        QString name = aEvent["track"];
133        Track track;
134        int trackId;
135        try
136        {
137            track = Track::retrieveByName(name);
138            trackId = track.id();
139            /*qDebug() << QString("DEBUG: Track %1 in DB").arg(name);*/
140        }
141        catch (OrmNoObjectException &e) {
142            track.setName(name);
143            trackId = track.insert();
144            /*qDebug() << QString("DEBUG: Track %1 added to DB").arg(name);*/
145        }
146        QDateTime startDateTime;
147        startDateTime.setTimeSpec(Qt::UTC);
148        startDateTime = QDateTime(QDate::fromString(aEvent["date"],DATE_FORMAT),QTime::fromString(aEvent["start"],TIME_FORMAT),Qt::UTC);
149        qDebug() << "startDateTime: " << startDateTime.toString();
150
151        bool event_exists = false;
152        {
153            QSqlQuery check_event_query;
154            check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
155            check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
156            check_event_query.bindValue(":id", aEvent["id"]);
157            if (!check_event_query.exec()) {
158                qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
159                        << "event id:" << aEvent["id"]
160                        << "error:" << check_event_query.lastError()
161                        ;
162                return;
163            }
164            if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
165                event_exists = true;
166            }
167        }
168
169        QSqlQuery result;
170        if (event_exists) {
171            result.prepare("UPDATE EVENT SET"
172                            " start = :start"
173                            ", duration = :duration"
174                            ", xid_track = :xid_track"
175                            ", type = :type"
176                            ", language = :language"
177                            ", tag = :tag"
178                            ", title = :title"
179                            ", subtitle = :subtitle"
180                            ", abstract = :abstract"
181                            ", description = :description"
182                                " WHERE id = :id AND xid_conference = :xid_conference");
183        } else {
184            result.prepare("INSERT INTO EVENT "
185                            " (xid_conference, id, start, duration, xid_track, type, "
186                                " language, tag, title, subtitle, abstract, description) "
187                            " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
188                                ":language, :tag, :title, :subtitle, :abstract, :description)");
189        }
190        result.bindValue(":xid_conference", aEvent["conference_id"]);
191        result.bindValue(":start", QString::number(startDateTime.toTime_t()));
192        result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
193        result.bindValue(":xid_track", trackId);
194        static const QList<QString> props = QList<QString>()
195            << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
196        foreach (QString prop_name, props) {
197            result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
198        }
199        if (!result.exec()) {
200            qWarning() << "event insert/update failed:" << result.lastError();
201        }
202    }
203}
204
205void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson)
206{
207    QSqlDatabase db = QSqlDatabase::database();
208
209    //TODO: check if the person doesn't exist before inserting
210    if (db.isValid() && db.isOpen())
211    {
212        QString values = QString("'%1', '%2'").arg(aPerson["id"],aPerson["name"]);
213        QString query = QString("INSERT INTO PERSON (id,name) VALUES (%1)").arg(values);
214        QSqlQuery result (query, db);
215        //LOG_AUTOTEST(query);
216
217        values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["event_id"],aPerson["id"]);
218        query = QString("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (%1)").arg(values);
219        QSqlQuery resultEventPerson (query, db);
220        //LOG_AUTOTEST(query);
221    }
222}
223
224void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
225{
226    QSqlDatabase db = QSqlDatabase::database();
227
228    if (db.isValid() && db.isOpen())
229    {
230        QString queryExist = QString("SELECT id FROM ROOM WHERE name='%1'").arg(aRoom["name"]);
231        QSqlQuery resultExist(queryExist,db);
232        // now we have to check whether ROOM record with 'name' exists or not,
233        // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
234        //   and assign autoincremented 'id' to aRoom
235        // - if it exists, then we need to get its 'id' and assign it to aRoom
236        int roomId = -1;
237        if(resultExist.next()) // ROOM record with 'name' already exists: we need to get its 'id'
238        {
239            roomId = resultExist.value(0).toInt();
240        }
241        else // ROOM record doesn't exist yet, need to create it
242        {
243            QString values = QString("'%1', '%2'").arg(aRoom["name"],aRoom["picture"]);
244            QString query = QString("INSERT INTO ROOM (name,picture) VALUES (%1)").arg(values);
245            QSqlQuery result (query, db);
246            roomId = result.lastInsertId().toInt(); // 'id' is assigned automatically
247            //LOG_AUTOTEST(query);
248        }
249
250        QString values = QString("'%1', '%2', '%3'").arg(aRoom["conference_id"],aRoom["event_id"],QString::number(roomId));
251        QString query = QString("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (%1)").arg(values);
252        QSqlQuery result (query, db);
253        //LOG_AUTOTEST(query);
254    }
255}
256
257void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
258{
259    QSqlDatabase db = QSqlDatabase::database();
260
261    //TODO: check if the link doesn't exist before inserting
262    if (db.isValid() && db.isOpen())
263    {
264        QString values = QString("'%1', '%2', '%3', '%4'").arg(aLink["event_id"],aLink["conference_id"],aLink["name"],aLink["url"]);
265        QString query = QString("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (%1)").arg(values);
266        QSqlQuery result(query, db);
267        //LOG_AUTOTEST(query);
268    }
269}
270
271int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword)
272{
273    QSqlDatabase db = QSqlDatabase::database();
274
275    if ( !db.isValid() || !db.isOpen())
276        return -1;
277
278
279    // DROP
280    execQuery( db, "DROP TABLE IF EXISTS SEARCH_EVENT;");
281    // CREATE
282    execQuery( db, "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER  NOT NULL, id INTEGER NOT NULL );");
283    // INSERT
284    QString query = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
285                "SELECT EVENT.xid_conference, EVENT.id FROM EVENT ");
286    if( aColumns.contains("ROOM") ){
287        query += "INNER JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
288        query += "INNER JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
289    }
290    if( aColumns.contains("PERSON") ){
291        query += "INNER JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
292        query += "INNER JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
293    }
294    query += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
295
296    foreach (QString table, aColumns.uniqueKeys()){
297        foreach (QString column, aColumns.values(table)){
298            query += QString("%1.%2 LIKE '\%%3\%' OR ").arg( table, column, aKeyword );
299        }
300    }
301    query.chop( QString(" OR ").length() );
302    query += QString(");");
303
304    execQuery( db, query );
305
306    return 1;
307}
308
309bool SqlEngine::beginTransaction()
310{
311    QSqlDatabase db = QSqlDatabase::database();
312
313    return execQuery(db, "BEGIN IMMEDIATE TRANSACTION");
314}
315
316bool SqlEngine::commitTransaction()
317{
318    QSqlDatabase db = QSqlDatabase::database();
319
320    return execQuery(db, "COMMIT");
321}
322
323bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
324{
325    //qDebug() << "\nSQL: " << aQuery;
326
327    QSqlQuery sqlQuery(aDatabase);
328    if( !sqlQuery.exec(aQuery) ){
329       qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
330       return false;
331    }
332    else{
333       //qDebug() << "SQL OK.\n";
334       return true;
335    }
336}
337
Note: See TracBrowser for help on using the repository browser.