/*
* This file is part of Jenirok.
*
* Jenirok 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.
*
* Jenirok 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 Jenirok. If not, see .
*
*/
#include
#include
#include
#include
#include
#include "db.h"
namespace
{
const QString SQL_DRIVER = "QSQLITE";
const QString SQL_DATABASE = ".jenirok.db";
const int DB_VERSION = 2;
}
bool DB::initialized_ = false;
QSqlDatabase DB::db_;
bool DB::connect()
{
if(!initialized_)
{
db_ = QSqlDatabase::addDatabase(SQL_DRIVER);
QString path = QDir::home().path() + QDir::separator() + SQL_DATABASE;
db_.setDatabaseName(QDir::toNativeSeparators(path));
}
bool ret = db_.open();
if(!ret)
{
QSqlError error = db_.lastError();
qDebug() << error.text();
}
if(ret && !initialized_)
{
QSqlQuery query("SELECT value FROM settings WHERE name = 'db_version'");
if(query.next())
{
int currentVersion = query.value(0).toString().toInt();
if(currentVersion < DB_VERSION)
{
ret = createTables(true);
}
}
else
{
ret = createTables(false);
}
}
if(!initialized_)
{
initialized_ = true;
}
return ret;
}
void DB::disconnect()
{
db_.close();
}
void DB::removeDatabase()
{
if(!initialized_)
{
return;
}
db_.close();
db_ = QSqlDatabase();
QSqlDatabase::removeDatabase(QSqlDatabase::defaultConnection);
initialized_ = false;
}
bool DB::connected()
{
return db_.isOpen();
}
QSqlDatabase& DB::instance()
{
return db_;
}
bool DB::createTables(bool update)
{
QSqlQuery query;
bool ret = true;
ret = ret && query.exec("CREATE TABLE IF NOT EXISTS cache (id INTEGER PRIMARY KEY, number VARCHAR(32) NOT NULL UNIQUE, name VARCHAR(255) NOT NULL, street VARCHAR(255) NOT NULL, city VARCHAR(255) NOT NULL)");
ret = ret && query.exec("CREATE TABLE IF NOT EXISTS settings (name VARCHAR(255) NOT NULL PRIMARY KEY, value VARCHAR(255) NOT NULL)");
ret = ret && query.exec("CREATE TABLE IF NOT EXISTS log (id INTEGER PRIMARY KEY, number VARCHAR(32) NOT NULL, name VARCHAR(255), street VARCHAR(255), city VARCHAR(255), country VARCHAR(255), time INTEGER NOT NULL, missed INTEGER NOT NULL)");
if(update)
{
ret = ret && query.exec("UPDATE settings SET value = '" + QString::number(DB_VERSION) + "' WHERE name = 'db_version'");
}
else
{
ret = ret && query.exec("INSERT INTO settings(name, value) VALUES('db_version', '" + QString::number(DB_VERSION) + "')");
}
return ret;
}