Sharing a Datatase in an App Group Container

This commit is contained in:
Gwendal Roué committed 2019-12-12 19:23:41 +01:00
1 parent 0529869617
commit 34eff46e56
3 files changed
+249 -20

No files matched your search

+2
View File
@@ -83,6 +83,8 @@ let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
The new [Interrupt a Database](README.md#interrupt-a-database) chapter documents the new `interrupt()` method.
The new [Sharing a Datatase in an App Group Container](Documentation/AppGroupContainers.md) guide explains how to setup GRDB when you share a database in an iOS App Group container.
### API Diff
+239
View File
@@ -0,0 +1,239 @@
Sharing a Datatase in an App Group Container
============================================
On iOS, you can share database files between multiple processes by storing them in an [App Group Container](https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati).
A shared database is accessed from several SQLite connections, from several processes. This creates challenges at various levels:
1. **Database setup** may be attempted by multiple processes, concurrently.
2. **SQLite** may throw `SQLITE_BUSY` errors, code 5, "database is locked".
3. **iOS** may kill your application with a `0xDEAD10CC` exception.
4. **GRDB** database observation misses changes performed by external processes.
We'll address all of those challenges below.
- [Use a Database Pool]
- [How to limit the `SQLITE_BUSY` error]
- [How to limit the `0xDEAD10CC` exception]
- [How to perform cross-process database observation]
## Use a Database Pool
In order to access a shared database, use a [Database Pool]. It opens the database in the [WAL mode](https://www.sqlite.org/wal.html), which helps sharing a database.
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
- In a process that can create and write in the database, use this sample code:
```swift
/// Returns an initialized database pool at the shared location databaseURL
func openSharedDatabase(at databaseURL: URL) throws -> DatabasePool {
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var dbPool: DatabasePool?
var dbError: Error?
coordinator.coordinate(writingItemAt: databaseURL, options: .forMerging, error: &coordinatorError, byAccessor: { url in
do {
dbPool = try openDatabase(at: url)
} catch {
dbError = error
}
})
if let error = dbError ?? coordinatorError {
throw error
}
return dbPool!
}
private func openDatabase(at databaseURL: URL) throws -> DatabasePool {
let dbPool = try DatabasePool(path: databaseURL.path)
// Perform here other database setups, such as defining
// the database schema with a DatabaseMigrator.
return dbPool
}
```
- In a process that only reads in the database, use this sample code:
```swift
/// Returns an initialized database pool at the shared location databaseURL,
/// or nil if the database was not created yet.
func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var dbPool: DatabasePool?
var dbError: Error?
coordinator.coordinate(readingItemAt: databaseURL, options: .withoutChanges, error: &coordinatorError, byAccessor: { url in
do {
dbPool = try openReadOnlyDatabase(at: url)
} catch {
dbError = error
}
})
if let error = dbError ?? coordinatorError {
throw error
}
return dbPool
}
private func openReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
do {
var configuration = Configuration()
configuration.readonly = true
return try DatabasePool(path: databaseURL.path, configuration: configuration)
} catch {
if FileManager.default.fileExists(atPath: databaseURL.path) {
throw error
} else {
return nil
}
}
}
```
## 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.
See https://www.sqlite.org/rescode.html#busy for more information about this error.
If several processes want to write in the database, configure the database pool of each process that wants to write:
```swift
var configuration = Configuration()
configuration.busyMode = .timeout(/* a TimeInterval */)
configuration.defaultTransactionKind = .immediate
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
With such a setup, you may still get `SQLITE_BUSY` (5, "database is locked") errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout.
```swift
do {
try dbPool.write { db in ... }
} catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY {
// Another process won't let you write. Deal with it.
}
```
> :bulb: **Tip**: In order to be nice to other processes, measure the duration of your longest writes, and attempt at optimizing the ones that last for too long.
## How to limit the `0xDEAD10CC` exception
> The exception code 0xDEAD10CC indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension.
See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for more information about this exception.
1. If you use SQLCipher, use SQLCipher 4+, and call the `cipher_plaintext_header_size` pragma from your database preparation function:
```swift
var configuration = Configuration()
configuration.prepareDatabase = { (db: Database) in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA cipher_plaintext_header_size = 32")
}
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
This will avoid https://github.com/sqlcipher/sqlcipher/issues/255.
2. In each process that wants to write in the database:
Set the `observesSuspensionNotifications` configuration flag:
```swift
var configuration = Configuration()
configuration.suspendsOnBackgroundTimeExpiration = true
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
Post `Database.suspendNotification` when the application is about to be [suspended](https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle). You can for example post this notification from `UIApplicationDelegate.applicationDidEnterBackground(_:)`, or in the expiration handler of a [background task](https://forums.developer.apple.com/thread/85066).
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationDidEnterBackground(_ application: UIApplication) {
// Suspend databases
NotificationCenter.default.post(name: Database.suspendNotification, object: self)
}
}
```
Post `Database.resumeNotification` from `UIApplicationDelegate.applicationWillEnterForeground(_:)` (or `SceneDelegate.sceneWillEnterForeground(_:)` for scene-based applications):
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationWillEnterForeground(_ application: UIApplication) {
// Resume databases
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
}
}
```
If the application uses the background modes supported by iOS, post `Database.resumeNotification` method from each and every background mode callback that may use the database. For example, if your application supports background fetches:
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// Resume databases
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
// Proceed with background fetch
...
}
}
```
Suspended databases greatly reduce the odds of `0xDEAD10CC` exception are greatly reduced. If you see one in your crash logs, please open an issue!
In exchange, you will get `SQLITE_INTERRUPT` (9) or `SQLITE_ABORT` (4) errors, with messages "Database is suspended", "Transaction was aborted", or "interrupted", for any attempt at writing in the database when it is suspended.
You can catch those errors:
```swift
do {
try dbPool.write { db in ... }
} catch let error as DatabaseError where error.isInterruptionError {
// Oops, the database is suspended.
// Maybe try again after database is resumed?
}
```
## How to perform cross-process database observation
GRDB [Database Observation] features, as well as [GRDBCombine] and [RxGRDB], are not able to notify database changes performed by other processes.
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
You can trigger those notifications automatically with [DatabaseRegionObservation]:
```swift
// Notify all changes made to the "player" and "team" database tables
let observation = DatabaseRegionObservation(tracking: Player.all(), Team.all())
let observer = try observation.start(in: dbPool) { (db: Database) in
// Notify other processes
}
// Notify all changes made to the databsae
let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase)
let observer = try observation.start(in: dbPool) { (db: Database) in
// Notify other processes
}
```
[Use a Database Pool]: #use-a-database-pool
[How to limit the `SQLITE_BUSY` error]: #how-to-limit-the-sqlite_busy-error
[How to limit the `0xDEAD10CC` exception]: #how-to-limit-the-0xdead10cc-exception
[How to perform cross-process database observation]: #how-to-perform-cross-process-database-observation
[Database Pool]: ../README.md#database-pools
[Database Observation]: ../README.md#database-changes-observation
[GRDBCombine]: http://github.com/groue/GRDBCombine
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
+8 -20
View File
@@ -289,6 +289,7 @@ Documentation
- [Encryption](#encryption): Encrypt your database with SQLCipher.
- [Backup](#backup): Dump the content of a database to another.
- [Interrupt a Database](#interrupt-a-database): Abort any pending database operation.
- [App Group Containers]
#### Good to Know
@@ -7140,7 +7141,7 @@ You can catch those errors and wait for [UIApplicationDelegate.applicationProtec
- [DatabaseWriter and DatabaseReader Protocols](#databasewriter-and-databasereader-protocols)
- [Asynchronous APIs](#asynchronous-apis)
- [Unsafe Concurrency APIs](#unsafe-concurrency-apis)
- [Dealing with External Connections](#dealing-with-external-connections)
- [App Group Containers]
### Guarantees and Rules
@@ -7181,7 +7182,7 @@ Those guarantees hold as long as you follow three rules:
See the [Demo Application] for a sample app that sets up a single database queue that is available throughout the application.
If there are several instances of database queues or pools that write in the same database, a multi-threaded application will eventually face "database is locked" errors. See [Dealing with External Connections](#dealing-with-external-connections).
See [App Group Containers] for the specific setup required by applications that share their database files.
```swift
// SAFE CONCURRENCY
@@ -7683,24 +7684,6 @@ try writer.asyncWriteWithoutTransaction { db in
There is a single valid use case for reentrant methods, which is when you are unable to control database access scheduling.
### Dealing with External Connections
The first rule of GRDB is:
- **[Rule 1](#guarantees-and-rules)**: Have a unique instance of DatabaseQueue or DatabasePool connected to any database file.
This means that dealing with external connections is not a focus of GRDB. [Guarantees](#guarantees-and-rules) of GRDB may or may not hold as soon as some external connection modifies a database.
If you absolutely need multiple connections, then:
- Reconsider your position
- Read about [isolation in SQLite](https://www.sqlite.org/isolation.html)
- Learn about [locks and transactions](https://www.sqlite.org/lang_transaction.html)
- Become a master of the [WAL mode](https://www.sqlite.org/wal.html)
- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/4.6/Structs/Configuration.html)
- [Ask questions](https://github.com/groue/GRDB.swift/issues)
## Performance
GRDB is a reasonably fast library, and can deliver quite efficient SQLite access. See [Comparing the Performances of Swift SQLite libraries](https://github.com/groue/GRDB.swift/wiki/Performance) for an overview.
@@ -8186,6 +8169,10 @@ This chapter has [moved](Documentation/FullTextSearch.md).
This chapter has [moved](Documentation/FullTextSearch.md#enabling-fts5-support).
#### Dealing with External Connections
This chapter has been superseded by [App Group Containers].
[Associations]: Documentation/AssociationsBasics.md
[Beyond FetchableRecord]: #beyond-fetchablerecord
[Codable Records]: #codable-records
@@ -8215,3 +8202,4 @@ This chapter has [moved](Documentation/FullTextSearch.md#enabling-fts5-support).
[custom SQLite build]: Documentation/CustomSQLiteBuilds.md
[Combine]: https://developer.apple.com/documentation/combine
[Demo Application]: Documentation/DemoApps/GRDBDemoiOS/README.md
[App Group Containers]: Documentation/AppGroupContainers.md