@@ -30,9 +30,7 @@ ConnectionState::~ConnectionState() {
3030}
3131
3232void ConnectionState::clearLock () {
33- if (!workQueue.empty ()) {
34- waitFinished ();
35- }
33+ waitFinished ();
3634 _currentLockId = EMPTY_LOCK_ID;
3735}
3836
@@ -47,9 +45,7 @@ bool ConnectionState::matchesLock(const ConnectionLockId &lockId) {
4745bool ConnectionState::isEmptyLock () { return _currentLockId == EMPTY_LOCK_ID; }
4846
4947void ConnectionState::close () {
50- if (!workQueue.empty ()) {
51- waitFinished ();
52- }
48+ waitFinished ();
5349 // So that the thread can stop (if not already)
5450 threadDone = true ;
5551 sqlite3_close_v2 (connection);
@@ -94,12 +90,18 @@ void ConnectionState::doWork() {
9490 --threadBusy;
9591 // Need to notify in order for waitFinished to be updated when
9692 // the queue is empty and not busy
97- workQueueConditionVariable.notify_all ();
93+ {
94+ std::unique_lock<std::mutex> g (workQueueMutex);
95+ workQueueConditionVariable.notify_all ();
96+ }
9897 }
9998}
10099
101100void ConnectionState::waitFinished () {
102101 std::unique_lock<std::mutex> g (workQueueMutex);
102+ if (workQueue.empty ()) {
103+ return ;
104+ }
103105 workQueueConditionVariable.wait (
104106 g, [&] { return workQueue.empty () && (threadBusy == 0 ); });
105107}
@@ -116,5 +118,29 @@ SQLiteOPResult genericSqliteOpenDb(string const dbName, string const docPath,
116118 .errorMessage = sqlite3_errmsg (*db)};
117119 }
118120
121+ // Set journal mode directly when opening.
122+ // This may have some overhead on the main thread,
123+ // but prevents race conditions with multiple connections.
124+ if (sqlOpenFlags & SQLITE_OPEN_READONLY) {
125+ exit = sqlite3_exec (*db, " PRAGMA busy_timeout = 30000;"
126+ // Default to normal on all connections
127+ " PRAGMA synchronous = NORMAL;" ,
128+ nullptr , nullptr , nullptr
129+ );
130+ } else {
131+ exit = sqlite3_exec (*db, " PRAGMA busy_timeout = 30000;"
132+ " PRAGMA journal_mode = WAL;"
133+ // 6Mb 1.5x default checkpoint size
134+ " PRAGMA journal_size_limit = 6291456;"
135+ // Default to normal on all connections
136+ " PRAGMA synchronous = NORMAL;" ,
137+ nullptr , nullptr , nullptr
138+ );
139+ }
140+ if (exit != SQLITE_OK) {
141+ return SQLiteOPResult{.type = SQLiteError,
142+ .errorMessage = sqlite3_errmsg (*db)};
143+ }
144+
119145 return SQLiteOPResult{.type = SQLiteOk, .rowsAffected = 0 };
120146}
0 commit comments