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