-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdatabase.cpp
50 lines (42 loc) · 1.16 KB
/
database.cpp
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
#include <QtGlobal>
#include <QDebug>
#include <QFileInfo>
#include <QDir>
#include <QSqlError>
#include "database.h"
#include "trace.h"
Database::Database(const QString &name, QObject *parent): QObject(parent), name_(name) {
}
Database::~Database() {
if (db_.isOpen()) {
db_.close();
}
if (db_.isValid()) {
QSqlDatabase::removeDatabase(db_.connectionName());
}
}
void Database::initialize() {
bool schemaRequired = false;
static int serial = 0;
QMutexLocker lock(&mutex_);
if (!db_.isValid()) {
QString connectionName = QString::number(serial++);
db_ = QSqlDatabase::addDatabase("QSQLITE", connectionName);
}
if (db_.isOpen()) {
return;
}
// Create database
if (!QFile::exists(name_)) {
schemaRequired = true;
QDir().mkpath(QFileInfo(name_).absolutePath());
}
db_.setDatabaseName(QDir::toNativeSeparators(name_));
if (!db_.open()) {
qCritical() << "Database::db: Could not open database:" << db_.lastError().text();
return;
}
if (schemaRequired) {
emit addSchema();
}
}