e91eddaf32859f7d788ae233a40373513c1bf19b
[emufront] / src / db / dbmediaimagecontainer.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 copy of the GNU General Public License
18 // along with EmuFront.  If not, see <http://www.gnu.org/licenses/>.
19
20 #include <QDebug>
21 #include <QSqlRecord>
22 #include <QSqlQuery>
23 #include <QSqlRelationalTableModel>
24 #include <QSqlError>
25 #include "dbmediaimagecontainer.h"
26 #include "dbmediaimage.h"
27 //#include "dbsetup.h"
28 #include "dbfilepath.h"
29
30 DbMediaImageContainer::DbMediaImageContainer(QObject *parent)
31     : DbFile(parent)
32 {
33     dbMediaImage = new DbMediaImage(parent);
34     dbFilePath = new DbFilePath(parent);
35     tableName = DbMediaImageContainer::DB_TABLE_MEDIAIMAGECONTAINER;
36 }
37
38 bool DbMediaImageContainer::updateDataObjectToModel(const EmuFrontObject *efo)
39 {
40     // TODO
41     return false;
42 }
43
44
45 int DbMediaImageContainer::storeMediaImageContainer(EmuFrontObject *efo)
46 {
47     MediaImageContainer *mic
48         = dynamic_cast<MediaImageContainer *>(efo);
49
50     if (!mic->getFilePath())
51         throw new EmuFrontException("Cannot install media image "
52             "container to database without a file path object!");
53
54     // multiple media image containers with matching checksum will be stored
55     //       if each instance is in a different file path
56
57     int fileId = -1;
58     QMap<QString, EmuFrontObject*> images = mic->getMediaImages();
59     QList<int> ids = dbMediaImage->storeMediaImages(images);
60
61     //qDebug() << "Stored " << ids.count() << " media images.";
62
63     if (ids.count() <= 0)
64         return -1;
65
66     /* Contained Media images successfully stored to db,
67         storing media image container also */
68
69     try {
70
71         // Insert MediaImageContainer first as a EmuFrontFile object to file table.
72
73         // File id is used to store the media image container instance to database,
74         // file id is also the media image container id
75
76         fileId = insertDataObjectToModel(mic);
77
78         //qDebug() << "Inserted media image container to file table with id " << fileId << ".";
79
80         if (fileId < 0) {
81             // TODO: note we most surely need to catch the exception
82             // in the calling code block and clean
83             // all the media image and ...containers from
84             // the memory!
85             throw new EmuFrontException(
86                     QString(tr("Inserting media image container %1 to file database failed"))
87                     .arg(mic->getName()));
88         }
89
90         mic->setId(fileId);
91
92         if (!linkMediaImageContainerToPath(mic)){
93             DbFile::deleteDataObject(fileId);
94             throw new EmuFrontException("Failed inserting media image to database!");
95         }
96         //qDebug() << "Inserted media image container " << fileId << " to mediaimagecontainer table.";
97         linkMediaImagesWithContainer(fileId, images.values());
98         //qDebug() << "Linked media image container with media images.";
99     } catch (EmuFrontException e) {
100         dbMediaImage->removeOrphanedMediaImages(ids);
101         throw e;
102     }
103
104     return fileId;
105 }
106
107 bool DbMediaImageContainer::deleteDataObjectFromModel(QModelIndex *i)
108 {
109     // TODO
110     return false;
111 }
112
113 QString DbMediaImageContainer::constructSelect(QString whereClause) const
114 {
115     // TODO, for a usual search we need a "light" version of this select
116     // and MediaImageContainer (only id, name)
117     QString select = QString("SELECT file.id, file.name, file.checksum, file.size, "
118                 "        filepath.id, filepath.name, "
119                 "        setup.id, "
120                 "        platform.id, platform.name, "
121                 "        mediatype.id, mediatype.name "
122                 "FROM file "
123                 "INNER JOIN mediaimagecontainer_filepath ON mediaimagecontainer_filepath.fileid = file.id "
124                 "INNER JOIN filepath ON mediaimagecontainer_filepath.filepathid = filepath.id "
125                 "INNER JOIN setup ON filepath.setupid = setup.id "
126                 "INNER JOIN platform ON setup.platformid = platform.id "
127                 "INNER JOIN mediatype ON setup.mediatypeid = mediatype.id "
128                 "%1 "
129                 "ORDER BY file.name").arg(whereClause);
130     //qDebug() << select;
131     return select;
132 }
133
134 QString DbMediaImageContainer::constructFilterById(int id) const
135 {
136     return QString("file.id = %1").arg(id);
137 }
138
139 QString DbMediaImageContainer::constructSelectById(int id) const
140 {
141     return constructSelect(
142         QString("WHERE %1").arg(constructFilterById(id))
143         );
144 }
145
146 EmuFrontObject* DbMediaImageContainer::recordToDataObject(const QSqlRecord *rec)
147 {
148     // TODO: checks!
149     MediaImageContainer *mic = 0;
150     if (!rec) return mic;
151     int id = rec->value(MIC_FileId).toInt();
152     QString name = rec->value(MIC_FileName).toString();
153     QString checksum = rec->value(MIC_FileCheckSum).toString();
154     int size = rec->value(MIC_FileSize).toInt();
155     int fpId = rec->value(MIC_FilePathId).toInt();
156     FilePathObject *fpo
157         = dynamic_cast<FilePathObject*>(dbFilePath->getDataObject(fpId));
158     //int supId = rec->value(MIC_SetupId).toInt();
159     //Setup *sup = dbSetup->getDataObject(supId)
160     QMap<QString, EmuFrontObject*> images = dbMediaImage->getMediaImages(id);
161
162     mic = new MediaImageContainer(
163        id, name, checksum, size, images, fpo
164     );
165     return mic;
166 }
167
168 QSqlQueryModel* DbMediaImageContainer::getData()
169 {
170     QSqlQueryModel *model = new QSqlQueryModel(this);
171     if (sqlTableModel){
172         model->setQuery(sqlTableModel->query());
173     }
174     else
175         model->setQuery(constructSelect());
176     model->setHeaderData(MIC_FileId, Qt::Horizontal, tr("File id"));
177     model->setHeaderData(MIC_FileName, Qt::Horizontal, tr("File Name"));
178     model->setHeaderData(MIC_FileCheckSum, Qt::Horizontal, tr("File checksum"));
179     model->setHeaderData(MIC_FileSize, Qt::Horizontal, tr("File Size"));
180     model->setHeaderData(MIC_FilePathId, Qt::Horizontal, tr("File path id"));
181     model->setHeaderData(MIC_FilePathName, Qt::Horizontal, tr("File path name"));
182     model->setHeaderData(MIC_SetupId, Qt::Horizontal, tr("Setup id"));
183     model->setHeaderData(MIC_PlatformId, Qt::Horizontal, tr("Platform id"));
184     model->setHeaderData(MIC_PlatformName, Qt::Horizontal, tr("Platform name"));
185     model->setHeaderData(MIC_MediaTypeId, Qt::Horizontal, tr("Media type id"));
186     model->setHeaderData(MIC_MediaTypeName, Qt::Horizontal, tr("Media type name"));
187     return model;
188 }
189
190 /* Returns the id of a media image container with a given cheksum or -1 if not found */
191 int DbMediaImageContainer::getMediaImageContainer(QString checksum) const
192 {
193     QSqlQuery q;
194     q.prepare("SELECT id FROM file WHERE checksum=:checksum");
195     q.bindValue(":checksum", checksum);
196     int id = -1;
197     if (q.next())
198         id = q.value(0).toInt();
199     return id;
200 }
201
202
203 /**
204 * Stores media image containers, including the media images included
205 * to database.
206 */
207 void DbMediaImageContainer::storeContainers(QList<MediaImageContainer *> lst, FilePathObject *fpo)
208 {
209     foreach(MediaImageContainer *mic, lst)
210     {
211         //qDebug() << "Media image container " << mic->getName();
212         int micFileId = storeMediaImageContainer(mic);
213     }
214 }
215
216 void DbMediaImageContainer::linkMediaImagesWithContainer(int micId, QList<EmuFrontObject*> mediaImages)
217 {
218     if (micId < 0 || mediaImages.count() <= 0)
219         return;
220
221     MediaImage *mi = 0;
222     foreach(EmuFrontObject *efo, mediaImages) {
223         mi = dynamic_cast<MediaImage*>(efo);
224         /*qDebug() << "Linking media image container " << micId
225             << " to media image " << mi->getId()  << ", " << mi->getName() << ".";*/
226         if (!linkMediaImageToMediaImageContainer(mi, micId)) {
227                 throw new EmuFrontException(QString("Failed linking media "
228                                                     "image container %1 to a media image %2").arg(micId).arg(mi->getId()));
229         }
230     }
231 }
232
233 void DbMediaImageContainer::filter(int mediaTypeId, int platformId)
234 {
235     /*qDebug() << "Filtering media images with media type " << mediaTypeId
236         << " and platform " << platformId;*/
237     QList<QString> filters;
238     if (mediaTypeId >= 0)
239         filters.append(QString("mediatype.id=%1").arg(mediaTypeId));
240     if (platformId >= 0)
241         filters.append(QString("platform.id=%1").arg(platformId));
242     filterDataObjects(filters);
243 }
244
245 QString DbMediaImageContainer::getCountRefsSelect(int id) const
246 {
247     /* we need to count file references to give media image container */
248     /* example:
249         select count(*) from mediaimagecontainer
250         INNER JOIN mediaimagecontainer_mediaimage
251         ON mediaimagecontainer_mediaimage.mediaimagecontainerid
252         = mediaimagecontainer.fileid
253         WHERE mediaimagecontainer.fileid=589;
254     */
255     return QString("SELECT count(*) FROM mediaimagecontainer "
256               "INNER JOIN mediaimagecontainer_mediaimage "
257               "ON mediaimagecontainer_mediaimage.mediaimagecontainerid "
258               "    =mediaimagecontainer.fileid "
259               "WHERE mediaimagecontainer.fileid=%1").arg(id);
260 }
261
262 QString DbMediaImageContainer::getDeleteObjectSql() const
263 {
264        // The trigger will take care of deleting
265        // the reference from the mediaimagecontainer
266        // and mediaimage_mediaimagecontainer tables.
267        // there is also a trigger that will delete
268        // all the files linked to mediaimagecontainer
269        // using mediaimage_mediaimagecontainer (the actual
270        // mediaimages).
271        return QString("DELETE FROM file WHERE id=:id");
272 }
273
274 EmuFrontObject* DbMediaImageContainer::getMediaImageContainerByChecksum(QString checksum)
275 {
276     return getDataObject(QString("file.checksum LIKE '%1'").arg(checksum));
277 }
278
279 bool DbMediaImageContainer::linkMediaImageContainerToPath(const MediaImageContainer *mic) const
280 {
281     QSqlQuery q;
282     q.prepare("INSERT INTO mediaimagecontainer_filepath "
283               "(fileid, filepathid, updatetime) "
284               "VALUES (:fileid, :filepathid, :updatetime)");
285     q.bindValue(":fileid", mic->getId());
286     q.bindValue(":filepathid", mic->getFilePath()->getId());
287     q.bindValue(":updatetime", DatabaseManager::getCurrentTimeStamp());
288     return q.exec();
289 }
290
291 bool DbMediaImageContainer::linkMediaImageToMediaImageContainer(const MediaImage *mi, int micId) const
292 {
293     QSqlQuery q;
294     q.prepare("INSERT INTO mediaimagecontainer_mediaimage "
295         "(mediaimagecontainerid, mediaimageid) "
296         "VALUES (:micid, :miid) ");
297     q.bindValue(":micid", micId);
298     q.bindValue(":miid", mi->getId());
299     return q.exec();
300 }
301
302 bool DbMediaImageContainer::removeFromFilePath(int filePathId) const
303 {
304     QSqlQuery q;
305     q.prepare("DELETE FROM mediaimagecontainer_filepath "
306         "WHERE filepathid=:filepathid");
307     q.bindValue(":filepathid", filePathId);
308     return q.exec();
309 }