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 QTime dayChange = QTime::fromString(aConference["day_change"].left(TIME_FORMAT.size()), TIME_FORMAT);
158 query.bindValue(":day_change", QTime(0, 0).secsTo(dayChange));
159 query.bindValue(":timeslot_duration", -QTime::fromString(aConference["timeslot_duration"],TIME_FORMAT).secsTo(QTime(0,0)));
160 query.bindValue(":active", 1);
161 if (!insert) query.bindValue(":id", conferenceId);
163 emitSqlQueryError(query);
165 aConference["id"] = query.lastInsertId().toString(); // 'id' is assigned automatically
167 aConference["id"] = QVariant(conferenceId).toString();
172 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent) {
173 int conferenceId = aEvent["conference_id"].toInt();
174 Conference conference = Conference::getById(conferenceId);
176 // insert event track to table and get track id
179 QString trackName = aEvent["track"];
180 if (trackName.isEmpty()) trackName = tr("No track");
183 track = Track::retrieveByName(conferenceId, trackName);
184 trackId = track.id();
186 catch (OrmNoObjectException &e) {
187 track.setConference(conferenceId);
188 track.setName(trackName);
189 trackId = track.insert();
191 QDate startDate = QDate::fromString(aEvent["date"], DATE_FORMAT);
192 QTime startTime = QTime::fromString(aEvent["start"], TIME_FORMAT);
193 QDateTime startDateTime;
194 startDateTime.setTimeSpec(Qt::UTC);
195 startDateTime = QDateTime(startDate, startTime, Qt::UTC);
197 bool event_exists = false;
199 QSqlQuery check_event_query;
200 check_event_query.prepare("SELECT * FROM EVENT WHERE xid_conference = :xid_conference AND id = :id");
201 check_event_query.bindValue(":xid_conference", aEvent["conference_id"]);
202 check_event_query.bindValue(":id", aEvent["id"]);
203 if (!check_event_query.exec()) {
204 qWarning() << "check event failed, conference id:" << aEvent["xid_conference"]
205 << "event id:" << aEvent["id"]
206 << "error:" << check_event_query.lastError()
210 if (check_event_query.isActive() and check_event_query.isSelect() and check_event_query.next()) {
217 result.prepare("UPDATE EVENT SET"
219 ", duration = :duration"
220 ", xid_track = :xid_track"
222 ", language = :language"
225 ", subtitle = :subtitle"
226 ", abstract = :abstract"
227 ", description = :description"
228 " WHERE id = :id AND xid_conference = :xid_conference");
230 result.prepare("INSERT INTO EVENT "
231 " (xid_conference, id, start, duration, xid_track, type, "
232 " language, tag, title, subtitle, abstract, description) "
233 " VALUES (:xid_conference, :id, :start, :duration, :xid_track, :type, "
234 ":language, :tag, :title, :subtitle, :abstract, :description)");
236 result.bindValue(":xid_conference", aEvent["conference_id"]);
237 result.bindValue(":start", QString::number(startDateTime.toTime_t()));
238 result.bindValue(":duration", -QTime::fromString(aEvent["duration"],TIME_FORMAT).secsTo(QTime(0,0)));
239 result.bindValue(":xid_track", trackId);
240 static const QList<QString> props = QList<QString>()
241 << "id" << "type" << "language" << "tag" << "title" << "subtitle" << "abstract" << "description";
242 foreach (QString prop_name, props) {
243 result.bindValue(QString(":") + prop_name, aEvent[prop_name]);
245 if (!result.exec()) {
246 qWarning() << "event insert/update failed:" << result.lastError();
251 void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson) {
253 query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)");
254 query.bindValue(":xid_conference", aPerson["conference_id"]);
255 query.bindValue(":id", aPerson["id"]);
256 query.bindValue(":name", aPerson["name"]);
257 query.exec(); // TODO some queries fail due to the unique key constraint
258 // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError();
260 query = QSqlQuery(db);
261 query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)");
262 query.bindValue(":xid_conference", aPerson["conference_id"]);
263 query.bindValue(":xid_event", aPerson["event_id"]);
264 query.bindValue(":xid_person", aPerson["id"]);
265 query.exec(); // TODO some queries fail due to the unique key constraint
266 // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError();
270 void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom) {
272 query.prepare("SELECT id FROM ROOM WHERE xid_conference=:conference_id and name=:name");
273 query.bindValue(":conference_id", aRoom["conference_id"]);
274 query.bindValue(":name", aRoom["name"]);
276 emitSqlQueryError(query);
277 // now we have to check whether ROOM record with 'name' exists or not,
278 // - if it doesn't exist yet, then we have to add that record to 'ROOM' table
279 // and assign autoincremented 'id' to aRoom
280 // - if it exists, then we need to get its 'id' and assign it to aRoom
282 if(query.next()) // ROOM record with 'name' already exists: we need to get its 'id'
284 aRoom["id"] = query.value(0).toString();
286 else // ROOM record doesn't exist yet, need to create it
288 query = QSqlQuery(db);
289 query.prepare("INSERT INTO ROOM (xid_conference,name) VALUES (:xid_conference, :name)");
290 query.bindValue(":xid_conference", aRoom["conference_id"]);
291 query.bindValue(":name", aRoom["name"]);
293 emitSqlQueryError(query);
294 aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
295 //LOG_AUTOTEST(query);
298 // remove previous conference/room records; room names might have changed
299 query = QSqlQuery(db);
300 query.prepare("DELETE FROM EVENT_ROOM WHERE xid_conference=:conference_id AND xid_event=:event_id");
301 query.bindValue(":conference_id", aRoom["conference_id"]);
302 query.bindValue(":event_id", aRoom["event_id"]);
304 emitSqlQueryError(query);
305 // and insert new ones
306 query = QSqlQuery(db);
307 query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
308 query.bindValue(":conference_id", aRoom["conference_id"]);
309 query.bindValue(":event_id", aRoom["event_id"]);
310 query.bindValue(":room_id", aRoom["id"]);
312 emitSqlQueryError(query);
316 void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink) {
317 //TODO: check if the link doesn't exist before inserting
319 query.prepare("INSERT INTO LINK (xid_event, xid_conference, name, url) VALUES (:xid_event, :xid_conference, :name, :url)");
320 query.bindValue(":xid_event", aLink["event_id"]);
321 query.bindValue(":xid_conference", aLink["conference_id"]);
322 query.bindValue(":name", aLink["name"]);
323 query.bindValue(":url", aLink["url"]);
325 emitSqlQueryError(query);
329 bool SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aColumns, const QString &aKeyword) {
330 if (aColumns.empty()) return false;
334 query.exec("DROP TABLE IF EXISTS SEARCH_EVENT");
335 emitSqlQueryError(query);
338 query.exec("CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER NOT NULL, id INTEGER NOT NULL )");
339 emitSqlQueryError(query);
342 QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
343 "SELECT DISTINCT EVENT.xid_conference, EVENT.id FROM EVENT ");
344 if( aColumns.contains("ROOM") ){
345 sql += "LEFT JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
346 sql += "LEFT JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
348 if( aColumns.contains("PERSON") ){
349 sql += "LEFT JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
350 sql += "LEFT JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
352 sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
354 QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
355 QStringList whereAnd;
356 for (int i=0; i < searchKeywords.count(); i++) {
358 foreach (QString table, aColumns.uniqueKeys()) {
359 foreach (QString column, aColumns.values(table)){
360 whereOr.append(QString("%1.%2 LIKE '\%' || :%1%2%3 || '\%'").arg(table).arg(column).arg(i));
363 whereAnd.append(whereOr.join(" OR "));
365 sql += whereAnd.join(") AND (");
369 for (int i = 0; i != searchKeywords.size(); ++i) {
370 QString keyword = searchKeywords[i];
371 foreach (QString table, aColumns.uniqueKeys()) {
372 foreach (QString column, aColumns.values(table)) {
373 query.bindValue(QString(":%1%2%3").arg(table).arg(column).arg(i), keyword );
378 bool success = query.exec();
379 emitSqlQueryError(query);
384 bool SqlEngine::beginTransaction() {
386 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
387 emitSqlQueryError(query);
392 bool SqlEngine::commitTransaction() {
394 bool success = query.exec("COMMIT");
395 emitSqlQueryError(query);
400 bool SqlEngine::rollbackTransaction() {
402 bool success = query.exec("ROLLBACK");
403 emitSqlQueryError(query);
408 bool SqlEngine::deleteConference(int id) {
410 bool success = query.exec("BEGIN IMMEDIATE TRANSACTION");
411 emitSqlQueryError(query);
414 sqlList << "DELETE FROM LINK WHERE xid_conference = ?"
415 << "DELETE FROM EVENT_ROOM WHERE xid_conference = ?"
416 << "DELETE FROM EVENT_PERSON WHERE xid_conference = ?"
417 << "DELETE FROM EVENT WHERE xid_conference = ?"
418 << "DELETE FROM ROOM WHERE xid_conference = ?"
419 << "DELETE FROM PERSON WHERE xid_conference = ?"
420 << "DELETE FROM TRACK WHERE xid_conference = ?"
421 << "DELETE FROM CONFERENCE WHERE id = ?";
423 foreach (const QString& sql, sqlList) {
425 query.bindValue(0, id);
426 success &= query.exec();
427 emitSqlQueryError(query);
430 success &= query.exec("COMMIT");
431 emitSqlQueryError(query);
437 void SqlEngine::emitSqlQueryError(const QSqlQuery &query) {
438 QSqlError error = query.lastError();
439 if (error.type() == QSqlError::NoError) return;
440 emit dbError(error.text());