First commit
[jenirok] / src / common / db.cpp
1 /*
2  * This file is part of Jenirok.
3  *
4  * Jenirok is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * Jenirok is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with Jenirok.  If not, see <http://www.gnu.org/licenses/>.
16  *
17  */
18
19 #include <QtCore/QDir>
20 #include <QtSql/QSqlQuery>
21 #include <QtSql/QSqlError>
22 #include "db.h"
23 #include <QDebug>
24
25 namespace
26 {
27         const QString SQL_DRIVER = "QSQLITE";
28         const QString SQL_DATABASE = ".jenirok.db";
29 }
30
31 bool DB::initialized_ = false;
32 QSqlDatabase DB::db_;
33
34 bool DB::connect()
35 {
36         if(!initialized_)
37         {
38                 db_ = QSqlDatabase::addDatabase(SQL_DRIVER);
39                 QString path = QDir::home().path() + QDir::separator() + SQL_DATABASE;
40                 db_.setDatabaseName(QDir::toNativeSeparators(path));
41         }
42
43         bool ret = db_.open();
44
45         if(!ret)
46         {
47                 QSqlError error = db_.lastError();
48                 qDebug() << error.text();
49         }
50
51         if(ret && !initialized_)
52         {
53                 QSqlQuery query("SELECT value FROM settings WHERE name = 'initialized'");
54
55                 if(!query.next())
56                 {
57                         ret = createTables();
58                 }
59         }
60
61         if(!initialized_)
62         {
63                 initialized_ = true;
64         }
65
66         return ret;
67 }
68
69 void DB::disconnect()
70 {
71         db_.close();
72 }
73
74 void DB::removeDatabase()
75 {
76         db_.close();
77         db_ = QSqlDatabase();
78         QSqlDatabase::removeDatabase(QSqlDatabase::defaultConnection);
79         initialized_ = false;
80 }
81
82 bool DB::connected()
83 {
84         return db_.isOpen();
85 }
86
87 QSqlDatabase& DB::instance()
88 {
89         return db_;
90 }
91
92 bool DB::createTables()
93 {
94         QSqlQuery query;
95
96         bool ret = true;
97
98         ret = ret && query.exec("CREATE TABLE 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)");
99         ret = ret && query.exec("CREATE TABLE settings (name VARCHAR(255) NOT NULL PRIMARY KEY, value VARCHAR(255) NOT NULL)");
100         ret = ret && query.exec("INSERT INTO settings(name, value) VALUES('initialized', '1')");
101
102         return ret;
103 }