pureimagecache.cpp 12.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/**
******************************************************************************
*
* @file       pureimagecache.cpp
* @author     The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief      
* @see        The GNU Public License (GPL) Version 3
* @defgroup   OPMapWidget
* @{
* 
*****************************************************************************/
/* 
* This program 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 3 of the License, or 
* (at your option) any later version.
* 
* This program 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 this program; if not, write to the Free Software Foundation, Inc., 
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "pureimagecache.h"
#include <QDateTime>
#include <QSettings>
//#define DEBUG_PUREIMAGECACHE
namespace core {
32 33
    static QMutex addDatabaseMutex; // QSqlDatabase::addDatabase is not thread safe when loadingn plugins

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    qlonglong PureImageCache::ConnCounter=0;

    PureImageCache::PureImageCache()
    {

    }

    void PureImageCache::setGtileCache(const QString &value)
    {
        lock.lockForWrite();
        gtilecache=value;
        QDir d;
        if(!d.exists(gtilecache))
        {
            d.mkdir(gtilecache);
#ifdef DEBUG_PUREIMAGECACHE
            qDebug()<<"Create Cache directory";
#endif //DEBUG_PUREIMAGECACHE
        }
        {
            QString db=gtilecache+"Data.qmdb";
            if(!QFileInfo(db).exists())
            {
#ifdef DEBUG_PUREIMAGECACHE
                qDebug()<<"Try to create EmptyDB";
#endif //DEBUG_PUREIMAGECACHE
                CreateEmptyDB(db);
            }
        }
        lock.unlock();
    }
    QString PureImageCache::GtileCache()
    {
        return gtilecache;
    }


    bool PureImageCache::CreateEmptyDB(const QString &file)
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"Create database at!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!:"<<file;
#endif //DEBUG_PUREIMAGECACHE
        QFileInfo File(file);
        QDir dir=File.absoluteDir();
        QString path=dir.absolutePath();
        QString filename=File.fileName();
        if(File.exists())
            QFile(filename).remove();
        if(!dir.exists())
        {
#ifdef DEBUG_PUREIMAGECACHE
            qDebug()<<"CreateEmptyDB: Cache path doesn't exist, try to create";
#endif //DEBUG_PUREIMAGECACHE
            if(!dir.mkpath(path))
            {
#ifdef DEBUG_PUREIMAGECACHE
                qDebug()<<"CreateEmptyDB: Could not create path";
#endif //DEBUG_PUREIMAGECACHE
                return false;
            }
        }
95
        addDatabaseMutex.lock();
96
        QSqlDatabase db(QSqlDatabase::addDatabase("QSQLITE",QLatin1String("CreateConn")));
97
        addDatabaseMutex.unlock();
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        db.setDatabaseName(file);
        if (!db.open())
        {
#ifdef DEBUG_PUREIMAGECACHE
            qDebug()<<"CreateEmptyDB: Unable to create database";
#endif //DEBUG_PUREIMAGECACHE

            return false;
        }
        QSqlQuery query(db);
        query.exec("CREATE TABLE IF NOT EXISTS Tiles (id INTEGER NOT NULL PRIMARY KEY, X INTEGER NOT NULL, Y INTEGER NOT NULL, Zoom INTEGER NOT NULL, Type INTEGER NOT NULL,Date TEXT)");
        if(query.numRowsAffected()==-1)
        {
#ifdef DEBUG_PUREIMAGECACHE
            qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
            db.close();
            return false;
        }
        query.exec("CREATE TABLE IF NOT EXISTS TilesData (id INTEGER NOT NULL PRIMARY KEY CONSTRAINT fk_Tiles_id REFERENCES Tiles(id) ON DELETE CASCADE, Tile BLOB NULL)");
        if(query.numRowsAffected()==-1)
        {
#ifdef DEBUG_PUREIMAGECACHE
            qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
            db.close();
            return false;
        }
        query.exec(
                "CREATE TRIGGER fki_TilesData_id_Tiles_id "
                "BEFORE INSERT ON [TilesData] "
                "FOR EACH ROW BEGIN "
                "SELECT RAISE(ROLLBACK, 'insert on table TilesData violates foreign key constraint fki_TilesData_id_Tiles_id') "
                "WHERE (SELECT id FROM Tiles WHERE id = NEW.id) IS NULL; "
                "END");
        if(query.numRowsAffected()==-1)
        {
#ifdef DEBUG_PUREIMAGECACHE
            qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
            db.close();
            return false;
        }
        query.exec(
                "CREATE TRIGGER fku_TilesData_id_Tiles_id "
                "BEFORE UPDATE ON [TilesData] "
                "FOR EACH ROW BEGIN "
                "SELECT RAISE(ROLLBACK, 'update on table TilesData violates foreign key constraint fku_TilesData_id_Tiles_id') "
                "WHERE (SELECT id FROM Tiles WHERE id = NEW.id) IS NULL; "
                "END");
        if(query.numRowsAffected()==-1)
        {
#ifdef DEBUG_PUREIMAGECACHE
            qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
            db.close();
            return false;
        }
        query.exec(
                "CREATE TRIGGER fkdc_TilesData_id_Tiles_id "
                "BEFORE DELETE ON Tiles "
                "FOR EACH ROW BEGIN "
                "DELETE FROM TilesData WHERE TilesData.id = OLD.id; "
                "END");
        if(query.numRowsAffected()==-1)
        {
#ifdef DEBUG_PUREIMAGECACHE
            qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
            db.close();
            return false;
        }
        db.close();
        QSqlDatabase::removeDatabase(QLatin1String("CreateConn"));
        return true;
    }
    bool PureImageCache::PutImageToCache(const QByteArray &tile, const MapType::Types &type,const Point &pos,const int &zoom)
    {
        if(gtilecache.isEmpty()|gtilecache.isNull())
            return false;
        lock.lockForRead();
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"PutImageToCache Start:";//<<pos;
#endif //DEBUG_PUREIMAGECACHE
        Mcounter.lock();
        qlonglong id=++ConnCounter;
        Mcounter.unlock();
        {
186
            addDatabaseMutex.lock();
187
            QSqlDatabase cn(QSqlDatabase::addDatabase("QSQLITE",QString::number(id)));
188
            addDatabaseMutex.unlock();
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
            QString db=gtilecache+"Data.qmdb";
            cn.setDatabaseName(db);
            cn.setConnectOptions("QSQLITE_ENABLE_SHARED_CACHE");
            if(cn.open())
            {
                {
                    QSqlQuery query(cn);
                    query.prepare("INSERT INTO Tiles(X, Y, Zoom, Type,Date) VALUES(?, ?, ?, ?,?)");
                    query.addBindValue(pos.X());
                    query.addBindValue(pos.Y());
                    query.addBindValue(zoom);

                    query.addBindValue((int)type);
                    query.addBindValue(QDateTime::currentDateTime().toString());
                    query.exec();
                }
                {
                    QSqlQuery query(cn);
                    query.prepare("INSERT INTO TilesData(id, Tile) VALUES((SELECT last_insert_rowid()), ?)");
                    query.addBindValue(tile);
                    query.exec();
                }
                cn.close();
            }
        }
        QSqlDatabase::removeDatabase(QString::number(id));
        lock.unlock();
        return true;
    }
    QByteArray PureImageCache::GetImageFromCache(MapType::Types type, Point pos, int zoom)
    {
        lock.lockForRead();
        QByteArray ar;
        if(gtilecache.isEmpty()|gtilecache.isNull())
            return ar;
        QString dir=gtilecache;
        Mcounter.lock();
        qlonglong id=++ConnCounter;
        Mcounter.unlock();
#ifdef DEBUG_PUREIMAGECACHE
Don Gagne's avatar
Don Gagne committed
229
        qDebug()<<"Cache dir="<<dir<<" Try to GET:"<<pos.X()<<","<<pos.Y();
230 231 232
#endif //DEBUG_PUREIMAGECACHE

            QString db=dir+"Data.qmdb";
oberion's avatar
oberion committed
233
			{
234
                addDatabaseMutex.lock();
235
				QSqlDatabase cn(QSqlDatabase::addDatabase("QSQLITE",QString::number(id)));
236
                addDatabaseMutex.unlock();
237

oberion's avatar
oberion committed
238 239 240
	            cn.setDatabaseName(db);
		        cn.setConnectOptions("QSQLITE_ENABLE_SHARED_CACHE");
			    if(cn.open())
241
				{
oberion's avatar
oberion committed
242 243 244 245 246 247 248 249 250 251
					QSqlQuery query(cn);
					query.exec(QString("SELECT Tile FROM TilesData WHERE id = (SELECT id FROM Tiles WHERE X=%1 AND Y=%2 AND Zoom=%3 AND Type=%4)").arg(pos.X()).arg(pos.Y()).arg(zoom).arg((int) type));
					query.next();
					if(query.isValid())
					{
						ar=query.value(0).toByteArray();
					}
					cn.close();
				}
			}
252
			QSqlDatabase::removeDatabase(QString::number(id));
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
        lock.unlock();
        return ar;
    }
    void PureImageCache::deleteOlderTiles(int const& days)
    {
        if(gtilecache.isEmpty()|gtilecache.isNull())
            return;
        QList<long> add;
        bool ret=true;
        QString dir=gtilecache;
        {
            QString db=dir+"Data.qmdb";
            ret=QFileInfo(db).exists();
            if(ret)
            {
                Mcounter.lock();
                qlonglong id=++ConnCounter;
                Mcounter.unlock();
271
                addDatabaseMutex.lock();
272
                QSqlDatabase cn(QSqlDatabase::addDatabase("QSQLITE",QString::number(id)));
273
                addDatabaseMutex.unlock();
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
                cn.setDatabaseName(db);
                cn.setConnectOptions("QSQLITE_ENABLE_SHARED_CACHE");
                if(cn.open())
                {
                    {
                        QSqlQuery query(cn);
                        query.exec(QString("SELECT id, X, Y, Zoom, Type, Date FROM Tiles"));
                        while(query.next())
                        {
                            if(QDateTime::fromString(query.value(5).toString()).daysTo(QDateTime::currentDateTime())>days)
                                add.append(query.value(0).toLongLong());
                        }
                        foreach(long i,add)
                        {
                            query.exec(QString("DELETE FROM Tiles WHERE id = %1;").arg(i));
                        }
                    }

                    cn.close();
                }
                QSqlDatabase::removeDatabase(QString::number(id));
            }
        }
    }
    // PureImageCache::ExportMapDataToDB("C:/Users/Xapo/Documents/mapcontrol/debug/mapscache/data.qmdb","C:/Users/Xapo/Documents/mapcontrol/debug/mapscache/data2.qmdb");
    bool PureImageCache::ExportMapDataToDB(QString sourceFile, QString destFile)
    {
        bool ret=true;
        QList<long> add;
        if(!QFileInfo(destFile).exists())
        {
#ifdef DEBUG_PUREIMAGECACHE
            qDebug()<<"Try to create EmptyDB";
#endif //DEBUG_PUREIMAGECACHE
            ret=CreateEmptyDB(destFile);
        }
        if(!ret) return false;
311
        addDatabaseMutex.lock();
312
        QSqlDatabase ca(QSqlDatabase::addDatabase("QSQLITE","ca"));
313
        addDatabaseMutex.unlock();
314 315 316 317
        ca.setDatabaseName(sourceFile);

        if(ca.open())
        {
318
            addDatabaseMutex.lock();
319
            QSqlDatabase cb(QSqlDatabase::addDatabase("QSQLITE","cb"));
320
            addDatabaseMutex.unlock();
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
            cb.setDatabaseName(destFile);
            if(cb.open())
            {
                QSqlQuery queryb(cb);
                queryb.exec(QString("ATTACH DATABASE \"%1\" AS Source").arg(sourceFile));
                QSqlQuery querya(ca);
                querya.exec("SELECT id, X, Y, Zoom, Type, Date FROM Tiles");
                while(querya.next())
                {
                    long id=querya.value(0).toLongLong();
                    queryb.exec(QString("SELECT id FROM Tiles WHERE X=%1 AND Y=%2 AND Zoom=%3 AND Type=%4;").arg(querya.value(1).toLongLong()).arg(querya.value(2).toLongLong()).arg(querya.value(3).toLongLong()).arg(querya.value(4).toLongLong()));
                    if(!queryb.next())
                    {
                        add.append(id);
                    }

                }
                long f;
                foreach(f,add)
                {
                    queryb.exec(QString("INSERT INTO Tiles(X, Y, Zoom, Type, Date) SELECT X, Y, Zoom, Type, Date FROM Source.Tiles WHERE id=%1").arg(f));
                    queryb.exec(QString("INSERT INTO TilesData(id, Tile) Values((SELECT last_insert_rowid()), (SELECT Tile FROM Source.TilesData WHERE id=%1))").arg(f));
                }
                add.clear();
                ca.close();
                cb.close();

            }
            else return false;
        }
        else return false;
        QSqlDatabase::removeDatabase("ca");
        QSqlDatabase::removeDatabase("cb");
        return true;

    }

}