2 * Copyright (C) 2010 Ixonos Plc.
3 * Copyright (C) 2011-2017 Philipp Spitzer, gregor herrmann, Stefan Stahl
5 * This file is part of ConfClerk.
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)
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
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/>.
27 #if QT_VERSION >= 0x050000
28 #include <QStandardPaths>
30 #include <QDesktopServices>
34 #include "sqlengine.h"
36 #include "conference.h"
40 SqlEngine::SqlEngine(QObject *aParent): QObject(aParent) {
41 #if QT_VERSION >= 0x050000
42 QDir dbPath(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
44 QDir dbPath(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
46 dbFilename = dbPath.absoluteFilePath("ConfClerk.sqlite");
50 SqlEngine::~SqlEngine() {
54 void SqlEngine::open() {
55 // we may have to create the directory of the database
56 QFileInfo dbFilenameInfo(dbFilename);
58 cwd.mkpath(dbFilenameInfo.absolutePath());
59 // We don't have to handle errors because in worst case, opening the database will fail
60 // and db.isOpen() returns false.
61 db = QSqlDatabase::addDatabase("QSQLITE");
62 db.setDatabaseName(dbFilename);
67 int SqlEngine::dbSchemaVersion() {
69 if (!query.exec("PRAGMA user_version")) {
70 emitSqlQueryError(query);
74 int version = query.value(0).toInt();
76 // check whether the tables are existing
77 if (!query.exec("select count(*) from sqlite_master where name='CONFERENCE'")) {
78 emitSqlQueryError(query);
82 if (query.value(0).toInt() == 1) return 0; // tables are existing
83 return -1; // database seems to be empty (or has other tables)
89 bool SqlEngine::updateDbSchemaVersion000To001() {
90 return applySqlFile(":/dbschema000to001.sql");
94 bool SqlEngine::createCurrentDbSchema() {
95 return applySqlFile(":/dbschema001.sql");
99 bool SqlEngine::createOrUpdateDbSchema() {
100 int version = dbSchemaVersion();
103 // the error has already been emitted by the previous function
107 return createCurrentDbSchema();
109 // db schema version 0
110 return updateDbSchemaVersion000To001();
115 // unsupported schema
116 emit dbError(tr("Unsupported database schema version %1.").arg(version));
122 bool SqlEngine::applySqlFile(const QString sqlFile) {
124 file.open(QIODevice::ReadOnly | QIODevice::Text);
125 QString allSqlStatements = file.readAll();
127 foreach(QString sql, allSqlStatements.split(";")) {
128 if (sql.trimmed().isEmpty()) // do not execute empty queries like the last character from create_tables.sql
130 if (!query.exec(sql)) {
131 emitSqlQueryError(query);
139 void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference, int conferenceId) {
141 bool insert = conferenceId <= 0;
142 if (insert) { // insert conference
143 query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,"
144 "day_change,timeslot_duration,active) "
145 " VALUES (:title,:url,:subtitle,:venue,:city,:start,:end,"
146 ":day_change,:timeslot_duration,:active)");
147 } else { // update conference
148 query.prepare("UPDATE CONFERENCE set title=:title, url=:url, subtitle=:subtitle, venue=:venue, city=:city, start=:start, end=:end,"
149 "day_change=:day_change, timeslot_duration=:timeslot_duration, active=:active "
152 foreach (QString prop_name, (QList<QString>() << "title" << "url" << "subtitle" << "venue" << "city")) {
153 query.bindValue(QString(":") + prop_name, aConference[prop_name]);
155 query.bindValue(":start", QDateTime(QDate::fromString(aConference["start"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
156 query.bindValue(":end", QDateTime(QDate::fromString(aConference["end"],DATE_FORMAT),QTime(0,0),Qt::UTC).toTime_t());
157 query.bindValue(":day_change", -QTime::fromString(aConference["day_change"],TIME_FORMAT).secsTo(QTime(0,0)));
158 query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
159 query.bindValue(":active", 1);
160 if (!insert) query.bindValue(":id", conferenceId);
162 emitSqlQueryError(query);
164 aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
166 aConference["id"] = QVariant(conferenceId).toString();
171 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent) {
172 int conferenceId = aEvent["conference_id"].toInt();
173 Conference conference = Conference::getById(conferenceId);
175 // insert event track to table and get track id
178 QString trackName = aEvent["track"];
179 if (trackName.isEmpty()) trackName = tr("No track");
182 track = Track::retrieveByName(conferenceId, trackName);
183 trackId = track.id();
185 catch (OrmNoObjectException &e) {
186 track.setConference(conferenceId);
187 track.setName(trackName);
188 trackId = track.insert();
190 QDate startDate = QDate::fromString(aEvent["date"], DATE_FORMAT);
191 QTime startTime = QTime::fromString(aEvent["start"], TIME_FORMAT);
192 QDateTime startDateTime;
193 startDateTime.setTimeSpec(Qt::UTC);
194 startDateTime = QDateTime(startDate, startTime, Qt::UTC);
196 bool event_exists = false;
198 QSqlQuery check_event_query;
199 check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
200 check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
201 check_event_query.bindValue(":id", aEvent["id"]);
202 if (!check_event_query.exec()) {
203 qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
204 << "event id:" << aEvent["id"]
205 << "error:" << check_event_query.lastError()
209 if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
216 result.prepare("UPDATE EVENT SET"
218 ", duration = :duration"
219 ", xid_track = :xid_track"
221 ", language = :language"
224 ", subtitle = :subtitle"
225 ", abstract = :abstract"
226 ", description = :description"
227 " WHERE id = :id AND xid_conference = :xid_conference");
229 result.prepare("INSERT INTO EVENT "
230 " (xid_conference, id, start, duration, xid_track, type, "
231 " language, tag, title, subtitle, abstract, description) "
232 " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
233 ":language, :tag, :title, :subtitle, :abstract, :description)");
235 result.bindValue(":xid_conference", aEvent["conference_id"]);
236 result.bindValue(":start", QString::number(startDateTime.toTime_t()));
237 result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
238 result.bindValue(":xid_track", trackId);
239 static const QList<QString> props = QList<QString>()
240 << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
241 foreach (QString prop_name, props) {
242 result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
244 if (!result.exec()) {
245 qWarning() << "event insert/update failed:" << result.lastError();
250 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson) {
252 query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)");
253 query.bindValue(":xid_conference", aPerson["conference_id"]);
254 query.bindValue(":id", aPerson["id"]);
255 query.bindValue(":name", aPerson["name"]);
256 query.exec(); // TODO some queries fail due to the unique key constraint
257 // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError();
259 query = QSqlQuery(db);
260 query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)");
261 query.bindValue(":xid_conference", aPerson["conference_id"]);
262 query.bindValue(":xid_event", aPerson["event_id"]);
263 query.bindValue(":xid_person", aPerson["id"]);
264 query.exec(); // TODO some queries fail due to the unique key constraint
265 // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError();
269 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom) {
271 query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
272 query.bindValue(":conference_id", aRoom["conference_id"]);
273 query.bindValue(":name", aRoom["name"]);
275 emitSqlQueryError(query);
276 // now we have to check whether ROOM record with 'name' exists or not,
277 // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
278 // and assign autoincremented 'id' to aRoom
279 // - if it exists, then we need to get its 'id' and assign it to aRoom
281 if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
283 aRoom["id"] = query.value(0).toString();
285 else // ROOM record doesn't exist yet, need to create it
287 query = QSqlQuery(db);
288 query.prepare("INSERT INTO ROOM (xid_conference,name) VALUES (:xid_conference, :name)");
289 query.bindValue(":xid_conference", aRoom["conference_id"]);
290 query.bindValue(":name", aRoom["name"]);
292 emitSqlQueryError(query);
293 aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
294 //LOG_AUTOTEST(query);
297 // remove previous conference/room records; room names might have changed
298 query = QSqlQuery(db);
299 query.prepare("DELETE FROM EVENT_ROOM WHERE xid_conference=:conference_id AND xid_event=:event_id");
300 query.bindValue(":conference_id", aRoom["conference_id"]);
301 query.bindValue(":event_id", aRoom["event_id"]);
303 emitSqlQueryError(query);
304 // and insert new ones
305 query = QSqlQuery(db);
306 query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
307 query.bindValue(":conference_id", aRoom["conference_id"]);
308 query.bindValue(":event_id", aRoom["event_id"]);
309 query.bindValue(":room_id", aRoom["id"]);
311 emitSqlQueryError(query);
315 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink) {
316 //TODO: check if the link doesn't exist before inserting
318 query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
319 query.bindValue(":xid_event", aLink["event_id"]);
320 query.bindValue(":xid_conference", aLink["conference_id"]);
321 query.bindValue(":name", aLink["name"]);
322 query.bindValue(":url", aLink["url"]);
324 emitSqlQueryError(query);
328 bool SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword) {
329 if (aColumns.empty()) return false;
333 query.exec("DROP TABLE IF EXISTS SEARCH_EVENT");
334 emitSqlQueryError(query);
337 query.exec("CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL )");
338 emitSqlQueryError(query);
341 QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
342 "SELECT DISTINCT EVENT.xid_conference, EVENT.id FROM EVENT ");
343 if( aColumns.contains("ROOM") ){
344 sql += "LEFT JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
345 sql += "LEFT JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
347 if( aColumns.contains("PERSON") ){
348 sql += "LEFT JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
349 sql += "LEFT JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
351 sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
353 QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
354 QStringList whereAnd;
355 for (int i=0; i < searchKeywords.count(); i++) {
357 foreach (QString table, aColumns.uniqueKeys()) {
358 foreach (QString column, aColumns.values(table)){
359 whereOr.append(QString("%1.%2 LIKE '\%' || :%1%2%3 || '\%'").arg(table).arg(column).arg(i));
362 whereAnd.append(whereOr.join(" OR "));
364 sql += whereAnd.join(") AND (");
368 for (int i = 0; i != searchKeywords.size(); ++i) {
369 QString keyword = searchKeywords[i];
370 foreach (QString table, aColumns.uniqueKeys()) {
371 foreach (QString column, aColumns.values(table)) {
372 query.bindValue(QString(":%1%2%3").arg(table).arg(column).arg(i), keyword );
377 bool success = query.exec();
378 emitSqlQueryError(query);
383 bool SqlEngine::beginTransaction() {
385 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
386 emitSqlQueryError(query);
391 bool SqlEngine::commitTransaction() {
393 bool success = query.exec("COMMIT");
394 emitSqlQueryError(query);
399 bool SqlEngine::deleteConference(int id) {
401 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
402 emitSqlQueryError(query);
405 sqlList << "DELETE FROM LINK WHERE xid_conference = ?"
406 << "DELETE FROM EVENT_ROOM WHERE xid_conference = ?"
407 << "DELETE FROM EVENT_PERSON WHERE xid_conference = ?"
408 << "DELETE FROM EVENT WHERE xid_conference = ?"
409 << "DELETE FROM ROOM WHERE xid_conference = ?"
410 << "DELETE FROM PERSON WHERE xid_conference = ?"
411 << "DELETE FROM TRACK WHERE xid_conference = ?"
412 << "DELETE FROM CONFERENCE WHERE id = ?";
414 foreach (const QString& sql, sqlList) {
416 query.bindValue(0, id);
417 success &= query.exec();
418 emitSqlQueryError(query);
421 success &= query.exec("COMMIT");
422 emitSqlQueryError(query);
428 void SqlEngine::emitSqlQueryError(const QSqlQuery &query) {
429 QSqlError error = query.lastError();
430 if (error.type() == QSqlError::NoError) return;
431 emit dbError(error.text());