Imported more functionality from old db classes to new models.
[emufront] / src / models / filemodel.cpp
1 /*
2 ** EmuFront
3 ** Copyright 2010 Mikko Keinänen
4 **
5 ** This file is part of EmuFront.
6 **
7 **
8 ** EmuFront is free software: you can redistribute it and/or modify
9 ** it under the terms of the GNU General Public License version 2 as published by
10 ** the Free Software Foundation and appearing in the file gpl.txt included in the
11 ** packaging of this file.
12 **
13 ** EmuFront is distributed in the hope that it will be useful,
14 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ** GNU General Public License for more details.
17 **
18 ** You should have received a copy of the GNU General Public License
19 ** along with EmuFront.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "emufrontfile.h"
23 #include "filemodel.h"
24 #include <QtSql>
25
26 FileModel::FileModel(QObject *parent) :
27     EmuFrontQueryModel(parent)
28 {
29 }
30
31 QString FileModel::constructSelect(QString where) const
32 {
33     return QString(
34             "SELECT file.id AS FileId, "
35             "file.name AS Name, "
36             "file.type AS FileType, "
37             "file.checksum AS Checksum, "
38             "file.size AS FileSize, "
39             "file.updatetime AS UpdateTime "
40             "FROM file "
41             "%1 "
42             "ORDER BY Name"
43         ).arg(where);
44 }
45
46 QString FileModel::constructFilterById(int id) const
47 {
48     return QString("file.id = %1").arg(id);
49 }
50
51 EmuFrontObject* FileModel::recordToDataObject(const QSqlRecord *record)
52 {
53     int id = record->value(File_Id).toInt();
54     QString name = record->value(File_Name).toString();
55     QString checksum = record->value(File_CheckSum).toString();
56     int size = record->value(File_FileSize).toInt();
57     int type = record->value(File_FileType).toInt();
58     return new EmuFrontFile(id, name, checksum, size, type);
59 }
60
61 /* Returns id of inserted data item after succesful insert, -1 if insert failed */
62 int FileModel::insertDataObject(const EmuFrontFile *fi)
63 {
64     QSqlQuery q;
65     q.prepare("INSERT INTO file "
66               "(id, name, type, checksum, size, updatetime) "
67               "VALUES (NULL, :name, :type, :checksum, :size, :updatetime)");
68     q.bindValue(":name", fi->getName());
69     q.bindValue(":type", fi->getType());
70     q.bindValue(":checksum", fi->getCheckSum());
71     q.bindValue(":size", fi->getSize());
72     q.bindValue(":updatetime", getCurrentTimeStamp());
73     int id = -1;
74     if (q.exec())
75         id = q.lastInsertId().toInt();
76     return id;
77 }
78
79 bool FileModel::deleteDataObject(int id) const
80 {
81     QSqlQuery q;
82     q.prepare(QString("DELETE FROM file WHERE id=:id"));
83     q.bindValue(":id", id);
84     return q.exec();
85 }
86