Document the "persistent WAL mode" and SQLITE_FCNTL_PERSIST_WAL

This commit is contained in:
Gwendal Roué committed 2020-05-06 18:24:06 +02:00
1 parent e4803c1e0c
commit b3b155459f
1 file changed
+29
+29
View File
@@ -104,6 +104,34 @@ Since several processes may open the database at the same time, protect the crea
```
#### The specific case of processes that lack write permission
If a process lacks the write permission, at the system level, on the shared database file, some extra setup is needed. This is the case, for example, of iOS keyboard extensions, or sandboxed macOS apps that lack some entitlements.
Such process is unable to open the database unless two extra files ending in `-shm` and `-wal` are present next to the database file ([source](https://www.sqlite.org/walformat.html#operations_that_require_locks_and_which_locks_those_operations_use)). Those files are regular companions of databases in the [WAL mode], but they are deleted, under regular operations, when database connections are closed. Precisely speaking, they *may* be deleted: it depends on the SQLite and the operating system versions ([source](https://github.com/groue/GRDB.swift/issues/739#issuecomment-604363998)).
As a consequence, make sure you activate the "persistent WAL mode", as explained below. This mode makes sure the `-shm` and `-wal` files are never deleted, and guarantees a database access to processes that lack the write permission.
The "persistent WAL mode" must be enabled on all writer connections, by setting the [SQLITE_FCNTL_PERSIST_WAL](https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal) flag. With GRDB, processes that can create and write in the database open the database as in this sample code:
```swift
var configuration = Configuration()
configuration.prepareDatabase = { db in
// Activate the persistent WAL mode for writer connections
if db.configuration.readonly == false {
var flag: CInt = 1
let code = withUnsafeMutablePointer(to: &flag) { flagP in
sqlite3_file_control(db.sqliteConnection, nil, SQLITE_FCNTL_PERSIST_WAL, flagP)
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: ResultCode(rawValue: code))
}
}
}
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
## How to limit the `SQLITE_BUSY` error
> The SQLITE_BUSY result code indicates that the database file could not be written (or in some cases read) because of concurrent activity by some other database connection, usually a database connection in a separate process.
@@ -248,3 +276,4 @@ let observer = try observation.start(in: dbPool) { (db: Database) in
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[WAL mode]: https://www.sqlite.org/wal.html