1 | /* |
---|
2 | * Copyright (C) 2010 Ixonos Plc. |
---|
3 | * Copyright (C) 2011-2013 Philipp Spitzer, gregor herrmann, Stefan Stahl |
---|
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 | |
---|
35 | const QString DATE_FORMAT ("yyyy-MM-dd"); |
---|
36 | const QString TIME_FORMAT ("hh:mm"); |
---|
37 | |
---|
38 | SqlEngine::SqlEngine(QObject *aParent): QObject(aParent) { |
---|
39 | QDir dbPath(QDesktopServices::storageLocation(QDesktopServices::DataLocation)); |
---|
40 | dbFilename = dbPath.absoluteFilePath("ConfClerk.sqlite"); |
---|
41 | } |
---|
42 | |
---|
43 | |
---|
44 | SqlEngine::~SqlEngine() { |
---|
45 | } |
---|
46 | |
---|
47 | |
---|
48 | void SqlEngine::open() { |
---|
49 | // we may have to create the directory of the database |
---|
50 | QFileInfo dbFilenameInfo(dbFilename); |
---|
51 | QDir cwd; |
---|
52 | cwd.mkpath(dbFilenameInfo.absolutePath()); |
---|
53 | // We don't have to handle errors because in worst case, opening the database will fail |
---|
54 | // and db.isOpen() returns false. |
---|
55 | db = QSqlDatabase::addDatabase("QSQLITE"); |
---|
56 | db.setDatabaseName(dbFilename); |
---|
57 | db.open(); |
---|
58 | } |
---|
59 | |
---|
60 | |
---|
61 | int SqlEngine::dbSchemaVersion() { |
---|
62 | QSqlQuery query(db); |
---|
63 | if (!query.exec("PRAGMA user_version")) { |
---|
64 | emitSqlQueryError(query); |
---|
65 | return -2; |
---|
66 | } |
---|
67 | query.first(); |
---|
68 | int version = query.value(0).toInt(); |
---|
69 | if (version == 0) { |
---|
70 | // check whether the tables are existing |
---|
71 | if (!query.exec("select count(*) from sqlite_master where name='CONFERENCE'")) { |
---|
72 | emitSqlQueryError(query); |
---|
73 | return -2; |
---|
74 | } |
---|
75 | query.first(); |
---|
76 | if (query.value(0).toInt() == 1) return 0; // tables are existing |
---|
77 | return -1; // database seems to be empty (or has other tables) |
---|
78 | } |
---|
79 | return version; |
---|
80 | } |
---|
81 | |
---|
82 | |
---|
83 | bool SqlEngine::updateDbSchemaVersion000To001() { |
---|
84 | return applySqlFile(":/dbschema000to001.sql"); |
---|
85 | } |
---|
86 | |
---|
87 | |
---|
88 | bool SqlEngine::createCurrentDbSchema() { |
---|
89 | return applySqlFile(":/dbschema001.sql"); |
---|
90 | } |
---|
91 | |
---|
92 | |
---|
93 | bool SqlEngine::createOrUpdateDbSchema() { |
---|
94 | int version = dbSchemaVersion(); |
---|
95 | switch (version) { |
---|
96 | case -2: |
---|
97 | // the error has already been emitted by the previous function |
---|
98 | return false; |
---|
99 | case -1: |
---|
100 | // empty database |
---|
101 | return createCurrentDbSchema(); |
---|
102 | case 0: |
---|
103 | // db schema version 0 |
---|
104 | return updateDbSchemaVersion000To001(); |
---|
105 | case 1: |
---|
106 | // current schema |
---|
107 | return true; |
---|
108 | default: |
---|
109 | // unsupported schema |
---|
110 | emit dbError(tr("Unsupported database schema version %1.").arg(version)); |
---|
111 | } |
---|
112 | return false; |
---|
113 | } |
---|
114 | |
---|
115 | |
---|
116 | bool SqlEngine::applySqlFile(const QString sqlFile) { |
---|
117 | QFile file(sqlFile); |
---|
118 | file.open(QIODevice::ReadOnly | QIODevice::Text); |
---|
119 | QString allSqlStatements = file.readAll(); |
---|
120 | QSqlQuery query(db); |
---|
121 | foreach(QString sql, allSqlStatements.split(";")) { |
---|
122 | if (sql.trimmed().isEmpty()) // do not execute empty queries like the last character from create_tables.sql |
---|
123 | continue; |
---|
124 | if (!query.exec(sql)) { |
---|
125 | emitSqlQueryError(query); |
---|
126 | return false; |
---|
127 | } |
---|
128 | } |
---|
129 | return true; |
---|
130 | } |
---|
131 | |
---|
132 | |
---|
133 | void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference, int conferenceId) { |
---|
134 | QSqlQuery query(db); |
---|
135 | if (conferenceId <= 0) // insert conference |
---|
136 | { |
---|
137 | query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end," |
---|
138 | "day_change,timeslot_duration,active) " |
---|
139 | " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end," |
---|
140 | ":day_change,:timeslot_duration,:active)"); |
---|
141 | foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) { |
---|
142 | query.bindValue(QString(":") + prop_name, aConference[prop_name]); |
---|
143 | } |
---|
144 | query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t()); |
---|
145 | query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t()); |
---|
146 | query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0))); |
---|
147 | query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0))); |
---|
148 | query.bindValue(":active", 1); |
---|
149 | query.exec(); |
---|
150 | emitSqlQueryError(query); |
---|
151 | aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically |
---|
152 | } |
---|
153 | else // update conference |
---|
154 | { |
---|
155 | query.prepare("UPDATE CONFERENCE set title=:title, url=:url, subtitle=:subtitle, venue=:venue, city=:city, start=:start, end=:end," |
---|
156 | "day_change=:day_change, timeslot_duration=:timeslot_duration, active=:active " |
---|
157 | "WHERE id=:id"); |
---|
158 | foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) { |
---|
159 | query.bindValue(QString(":") + prop_name, aConference[prop_name]); |
---|
160 | } |
---|
161 | query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t()); |
---|
162 | query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t()); |
---|
163 | query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0))); |
---|
164 | query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0))); |
---|
165 | query.bindValue(":active", 1); |
---|
166 | query.bindValue(":id", conferenceId); |
---|
167 | query.exec(); |
---|
168 | emitSqlQueryError(query); |
---|
169 | aConference["id"] = QVariant(conferenceId).toString(); |
---|
170 | } |
---|
171 | } |
---|
172 | |
---|
173 | |
---|
174 | void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent) { |
---|
175 | int conferenceId = aEvent["conference_id"].toInt(); |
---|
176 | Conference conference = Conference::getById(conferenceId); |
---|
177 | |
---|
178 | // insert event track to table and get track id |
---|
179 | Track track; |
---|
180 | int trackId; |
---|
181 | QString trackName = aEvent["track"]; |
---|
182 | try |
---|
183 | { |
---|
184 | track = Track::retrieveByName(conferenceId, trackName); |
---|
185 | trackId = track.id(); |
---|
186 | } |
---|
187 | catch (OrmNoObjectException &e) { |
---|
188 | track.setConference(conferenceId); |
---|
189 | track.setName(trackName); |
---|
190 | trackId = track.insert(); |
---|
191 | } |
---|
192 | QDate startDate = QDate::fromString(aEvent["date"], DATE_FORMAT); |
---|
193 | QTime startTime = QTime::fromString(aEvent["start"], TIME_FORMAT); |
---|
194 | // consider day_change (note that if day_change is e.g. at 04:00 AM, an event starting at 02:00 AM has the previous date in the XML file) |
---|
195 | if (startTime < conference.dayChangeTime()) startDate = startDate.addDays(1); |
---|
196 | QDateTime startDateTime; |
---|
197 | startDateTime.setTimeSpec(Qt::UTC); |
---|
198 | startDateTime = QDateTime(startDate, startTime, Qt::UTC); |
---|
199 | |
---|
200 | bool event_exists = false; |
---|
201 | { |
---|
202 | QSqlQuery check_event_query; |
---|
203 | check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id"); |
---|
204 | check_event_query.bindValue(":xid_conference", aEvent["conference_id"]); |
---|
205 | check_event_query.bindValue(":id", aEvent["id"]); |
---|
206 | if (!check_event_query.exec()) { |
---|
207 | qWarning() << "check event failed, conference id:" << aEvent["xid_conference"] |
---|
208 | << "event id:" << aEvent["id"] |
---|
209 | << "error:" << check_event_query.lastError() |
---|
210 | ; |
---|
211 | return; |
---|
212 | } |
---|
213 | if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) { |
---|
214 | event_exists = true; |
---|
215 | } |
---|
216 | } |
---|
217 | |
---|
218 | QSqlQuery result; |
---|
219 | if (event_exists) { |
---|
220 | result.prepare("UPDATE EVENT SET" |
---|
221 | " start = :start" |
---|
222 | ", duration = :duration" |
---|
223 | ", xid_track = :xid_track" |
---|
224 | ", type = :type" |
---|
225 | ", language = :language" |
---|
226 | ", tag = :tag" |
---|
227 | ", title = :title" |
---|
228 | ", subtitle = :subtitle" |
---|
229 | ", abstract = :abstract" |
---|
230 | ", description = :description" |
---|
231 | " WHERE id = :id AND xid_conference = :xid_conference"); |
---|
232 | } else { |
---|
233 | result.prepare("INSERT INTO EVENT " |
---|
234 | " (xid_conference, id, start, duration, xid_track, type, " |
---|
235 | " language, tag, title, subtitle, abstract, description) " |
---|
236 | " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, " |
---|
237 | ":language, :tag, :title, :subtitle, :abstract, :description)"); |
---|
238 | } |
---|
239 | result.bindValue(":xid_conference", aEvent["conference_id"]); |
---|
240 | result.bindValue(":start", QString::number(startDateTime.toTime_t())); |
---|
241 | result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0))); |
---|
242 | result.bindValue(":xid_track", trackId); |
---|
243 | static const QList<QString> props = QList<QString>() |
---|
244 | << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description"; |
---|
245 | foreach (QString prop_name, props) { |
---|
246 | result.bindValue(QString(":") + prop_name, aEvent[prop_name]); |
---|
247 | } |
---|
248 | if (!result.exec()) { |
---|
249 | qWarning() << "event insert/update failed:" << result.lastError(); |
---|
250 | } |
---|
251 | } |
---|
252 | |
---|
253 | |
---|
254 | void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson) { |
---|
255 | QSqlQuery query(db); |
---|
256 | query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)"); |
---|
257 | query.bindValue(":xid_conference", aPerson["conference_id"]); |
---|
258 | query.bindValue(":id", aPerson["id"]); |
---|
259 | query.bindValue(":name", aPerson["name"]); |
---|
260 | query.exec(); // TODO some queries fail due to the unique key constraint |
---|
261 | // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError(); |
---|
262 | |
---|
263 | query = QSqlQuery(db); |
---|
264 | query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)"); |
---|
265 | query.bindValue(":xid_conference", aPerson["conference_id"]); |
---|
266 | query.bindValue(":xid_event", aPerson["event_id"]); |
---|
267 | query.bindValue(":xid_person", aPerson["id"]); |
---|
268 | query.exec(); // TODO some queries fail due to the unique key constraint |
---|
269 | // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError(); |
---|
270 | } |
---|
271 | |
---|
272 | |
---|
273 | void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom) { |
---|
274 | QSqlQuery query(db); |
---|
275 | query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name"); |
---|
276 | query.bindValue(":conference_id", aRoom["conference_id"]); |
---|
277 | query.bindValue(":name", aRoom["name"]); |
---|
278 | query.exec(); |
---|
279 | emitSqlQueryError(query); |
---|
280 | // now we have to check whether ROOM record with 'name' exists or not, |
---|
281 | // - if it doesn't exist yet, then we have to add that record to 'ROOM' table |
---|
282 | // and assign autoincremented 'id' to aRoom |
---|
283 | // - if it exists, then we need to get its 'id' and assign it to aRoom |
---|
284 | aRoom["id"] = ""; |
---|
285 | if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id' |
---|
286 | { |
---|
287 | aRoom["id"] = query.value(0).toString(); |
---|
288 | } |
---|
289 | else // ROOM record doesn't exist yet, need to create it |
---|
290 | { |
---|
291 | query = QSqlQuery(db); |
---|
292 | query.prepare("INSERT INTO ROOM (xid_conference,name) VALUES (:xid_conference, :name)"); |
---|
293 | query.bindValue(":xid_conference", aRoom["conference_id"]); |
---|
294 | query.bindValue(":xid_name", aRoom["name"]); |
---|
295 | query.exec(); |
---|
296 | emitSqlQueryError(query); |
---|
297 | aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically |
---|
298 | //LOG_AUTOTEST(query); |
---|
299 | } |
---|
300 | |
---|
301 | // remove previous conference/room records; room names might have changed |
---|
302 | query = QSqlQuery(db); |
---|
303 | query.prepare("DELETE FROM EVENT_ROOM WHERE xid_conference=:conference_id AND xid_event=:event_id"); |
---|
304 | query.bindValue(":conference_id", aRoom["conference_id"]); |
---|
305 | query.bindValue(":event_id", aRoom["event_id"]); |
---|
306 | query.exec(); |
---|
307 | emitSqlQueryError(query); |
---|
308 | // and insert new ones |
---|
309 | query = QSqlQuery(db); |
---|
310 | query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)"); |
---|
311 | query.bindValue(":conference_id", aRoom["conference_id"]); |
---|
312 | query.bindValue(":event_id", aRoom["event_id"]); |
---|
313 | query.bindValue(":room_id", aRoom["id"]); |
---|
314 | query.exec(); |
---|
315 | emitSqlQueryError(query); |
---|
316 | } |
---|
317 | |
---|
318 | |
---|
319 | void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink) { |
---|
320 | //TODO: check if the link doesn't exist before inserting |
---|
321 | QSqlQuery query(db); |
---|
322 | query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)"); |
---|
323 | query.bindValue(":xid_event", aLink["event_id"]); |
---|
324 | query.bindValue(":xid_conference", aLink["conference_id"]); |
---|
325 | query.bindValue(":name", aLink["name"]); |
---|
326 | query.bindValue(":url", aLink["url"]); |
---|
327 | query.exec(); |
---|
328 | emitSqlQueryError(query); |
---|
329 | } |
---|
330 | |
---|
331 | |
---|
332 | bool SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword) { |
---|
333 | if (aColumns.empty()) return false; |
---|
334 | |
---|
335 | // DROP |
---|
336 | QSqlQuery query(db); |
---|
337 | query.exec("DROP TABLE IF EXISTS SEARCH_EVENT"); |
---|
338 | emitSqlQueryError(query); |
---|
339 | |
---|
340 | // CREATE |
---|
341 | query.exec("CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL )"); |
---|
342 | emitSqlQueryError(query); |
---|
343 | |
---|
344 | // INSERT |
---|
345 | QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) " |
---|
346 | "SELECT DISTINCT EVENT.xid_conference, EVENT.id FROM EVENT "); |
---|
347 | if( aColumns.contains("ROOM") ){ |
---|
348 | sql += "LEFT JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) "; |
---|
349 | sql += "LEFT JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) "; |
---|
350 | } |
---|
351 | if( aColumns.contains("PERSON") ){ |
---|
352 | sql += "LEFT JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) "; |
---|
353 | sql += "LEFT JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) "; |
---|
354 | } |
---|
355 | sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId ); |
---|
356 | |
---|
357 | QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+")); |
---|
358 | QStringList whereAnd; |
---|
359 | for (int i=0; i < searchKeywords.count(); i++) { |
---|
360 | QStringList whereOr; |
---|
361 | foreach (QString table, aColumns.uniqueKeys()) { |
---|
362 | foreach (QString column, aColumns.values(table)){ |
---|
363 | whereOr.append(QString("%1.%2 LIKE '\%' || :%1%2%3 || '\%'").arg(table).arg(column).arg(i)); |
---|
364 | } |
---|
365 | } |
---|
366 | whereAnd.append(whereOr.join(" OR ")); |
---|
367 | } |
---|
368 | sql += whereAnd.join(") AND ("); |
---|
369 | sql += QString(")"); |
---|
370 | |
---|
371 | query.prepare(sql); |
---|
372 | for (int i = 0; i != searchKeywords.size(); ++i) { |
---|
373 | QString keyword = searchKeywords[i]; |
---|
374 | foreach (QString table, aColumns.uniqueKeys()) { |
---|
375 | foreach (QString column, aColumns.values(table)) { |
---|
376 | query.bindValue(QString(":%1%2%3").arg(table).arg(column).arg(i), keyword ); |
---|
377 | } |
---|
378 | } |
---|
379 | } |
---|
380 | |
---|
381 | bool success = query.exec(); |
---|
382 | emitSqlQueryError(query); |
---|
383 | return success; |
---|
384 | } |
---|
385 | |
---|
386 | |
---|
387 | bool SqlEngine::beginTransaction() { |
---|
388 | QSqlQuery query(db); |
---|
389 | bool success = query.exec("BEGIN IMMEDIATE TRANSACTION"); |
---|
390 | emitSqlQueryError(query); |
---|
391 | return success; |
---|
392 | } |
---|
393 | |
---|
394 | |
---|
395 | bool SqlEngine::commitTransaction() { |
---|
396 | QSqlQuery query(db); |
---|
397 | bool success = query.exec("COMMIT"); |
---|
398 | emitSqlQueryError(query); |
---|
399 | return success; |
---|
400 | } |
---|
401 | |
---|
402 | |
---|
403 | bool SqlEngine::deleteConference(int id) { |
---|
404 | QSqlQuery query(db); |
---|
405 | bool success = query.exec("BEGIN IMMEDIATE TRANSACTION"); |
---|
406 | emitSqlQueryError(query); |
---|
407 | |
---|
408 | QStringList sqlList; |
---|
409 | sqlList << "DELETE FROM LINK WHERE xid_conference = ?" |
---|
410 | << "DELETE FROM EVENT_ROOM WHERE xid_conference = ?" |
---|
411 | << "DELETE FROM EVENT_PERSON WHERE xid_conference = ?" |
---|
412 | << "DELETE FROM EVENT WHERE xid_conference = ?" |
---|
413 | << "DELETE FROM ROOM WHERE xid_conference = ?" |
---|
414 | << "DELETE FROM PERSON WHERE xid_conference = ?" |
---|
415 | << "DELETE FROM TRACK WHERE xid_conference = ?" |
---|
416 | << "DELETE FROM CONFERENCE WHERE id = ?"; |
---|
417 | |
---|
418 | foreach (const QString& sql, sqlList) { |
---|
419 | query.prepare(sql); |
---|
420 | query.bindValue(0, id); |
---|
421 | success &= query.exec(); |
---|
422 | emitSqlQueryError(query); |
---|
423 | } |
---|
424 | |
---|
425 | success &= query.exec("COMMIT"); |
---|
426 | emitSqlQueryError(query); |
---|
427 | |
---|
428 | return success; |
---|
429 | } |
---|
430 | |
---|
431 | |
---|
432 | void SqlEngine::emitSqlQueryError(const QSqlQuery &query) { |
---|
433 | QSqlError error = query.lastError(); |
---|
434 | if (error.type() == QSqlError::NoError) return; |
---|
435 | emit dbError(error.text()); |
---|
436 | } |
---|
437 | |
---|