-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathappdatabase.cpp
More file actions
70 lines (63 loc) · 2.46 KB
/
appdatabase.cpp
File metadata and controls
70 lines (63 loc) · 2.46 KB
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
32
33
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
#include "appdatabase.h"
void AppDatabase::createIfNotExist()
{
QSqlQuery query;
if (!query.exec("CREATE TABLE IF NOT EXISTS messages ( \
id INTEGER NOT NULL, \
senderName TEXT, \
text TEXT, \
time INTEGER, \
channelNumber INTEGER, \
PRIMARY KEY(id AUTOINCREMENT) \
);")) {
qDebug() << query.lastError().text();
throw std::runtime_error("Can't create table \"messages\": "+query.lastError().text().toStdString());
}
// if (!query.exec("CREATE TABLE \"pairs\" ( \
// \"key\" TEXT NOT NULL UNIQUE, \
// \"value\" TEXT \
// );")) {
// qDebug() << query.lastError().text();
// throw std::runtime_error("Can't create table \"pairs\": "+query.lastError().text().toStdString());
// }
// insertIfNotExist("pairs", {"key", "name"}, {{"value", QHostInfo::localHostName().first(8)}});
}
void AppDatabase::insertIfNotExist(QString table, QPair<QString, QVariant> key, QMap<QString, QVariant> columnValues)
{
QString columnNames = columnValues.keys().join(',');
QString columnVars = ':'+columnValues.keys().join(",:");
QSqlQuery query;
query.prepare("IF NOT EXISTS (SELECT * FROM pairs \
WHERE "+key.first+" = :key) \
BEGIN \
INSERT INTO pairs ("+columnNames+") \
VALUES ("+columnVars+") \
END");
query.bindValue(":key", key.second);
for (auto key : columnValues.keys()) {
query.bindValue(':'+key, columnValues[key]);
}
if (!query.exec()) {
qDebug() << query.lastError().text();
throw std::runtime_error("Can't insert into table \"\": "+query.lastError().text().toStdString());
}
db.commit();
}
AppDatabase::AppDatabase(QObject *parent)
: QObject{parent}
, db(QSqlDatabase::addDatabase("QSQLITE"))
{
QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
if (!QDir().mkpath(path))
{
qDebug() << "Can't create application files directory";
QCoreApplication::quit();
}
qDebug() << path;
db.setDatabaseName(path+"/application_db.db");
if (!db.open()) {
qDebug() << db.lastError().text();
throw std::runtime_error("Can't open SQLite database: "+db.lastError().text().toStdString());
}
createIfNotExist();
}