Setting up 0.1.6a bugfix release.
[emufront] / src / db / dbquerymodelmanager.cpp
1 // EmuFront
2 // Copyright 2010 Mikko Keinänen
3 //
4 // This file is part of EmuFront.
5 //
6 //
7 // EmuFront is free software: you can redistribute it and/or modify
8 // it under the terms of the GNU General Public License version 2 as published by
9 // the Free Software Foundation and appearing in the file gpl.txt included in the
10 // packaging of this file.
11 //
12 // EmuFront is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 // GNU General Public License for more details.
16 //
17 // You should have received a cyopy of the GNU General Public License
18 // along with EmuFront.  If not, see <http://www.gnu.org/licenses/>.
19
20 #include <QSqlQuery>
21 #include <QSqlQueryModel>
22 #include <QSqlError>
23 #include <QDebug>
24 #include "dbquerymodelmanager.h"
25
26 DbQueryModelManager::DbQueryModelManager(QObject *parent)
27     : DatabaseManager(parent)
28 {
29 }
30
31 void DbQueryModelManager::filterById(int id)
32 {
33     QList<QString> filters;
34     filters.append(constructFilterById(id));
35     filterDataObjects(filters);
36 }
37
38 /* filters is a list of SQL conditions e.g. setup.id=1 */
39 void DbQueryModelManager::filterDataObjects(QList<QString> filters)
40 {
41     //if (!sqlTableModel) sqlTableModel = getDataModel();
42     if (!sqlTableModel)
43         getDataModel();
44     QString where = constructWhereByFilters(filters);
45     //qDebug() << "Constructing SQL with " << where;
46     QString query = constructSelect(where);
47     sqlTableModel->setQuery(query);
48 }
49
50 QString DbQueryModelManager::constructWhereByFilters(QList<QString>filters)
51 {
52     if (filters.count() == 0) return "";
53     QString where = " WHERE ";
54     int c = 0;
55     foreach(QString filter, filters){
56         where.append(QString(" %1 ").arg(filter));
57         if (++c < filters.count())
58             where.append(" AND ");
59     }
60     //qDebug() << "constructWhereByFilters: " << where;
61     return where;
62 }
63
64 void DbQueryModelManager::clearFilters()
65 {
66     sqlTableModel->setQuery(constructSelect());
67 }
68
69 bool DbQueryModelManager::deleteDataObject(int id) const
70 {
71     QString sql = getDeleteObjectSql();
72     //qDebug() << sql;
73     QSqlQuery q;
74     q.prepare(sql);
75     q.bindValue(":id", id);
76     bool ret =  q.exec();
77     if (!ret) {
78            qDebug() << q.lastError().text();
79     }
80     return ret;
81 }
82
83 QString DbQueryModelManager::getDeleteObjectSql() const
84 {
85     return QString("DELETE FROM %1 WHERE id=:id").arg(tableName);
86 }
87