-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathConnectionState.cpp
More file actions
176 lines (147 loc) · 4.99 KB
/
ConnectionState.cpp
File metadata and controls
176 lines (147 loc) · 4.99 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#include "ConnectionState.h"
#include "fileUtils.h"
#include "sqlite3.h"
const std::string EMPTY_LOCK_ID = "";
SQLiteOPResult genericSqliteOpenDb(string const dbName, string const docPath,
sqlite3 **db, int sqlOpenFlags);
ConnectionState::ConnectionState(const std::string dbName,
const std::string docPath, int SQLFlags) {
auto result = genericSqliteOpenDb(dbName, docPath, &connection, SQLFlags);
if (result.type != SQLiteOk) {
throw std::runtime_error("Failed to open SQLite database: " + result.errorMessage);
}
thread = std::thread(&ConnectionState::doWork, this);
this->clearLock();
}
ConnectionState::~ConnectionState() {
if (!isClosed) {
close();
}
}
void ConnectionState::clearLock() {
waitFinished();
_currentLockId = EMPTY_LOCK_ID;
}
void ConnectionState::activateLock(const ConnectionLockId &lockId) {
_currentLockId = lockId;
}
bool ConnectionState::matchesLock(const ConnectionLockId &lockId) {
return _currentLockId == lockId;
}
bool ConnectionState::isEmptyLock() { return _currentLockId == EMPTY_LOCK_ID; }
std::future<void> ConnectionState::refreshSchema() {
auto promise = std::make_shared<std::promise<void>>();
auto future = promise->get_future();
queueWork([promise](sqlite3* db) {
try {
int rc = sqlite3_exec(db, "PRAGMA table_info('sqlite_master')", nullptr, nullptr, nullptr);
if (rc != SQLITE_OK) {
throw std::runtime_error("Failed to refresh schema");
}
promise->set_value();
} catch (...) {
promise->set_exception(std::current_exception());
}
});
return future;
}
void ConnectionState::close() {
{
std::unique_lock<std::mutex> g(workQueueMutex);
// prevent any new work from being queued
isClosed = true;
}
// Wait for the work queue to empty
waitFinished();
{
// Now signal the thread to stop and notify it
std::unique_lock<std::mutex> g(workQueueMutex);
threadDone = true;
workQueueConditionVariable.notify_all();
}
// Join the worker thread
if (thread.joinable()) {
thread.join();
}
// Safely close the SQLite connection
sqlite3_close_v2(connection);
}
void ConnectionState::queueWork(std::function<void(sqlite3 *)> task) {
{
std::unique_lock<std::mutex> g(workQueueMutex);
if (isClosed) {
throw std::runtime_error("Connection is not open. Connection has been closed before queueing work.");
}
workQueue.push(task);
}
workQueueConditionVariable.notify_all();
}
void ConnectionState::doWork() {
// Loop while the queue is not destructing
while (!threadDone) {
std::function<void(sqlite3 *)> task;
// Create a scope, so we don't lock the queue for longer than necessary
{
std::unique_lock<std::mutex> g(workQueueMutex);
workQueueConditionVariable.wait(g, [&] {
// Only wake up if there are elements in the queue or the program is
// shutting down
return !workQueue.empty() || threadDone;
});
// If we are shutting down exit without trying to process more work
if (threadDone) {
break;
}
task = workQueue.front();
workQueue.pop();
}
threadBusy = true;
task(connection);
threadBusy = false;
// Need to notify in order for waitFinished to be updated when
// the queue is empty and not busy
{
std::unique_lock<std::mutex> g(workQueueMutex);
workQueueConditionVariable.notify_all();
}
}
}
void ConnectionState::waitFinished() {
std::unique_lock<std::mutex> g(workQueueMutex);
workQueueConditionVariable.wait(
g, [&] { return workQueue.empty() && !threadBusy; });
}
SQLiteOPResult genericSqliteOpenDb(string const dbName, string const docPath,
sqlite3 **db, int sqlOpenFlags) {
string dbPath = get_db_path(dbName, docPath);
int exit = 0;
exit = sqlite3_open_v2(dbPath.c_str(), db, sqlOpenFlags, nullptr);
if (exit != SQLITE_OK) {
return SQLiteOPResult{.type = SQLiteError,
.errorMessage = sqlite3_errmsg(*db)};
}
// Set journal mode directly when opening.
// This may have some overhead on the main thread,
// but prevents race conditions with multiple connections.
if (sqlOpenFlags & SQLITE_OPEN_READONLY) {
exit = sqlite3_exec(*db, "PRAGMA busy_timeout = 30000;"
// Default to normal on all connections
"PRAGMA synchronous = NORMAL;",
nullptr, nullptr, nullptr
);
} else {
exit = sqlite3_exec(*db, "PRAGMA busy_timeout = 30000;"
"PRAGMA journal_mode = WAL;"
// 6Mb 1.5x default checkpoint size
"PRAGMA journal_size_limit = 6291456;"
// Default to normal on all connections
"PRAGMA synchronous = NORMAL;",
nullptr, nullptr, nullptr
);
}
if (exit != SQLITE_OK) {
return SQLiteOPResult{.type = SQLiteError,
.errorMessage = sqlite3_errmsg(*db)};
}
return SQLiteOPResult{.type = SQLiteOk, .rowsAffected = 0};
}