Heart 1.4.984.b4712811
Heart is base back end library for your c++ Qt projects.
Loading...
Searching...
No Matches
database.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2018-2027 QuasarApp.
3 * Distributed under the lgplv3 software license, see the accompanying
4 * Everyone is permitted to copy and distribute verbatim copies
5 * of this license document, but changing it is not allowed.
6*/
7
8#include "database.h"
9#include "sqldbwriter.h"
10#include "asyncsqldbwriter.h"
11
12#include <QCoreApplication>
13#include <deleteobject.h>
14#include <QSet>
15#include <itoken.h>
16#include <sqlitedbcache.h>
17#include <sqldb.h>
18#include "getsinglevalue.h"
19#include "setsinglevalue.h"
20#include <qaglobalutils.h>
21
22namespace QH {
23using namespace PKG;
24
25DataBase::DataBase(QObject *ptr): QObject(ptr) {
26 qRegisterMetaType<QSharedPointer<QH::PKG::DBObject>>();
27}
28
29bool DataBase::initSqlDb(QString DBparamsFile,
30 ISqlDB *cache,
31 SqlDBWriter *writer) {
32
33 initDefaultDbObjects(cache, writer);
34
35 QVariantMap params;
36 _db->setSQLSources(SQLSources());
37
38 if (DBparamsFile.isEmpty()) {
39 params = defaultDbParams();
40
41 if (!_db->init(params)) {
42 return false;
43 }
44
45 } else {
46
47 if (!_db->init(DBparamsFile)) {
48 return false;
49 }
50
51 }
52
53 if (!upgradeDataBase()) {
54 qCritical() << "Failed to upgrade database";
55 return false;
56 }
57
58 qDebug() << "Database loaded from: " << dbLocation();
59
60 connect(_db, &ISqlDB::sigItemChanged,
62 Qt::DirectConnection);
63
64 connect(_db, &ISqlDB::sigItemDeleted,
66 Qt::DirectConnection);
67
68 return true;
69}
70
72 return _db;
73}
74
76 if (!isSqlInited() && !initSqlDb()) {
77 return false;
78 }
79 return true;
80}
81
82bool DataBase::run(const QString &localNodeName) {
83
84 if (localNodeName.isEmpty())
85 return false;
86
88
89 if (!isSqlInited() && !initSqlDb()) {
90 return false;
91 }
92
93 return true;
94}
95
97
98 if (db()) {
99 auto writer = _db->writer();
100 _db->softDelete();
101 _db = nullptr;
102 delete writer;
103 }
104}
105
107 stop();
108}
109
111 SqlDBWriter *writer) {
112 if (!writer) {
113 writer = new AsyncSqlDBWriter();
114 }
115
116 if (!cache) {
117 cache = new SqlDB();
118 }
119
120 cache->setWriter(writer);
121 _db = cache;
122}
123
124
126 return true;
127}
128
129QStringList DataBase::SQLSources() const{
130 return {
132 };
133}
134
135QSet<QString> DataBase::systemTables() const {
136 return {"NetworkMembers", "MemberPermisions"};
137}
138
140
141}
142
143void DataBase::objectChanged(const QSharedPointer<DBObject> &) {
144
145}
146
148 return _dbPatches;
149}
150
151void DataBase::addDBPatch(const DBPatch &patch) {
152 debug_assert(patch.isValid(),
153 "Failed to initialise a Data base patch!"
154 " Patch object is invalid");
155
156
157 debug_assert(!_dbPatches[patch.versionFrom].contains(patch.versionTo),
158 "Failed to initialise a Data base patch!");
159
160 _dbPatches[patch.versionFrom][patch.versionTo] = patch;
161
162 _targetDBVersion = std::max(_targetDBVersion, patch.versionTo);
163}
164
165QString DataBase::dbLocation() const {
166 if (db() && db()->writer()) {
167 return db()->writer()->databaseLocation();
168 }
169
170 return "";
171}
172
173QString DataBase::backUp(int version) const {
174 auto&& params = defaultDbParams();
175
176 if (params.value(QH_DB_DRIVER) != "QSQLITE")
177 return {};
178
179 QString&& path = params.value(QH_DB_BACKUP_PATH).toString();
180 if (path.isEmpty()) {
181 return {};
182 }
183
184 auto file = path + "/DBv%0_" + QDateTime::currentDateTimeUtc().toString("hh:mm:ss_dd_MM_yyyy") + ".db";
185 file = file.arg(version);
186 if (db() && db()->writer() &&
187 QFile::exists(db()->writer()->databaseLocation())) {
188
189 QDir().mkpath(path);
190
191 if (!QFile::copy(db()->writer()->databaseLocation(), file)) {
192 return {};
193 }
194 }
195
196 return file;
197}
198
200 return _db;
201}
202
203bool DataBase::isForbiddenTable(const QString &table) {
204 return systemTables().contains(table);
205}
206
208 if (!db())
209 return false;
210
211 DBPatchMap patchesPack = dbPatches();
212 if (!patchesPack.size()) {
213 return true;
214 }
215
216 int currentVersion = 0;
217
218 bool fsupportUpgrade = db()->doQuery("SELECT COUNT(*) FROM DataBaseAttributes", {}, true);
219
220 if (!fsupportUpgrade) {
221
222 qCritical() << "The data base of application do not support soft upgrade. "
223 "Please remove database monyaly and restart application."
224 "You can disable upgrade functions for this override the upgradeDataBase method. ";
225 return false;
226 }
227
228 currentVersion = getDBAttribute("version", 0).toInt();
229
230 if (currentVersion < _targetDBVersion)
231 onBeforeDBUpgrade(currentVersion, _targetDBVersion);
232
233 while (currentVersion < _targetDBVersion) {
234
235 QString message;
236 message = "Upgrade data base from %0 to %1 versions. %2";
237 message = message.arg(currentVersion);
238
239 auto patches = patchesPack.value(currentVersion, {});
240
241 if (!patches.size()) {
242 qCritical() << "Failed to " + message.arg("Unknown", "Required patch not found!");
243 return false;
244 }
245
246 auto patch = patches.last();
247 message = message.arg(patch.versionTo);
248
249 qInfo() << message.arg("(Begin)");
250
251 if (!patch.action(db())) {
252 qCritical() << "Failed to " + message.arg("Patch finished with error code!");
253 return false;
254 }
255
256 currentVersion = patch.versionTo;
257 if (!setDBAttribute("version", currentVersion)) {
258 return false;
259 }
260 }
261
262 return true;
263}
264
265void DataBase::onBeforeDBUpgrade(int currentVersion, int ) const {
266 backUp(currentVersion);
267}
268
269const QString &DataBase::localNodeName() const {
270 return _localNodeName;
271}
272
273void DataBase::setLocalNodeName(const QString &newLocalNodeName) {
274 _localNodeName = newLocalNodeName;
275}
276
277QVariantMap DataBase::defaultDbParams() const {
278
279 return {
280 {QH_DB_DRIVER, "QSQLITE"},
281 {QH_DB_FILE_PATH, DEFAULT_DB_PATH + "/" + localNodeName() + "/" + QCoreApplication::applicationName() + "_" + DEFAULT_DB_NAME},
282 {QH_DB_BACKUP_PATH, DEFAULT_DB_PATH + "/" + localNodeName() + "/BackUp"}
283 };
284}
285
286QVariant DataBase::getDBAttribute(const QString& key, const QVariant& defaultVal) {
287 if (!_db)
288 return defaultVal;
289
290 PKG::GetSingleValue request({"DataBaseAttributes", key}, "value", "name");
291
292 if (auto&& response = _db->getObject(request)) {
293 if (!response->value().isNull())
294 return response->value();
295
296 }
297
298 return defaultVal;
299}
300
301bool DataBase::setDBAttribute(const QString& key, const QVariant& newValue) {
302 auto updateVersionRequest = QSharedPointer<PKG::SetSingleValue>::create(
303 DbAddress{"DataBaseAttributes", key},
304 "value", newValue, "name");
305
306 if (!_db->replaceObject(updateVersionRequest, true)) {
307
308 qCritical() << "Failed to update " << key << " attribute";
309 return false;
310 }
311
312 return true;
313}
314
315}
316
The AbstractNodeInfo class contains information about client or server connection and tcp socket of n...
void sigObjectChanged(const QSharedPointer< QH::PKG::DBObject > &obj)
sigItemChanged This signal emitted when database object is changed.
bool isSqlInited() const
isSqlInited This method return true if database initialized successful.
Definition database.cpp:71
void stop()
stop This method stop and diskonnect the database.
Definition database.cpp:96
virtual bool upgradeDataBase()
upgradeDataBase This method upgrade data base to actyaly database version.
Definition database.cpp:207
void setLocalNodeName(const QString &newLocalNodeName)
setLocalNodeName This method sets new local name of database file.
Definition database.cpp:273
DataBase(QObject *ptr=nullptr)
Definition database.cpp:25
bool run()
run This method start and initialize the data base connection.
Definition database.cpp:75
QVariant getDBAttribute(const QString &key, const QVariant &defaultVal)
getDBAttribute This method gets value from the default of QH DB table "DataBaseAttributes".
Definition database.cpp:286
virtual void initDefaultDbObjects(ISqlDB *cache, SqlDBWriter *writer)
initDefaultDbObjects This method create a default cache and database writer objects if the input poin...
Definition database.cpp:110
bool setDBAttribute(const QString &key, const QVariant &newValue)
setDBAttribute This method sets value for the default of QH DB table "DataBaseAttributes".
Definition database.cpp:301
virtual const DBPatchMap dbPatches() const
dbPatches This method should be return map with functions that upgrade production data base....
Definition database.cpp:147
virtual void onBeforeDBUpgrade(int currentVersion, int tergetVersion) const
onBeforeDBUpgrade This method will be invoked before upgrade database.
Definition database.cpp:265
virtual QVariantMap defaultDbParams() const
defaultDbParams This method return default database parameters for this node. Override this method fo...
Definition database.cpp:277
void sigObjectDeleted(const QH::DbAddress &obj)
sigItemDeleted This signal emitted when database object is deleted.
virtual QStringList SQLSources() const
SQLSources This method contains list of sqldatabase sources. This method will be invoked into initial...
Definition database.cpp:129
virtual bool welcomeAddress(AbstractNodeInfo *node)
welcomeAddress This method send to the node information about self. Override this method if you want ...
Definition database.cpp:125
const QString & localNodeName() const
localNodeName This method return local node name.
Definition database.cpp:269
virtual void objectRemoved(const DbAddress &address)
objectRemoved This method invoked when object with address removed from database. Oberride this metho...
Definition database.cpp:139
QString dbLocation() const
dbLocation This method return location of nodes or clients database.
Definition database.cpp:165
void addDBPatch(const DBPatch &patch)
addDBPatch This method add database patch to the data base object.
Definition database.cpp:151
virtual QSet< QString > systemTables() const
systemTables This method return the set of tables that forbidden for users. By default is NetworkMemb...
Definition database.cpp:135
ISqlDB * db() const
db This node return pointer to database object.
Definition database.cpp:199
virtual void objectChanged(const QSharedPointer< PKG::DBObject > &obj)
objectChanged This method invoked when object with address changed in database. Override this method ...
Definition database.cpp:143
QString backUp(int version) const
backUp This method make a backup of database.
Definition database.cpp:173
virtual bool initSqlDb(QString DBparamsFile="", ISqlDB *cache=nullptr, SqlDBWriter *writer=nullptr)
intSqlDb This method initialize database of this node or server.
Definition database.cpp:29
The DbAddress class use to work with database addresses. Database Address it is structure with 2 valu...
Definition dbaddress.h:24
The ISqlDB class it is db cache and bridge for DbWriters. Work Scheme of the database cache:
Definition isqldb.h:73
void setWriter(SqlDBWriter *writer)
setWriter This method set new writer for this cache.
Definition isqldb.cpp:154
SqlDBWriter * writer() const
writer This method return is database writer object. For more information about writer see the SqlDBW...
Definition isqldb.cpp:150
bool doQuery(const QString &query, const QVariantMap &bindValues, bool wait=false, QSqlQuery *result=nullptr) const override
doQuery This method execute a query in this database.
Definition isqldb.cpp:247
void sigItemChanged(const QSharedPointer< QH::PKG::DBObject > &obj)
sigItemChanged This signal emitted when database object is changed.
void sigItemDeleted(const QH::DbAddress &obj)
sigItemDeleted This signal emitted when database object is deleted.
The GetSingleValue class is intended for get a single value from database. The value is selected by p...
The SqlDBWriter class. This class write and read objects from database (hard level)....
Definition sqldbwriter.h:36
QString databaseLocation() const
databaseLocation This method return location of database. If it is sqlite then return path to db file...
#define DEFAULT_DB_PATH
Definition config.h:27
#define QH_DB_DRIVER
Definition config.h:32
#define DEFAULT_DB_NAME
Definition config.h:26
#define QH_DB_BACKUP_PATH
Definition config.h:39
#define DEFAULT_DB_INIT_FILE_PATH
Definition config.h:28
#define QH_DB_FILE_PATH
Definition config.h:33
The PKG namespace - this namespace contains all default packages of the Heart library....
Definition heart.h:211
The QH namespace - QuasarApp Heart namespace. This namespace contains all classes of the Heart librar...
Definition heart.cpp:13
QMap< unsigned short, QMap< unsigned short, DBPatch > > DBPatchMap
DBPatchMap This is 2 depch map of the DBPatch structure when the first key it is version (from) and s...
Definition dbpatch.h:50
DBPatch This is function that should be upgrade database.
Definition dbpatch.h:26
unsigned short versionFrom
Definition dbpatch.h:29
bool isValid() const
isValid This method check this object to valid.
Definition dbpatch.cpp:12
unsigned short versionTo
Definition dbpatch.h:33