]> ToastFreeware Gitweb - toast/confclerk.git/blobdiff - src/sql/sqlengine.cpp
Add .pro.user.* to svn:ignore and remove it in the release target.
[toast/confclerk.git] / src / sql / sqlengine.cpp
index 65c2dc5dc5d564265b65cb3b387a52fd4abc643a..4212e02b8904c5891915916922dba4b1b399b1dd 100644 (file)
@@ -1,20 +1,21 @@
 /*
  * Copyright (C) 2010 Ixonos Plc.
+ * Copyright (C) 2011-2012 Philipp Spitzer, gregor herrmann, Stefan Stahl
  *
- * This file is part of fosdem-schedule.
+ * This file is part of ConfClerk.
  *
- * fosdem-schedule is free software: you can redistribute it and/or modify it
+ * ConfClerk is free software: you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the Free
  * Software Foundation, either version 2 of the License, or (at your option)
  * any later version.
  *
- * fosdem-schedule is distributed in the hope that it will be useful, but
+ * ConfClerk is distributed in the hope that it will be useful, but
  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
  * more details.
  *
  * You should have received a copy of the GNU General Public License along with
- * fosdem-schedule.  If not, see <http://www.gnu.org/licenses/>.
+ * ConfClerk.  If not, see <http://www.gnu.org/licenses/>.
  */
 
 #include <QSqlError>
@@ -24,6 +25,7 @@
 #include <QDateTime>
 
 #include <QDir>
+#include <QDesktopServices>
 #include "sqlengine.h"
 #include <track.h>
 #include <conference.h>
@@ -56,8 +58,10 @@ QString SqlEngine::login(const QString &aDatabaseType, const QString &aDatabaseN
         file.open(QIODevice::ReadOnly | QIODevice::Text);
         QString allSqlStatements = file.readAll();
         foreach(QString sql, allSqlStatements.split(";")) {
+            if (sql.trimmed().length() == 0)     // do not execute empty queries like the last character from create_tables.sql
+                continue;
             QSqlQuery query(database);
-            if (!query.exec(sql)) qDebug() << "Could not execute query" << query.lastError();
+            if (!query.exec(sql)) qDebug() << "Could not execute query '" << sql << "' error:" << query.lastError();
         }
     }
     else
@@ -65,8 +69,6 @@ QString SqlEngine::login(const QString &aDatabaseType, const QString &aDatabaseN
         database.open();
     }
 
-    checkConferenceMap(database);
-
     //LOG_INFO(QString("Opening '%1' database '%2'").arg(aDatabaseType).arg(aDatabaseName));
 
     return result ? QString() : database.lastError().text();
@@ -75,9 +77,12 @@ QString SqlEngine::login(const QString &aDatabaseType, const QString &aDatabaseN
 void SqlEngine::initialize()
 {
     QString databaseName;
-    if(!QDir::home().exists(".fosdem"))
-        QDir::home().mkdir(".fosdem");
-    databaseName = QDir::homePath() + "/.fosdem/" + "fosdem.sqlite";
+    QString dataDirName;
+    dataDirName = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
+    QDir dataDir = QDir(dataDirName).absolutePath();
+    if(!dataDir.exists())
+        dataDir.mkpath(dataDirName);
+    databaseName = dataDirName + "/ConfClerk.sqlite";
     login("QSQLITE",databaseName);
 }
 
@@ -106,6 +111,11 @@ void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference)
 
         if(!confId) // conference 'aConference' isn't in the table => insert
         {
+            // HACK
+            // When city is empty, assign a dummy value. We probably want to find a way to change the database scheme ...
+            // cf. #32
+            if (aConference["city"].isEmpty()) aConference["city"] = "n/a";
+
             QSqlQuery query(db);
             query.prepare("INSERT INTO CONFERENCE (title,url,subtitle,venue,city,start,end,days,"
                                                     "day_change,timeslot_duration,active) "
@@ -127,8 +137,6 @@ void SqlEngine::addConferenceToDB(QHash<QString,QString> &aConference)
 
 void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent)
 {
-    //LOG_DEBUG(QString("Adding event '%1' to DB").arg(*aEvent));
-
     QSqlDatabase db = QSqlDatabase::database();
 
     if (db.isValid() && db.isOpen())
@@ -142,18 +150,15 @@ void SqlEngine::addEventToDB(QHash<QString,QString> &aEvent)
         {
             track = Track::retrieveByName(conference, name);
             trackId = track.id();
-            /*qDebug() << QString("DEBUG: Track %1 in DB").arg(name);*/
         }
         catch (OrmNoObjectException &e) {
             track.setConference(conference);
             track.setName(name);
             trackId = track.insert();
-            /*qDebug() << QString("DEBUG: Track %1 added to DB").arg(name);*/
         }
         QDateTime startDateTime;
         startDateTime.setTimeSpec(Qt::UTC);
         startDateTime = QDateTime(QDate::fromString(aEvent["date"],DATE_FORMAT),QTime::fromString(aEvent["start"],TIME_FORMAT),Qt::UTC);
-        // qDebug() << "startDateTime: " << startDateTime.toString();
 
         bool event_exists = false;
         {
@@ -215,17 +220,21 @@ void SqlEngine::addPersonToDB(QHash<QString,QString> &aPerson)
 
     if (db.isValid() && db.isOpen())
     {
-        // TODO: SQL Injection!!!
-        QString values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["id"],aPerson["name"]);
-        QString query = QString("INSERT INTO PERSON (xid_conference,id,name) VALUES (%1)").arg(values);
-        QSqlQuery result (query, db);
-        //LOG_AUTOTEST(query);
-
-        // TODO: SQL Injection!!!
-        values = QString("'%1', '%2', '%3'").arg(aPerson["conference_id"],aPerson["event_id"],aPerson["id"]);
-        query = QString("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (%1)").arg(values);
-        QSqlQuery resultEventPerson (query, db);
-        //LOG_AUTOTEST(query);
+        QSqlQuery query(db);
+        query.prepare("INSERT INTO PERSON (xid_conference,id,name) VALUES (:xid_conference, :id, :name)");
+        query.bindValue(":xid_conference", aPerson["conference_id"]);
+        query.bindValue(":id", aPerson["id"]);
+        query.bindValue(":name", aPerson["name"]);
+        query.exec(); // some queries fail due to the unique key constraint
+        // if (!query.exec()) qDebug() << "SQL query 'insert into person' failed: " << query.lastError();
+
+        query = QSqlQuery(db);
+        query.prepare("INSERT INTO EVENT_PERSON (xid_conference,xid_event,xid_person) VALUES (:xid_conference, :xid_event, :xid_person)");
+        query.bindValue(":xid_conference", aPerson["conference_id"]);
+        query.bindValue(":xid_event", aPerson["event_id"]);
+        query.bindValue(":xid_person", aPerson["id"]);
+        query.exec(); // some queries fail due to the unique key constraint
+        // if (!query.exec()) qDebug() << "SQL query 'insert into event_person' failed: " << query.lastError();
     }
 }
 
@@ -252,21 +261,27 @@ void SqlEngine::addRoomToDB(QHash<QString,QString> &aRoom)
         else // ROOM record doesn't exist yet, need to create it
         {
             query = QSqlQuery(db);
-            query.prepare("INSERT INTO ROOM (xid_conference,name,picture) VALUES (:xid_conference, :name, :picture)");
+            query.prepare("INSERT INTO ROOM (xid_conference,name,picture) VALUES (:xid_conference, :name, '')");
             query.bindValue(":xid_conference", aRoom["conference_id"]);
             query.bindValue(":xid_name", aRoom["name"]);
-            query.bindValue(":xid_picture", aRoom["picture"]);
             if (!query.exec()) qDebug() << "Could not execute 'insert into room ...' query." << query.lastError();
             aRoom["id"]= query.lastInsertId().toString(); // 'id' is assigned automatically
             //LOG_AUTOTEST(query);
         }
+        
+        // remove previous conference/room records; room names might have changed
+        query = QSqlQuery(db);
+        query.prepare("DELETE FROM EVENT_ROOM WHERE xid_conference=:conference_id AND xid_event=:event_id");
+        query.bindValue(":conference_id", aRoom["conference_id"]);
+        query.bindValue(":event_id", aRoom["event_id"]);
+        if (!query.exec()) qDebug() << "Could not execute SELECT * FROM EVENT_ROOM' query:" << query.lastError();
+        // and insert new ones
         query = QSqlQuery(db);
         query.prepare("INSERT INTO EVENT_ROOM (xid_conference,xid_event,xid_room) VALUES (:conference_id, :event_id, :room_id)");
         query.bindValue(":conference_id", aRoom["conference_id"]);
         query.bindValue(":event_id", aRoom["event_id"]);
         query.bindValue(":room_id", aRoom["id"]);
         if (!query.exec()) qDebug() << "Could not 'execute insert into event_room' query:" << query.lastError();
-        //LOG_AUTOTEST(query);
     }
 }
 
@@ -284,7 +299,6 @@ void SqlEngine::addLinkToDB(QHash<QString,QString> &aLink)
         query.bindValue(":name", aLink["name"]);
         query.bindValue(":url", aLink["url"]);
         if (!query.exec()) qDebug() << "Error executing 'insert into link' query: " << query.lastError();
-        //LOG_AUTOTEST(query);
     }
 }
 
@@ -303,30 +317,39 @@ int SqlEngine::searchEvent(int aConferenceId, const QHash<QString,QString> &aCol
     execQuery( db, "CREATE TEMP TABLE SEARCH_EVENT ( xid_conference INTEGER  NOT NULL, id INTEGER NOT NULL )");
     // INSERT
     QString sql = QString("INSERT INTO SEARCH_EVENT ( xid_conference, id ) "
-                "SELECT EVENT.xid_conference, EVENT.id FROM EVENT ");
+                "SELECT DISTINCT EVENT.xid_conference, EVENT.id FROM EVENT ");
     if( aColumns.contains("ROOM") ){
-        sql += "INNER JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
-        sql += "INNER JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
+        sql += "LEFT JOIN EVENT_ROOM ON ( EVENT.xid_conference = EVENT_ROOM.xid_conference AND EVENT.id = EVENT_ROOM.xid_event ) ";
+        sql += "LEFT JOIN ROOM ON ( EVENT_ROOM.xid_room = ROOM.id ) ";
     }
     if( aColumns.contains("PERSON") ){
-        sql += "INNER JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
-        sql += "INNER JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
+        sql += "LEFT JOIN EVENT_PERSON ON ( EVENT.xid_conference = EVENT_PERSON.xid_conference AND EVENT.id = EVENT_PERSON.xid_event ) ";
+        sql += "LEFT JOIN PERSON ON ( EVENT_PERSON.xid_person = PERSON.id ) ";
     }
     sql += QString("WHERE EVENT.xid_conference = %1 AND (").arg( aConferenceId );
 
-    foreach (QString table, aColumns.uniqueKeys()){
-        foreach (QString column, aColumns.values(table)){
-            sql += QString("%1.%2 LIKE '\%' || :%1%2 || '\%' OR ").arg( table, column );
+    QStringList searchKeywords = aKeyword.trimmed().split(QRegExp("\\s+"));
+    QStringList whereAnd;
+    for (int i=0; i < searchKeywords.count(); i++) {
+        QStringList whereOr;
+        foreach (QString table, aColumns.uniqueKeys()) {
+            foreach (QString column, aColumns.values(table)){
+                 whereOr.append(QString("%1.%2 LIKE '\%' || :%1%2%3 || '\%'").arg(table).arg(column).arg(i));
+            }
         }
+        whereAnd.append(whereOr.join(" OR "));
     }
-    sql.chop( QString(" OR ").length() );
+    sql += whereAnd.join(") AND (");
     sql += QString(")");
 
     QSqlQuery query(db);
     query.prepare(sql);
-    foreach (QString table, aColumns.uniqueKeys()){
-        foreach (QString column, aColumns.values(table)){
-            query.bindValue(QString(":%1%2").arg(table, column), aKeyword );
+    for (int i = 0; i != searchKeywords.size(); ++i) {
+        QString keyword = searchKeywords[i];
+        foreach (QString table, aColumns.uniqueKeys()) {
+            foreach (QString column, aColumns.values(table)) {
+                query.bindValue(QString(":%1%2%3").arg(table).arg(column).arg(i), keyword );
+            }
         }
     }
 
@@ -378,23 +401,16 @@ void SqlEngine::deleteConference(int id)
 
 bool SqlEngine::execQuery(QSqlDatabase &aDatabase, const QString &aQuery)
 {
-    //qDebug() << "\nSQL: " << aQuery;
-
     QSqlQuery sqlQuery(aDatabase);
     if( !sqlQuery.exec(aQuery) ){
        qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
        return false;
     }
-    else{
-       //qDebug() << "SQL OK.\n";
-       return true;
-    }
+    return true;
 }
 
 bool SqlEngine::execQueryWithParameter(QSqlDatabase &aDatabase, const QString &aQuery, const QHash<QString, QVariant>& params)
 {
-    qDebug() << "SQL:" << aQuery << "params:" << params;
-
     QSqlQuery sqlQuery(aDatabase);
     sqlQuery.prepare(aQuery);
     foreach (QString param_key, params.keys()) {
@@ -404,19 +420,5 @@ bool SqlEngine::execQueryWithParameter(QSqlDatabase &aDatabase, const QString &a
        qDebug() << "SQL ERR: " << sqlQuery.lastError().number() << ", " << sqlQuery.lastError().text();
        return false;
     }
-    else{
-       //qDebug() << "SQL OK.\n";
-       return true;
-    }
-}
-
-void SqlEngine::checkConferenceMap(QSqlDatabase &aDatabase)
-{
-    QSqlQuery sqlQuery(aDatabase);
-    sqlQuery.prepare("SELECT map FROM conference");
-    if (!sqlQuery.exec()) {
-        qWarning() << "column conference.map is missing; adding";
-        execQuery(aDatabase, "ALTER TABLE conference ADD COLUMN map VARCHAR")
-         and execQuery(aDatabase, "UPDATE conference SET map = ':/maps/campus.png' WHERE title = 'FOSDEM 2010'");
-    }
+    return true;
 }