Compare commits

..
30 Commits
Author SHA1 Message Date
Gwendal Roué ef07897ba4 CHANGELOG 2022-09-08 13:42:13 +02:00
Gwendal Roué dd7e7f39e8 v5.26.1 2022-09-08 13:30:56 +02:00
Gwendal Roué 8801adb21c Run CI on GRBD5 2022-09-08 12:26:29 +02:00
Gwendal Roué f721af86cd Fix #1276 2022-09-08 08:05:42 +02:00
Gwendal Roué 23f4254ae3 Merge branch 'development' 2022-07-09 18:28:22 +02:00
Gwendal Roué 2df6a17c1c v5.26.0 2022-07-09 18:27:57 +02:00
Gwendal Roué 5aeee0e429 CHANGELOG 2022-07-09 17:17:27 +02:00
Gwendal Roué 3a61a8a0e0 Merge pull request #1253 from george-signal/george-signal/optional-memory-management
Make memory management optional.
2022-07-09 17:14:11 +02:00
Gwendal Roué e0766449f1 Fix compilation error on iOS Xcode 13.3.1.app, macOS 12, Swift 5.6 2022-07-09 16:14:37 +02:00
Gwendal Roué c1e752132c Document why DatabasePool.releaseMemory() needs a barrier 2022-07-09 14:28:09 +02:00
Gwendal Roué 6ab90a03c4 Document releaseMemoryEventually and automaticMemoryManagement 2022-07-09 14:00:00 +02:00
Gwendal Roué 23fa42a3e4 Make Database.releaseMemory() public
This allows us to document how to release memory asynchronously with a DatabaseQueue (in the next commit)
2022-07-09 13:55:39 +02:00
Gwendal Roué 07eaeee123 automaticMemoryManagement tests check for actual connection closing 2022-07-09 13:39:39 +02:00
Gwendal Roué 0bfb4de02d Enhance DatabaseQueue automatic memory management
We have async methods, now: no need to use a global dispatch queue.
2022-07-09 13:39:11 +02:00
Gwendal Roué d72b7109ad DatabasePool automatic memory management no longer uses any reader barrier
This fixes the failing `testDatabasePoolDoesNotPreventConcurrentReadsOnPressureEvent` test
2022-07-09 13:39:11 +02:00
Gwendal Roué e1a63a4c05 Introduce DatabasePool.releaseMemoryEventually 2022-07-09 13:33:01 +02:00
Gwendal Roué caab403282 Failing test for concurrent read on memory warning 2022-07-09 13:31:15 +02:00
George Nachman bbe94a9607 Make memory management optional.
Memory management may not be desirable for all
users of GRDB. `DatabasePool.releaseMemory`
creates a barrier which may cause normally fast
readers to block for a long time. If this is not a
desirable tradeoff, the new
`automaticMemoryManagement` flag in
`Configuration` allows you to disable this feature
of GRDB.
2022-07-05 15:27:55 -07:00
Gwendal Roué 84bee1977e Merge pull request #1248 from groue/dev/WALSnapshot
Avoid double notification of the initial value for ValueObservation on DatabasePool
2022-06-30 20:35:52 +02:00
Gwendal Roué 0aa561e61c [skip-ci] CHANGELOG 2022-06-30 19:32:35 +02:00
Gwendal Roué b1b51c01f8 [skip-ci] Xcode drives me crazy 2022-06-30 19:32:24 +02:00
Gwendal Roué cc5196757d Fix for Xcode 12.4 2022-06-30 19:22:23 +02:00
Gwendal Roué 0e9766373d Merge pull request #1246 from sameer4/patch-1
Update AssociationsBasics.md
2022-06-30 10:43:50 +02:00
Sameer aacaa433c9 Update AssociationsBasics.md
Fixed a typo
2022-06-30 12:51:53 +05:00
Gwendal Roué 44ec3535c2 Documentation 2022-06-24 16:48:38 +02:00
Gwendal Roué 38c0d68db7 WALSnapshot
SQLITE_ENABLE_SNAPSHOT is available from Xcode 14 :-)
2022-06-24 16:48:38 +02:00
Gwendal Roué f3cc4add9f Merge pull request #1240 from danielinoa/patch-1
Fix inline documentation typo in Row
2022-06-12 14:47:16 +02:00
Daniel Inoa 432670e13a Fix documentation typo in Row 2022-06-12 05:14:28 -07:00
Gwendal Roué 3ba13b0af6 Merge pull request #1239 from groue/dependabot/github_actions/actions/checkout-3
Bump actions/checkout from 2 to 3
2022-06-12 08:32:19 +02:00
dependabot[bot] 1a6228e2c5 Bump actions/checkout from 2 to 3
Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-06-11 15:37:15 +00:00
21 changed files with 427 additions and 350 deletions

No files matched your search

+8 -7
View File
@@ -5,6 +5,7 @@ on:
branches:
- master
- development
- GRDB5
paths:
- 'GRDB/**'
- 'Tests/**'
@@ -57,7 +58,7 @@ jobs:
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
shell: "/bin/zsh {0}"
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_framework_GRDBOSX_maxSwift
iOS:
@@ -77,7 +78,7 @@ jobs:
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
shell: "/bin/zsh {0}"
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_framework_GRDBiOS_maxTarget_maxSwift
SPM:
@@ -93,7 +94,7 @@ jobs:
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
shell: "/bin/zsh {0}"
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_SPM test_install_SPM
SQLCipher3:
@@ -109,7 +110,7 @@ jobs:
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
shell: "/bin/zsh {0}"
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher3Encrypted
SQLCipher4:
@@ -129,7 +130,7 @@ jobs:
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
shell: "/bin/zsh {0}"
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher4Encrypted
CustomSQLite:
@@ -149,7 +150,7 @@ jobs:
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
shell: "/bin/zsh {0}"
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_framework_GRDBCustomSQLiteOSX
XCFramework:
@@ -165,7 +166,7 @@ jobs:
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
shell: "/bin/zsh {0}"
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_archive_GRDBOSX_xcframework
+15
View File
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 5.x Releases
- `5.26.x` Releases - [5.26.0](#5260) | [5.26.1](#5261)
- `5.25.x` Releases - [5.25.0](#5250)
- `5.24.x` Releases - [5.24.0](#5240) | [5.24.1](#5241)
- `5.23.x` Releases - [5.23.0](#5230)
@@ -92,6 +93,20 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 5.26.1
Released September 8, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.26.0...v5.26.1)
- **Fixed**: [#1276](https://github.com/groue/GRDB.swift/pull/1276) Fix build error with Xcode 14.0 RC (14A309)
## 5.26.0
Released July 9, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.25.0...v5.26.0)
- **New**: [#1248](https://github.com/groue/GRDB.swift/pull/1248) by [@groue](https://github.com/groue): Avoid double notification of the initial value for ValueObservation on DatabasePool
- **New**: [#1253](https://github.com/groue/GRDB.swift/pull/1253) by [@george-signal](https://github.com/george-signal): Make memory management optional
- **Fixed**: DatabasePool no longer prevents database reads when UIKit posts `UIApplication.didReceiveMemoryWarningNotification` (see [#1253](https://github.com/groue/GRDB.swift/pull/1253) for more information).
## 5.25.0
Released June 11, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.24.1...v5.25.0)
+1 -1
View File
@@ -1510,7 +1510,7 @@ let sortedAuthor = Book.author.order(Column("name"))
let request = Book.including(required: sortedAuthor)
```
When you sort both the base record on the associated record, the request is sorted on the base record first, and on the associated record next:
When you sort both the base record and the associated record, the request is sorted on the base record first, and on the associated record next:
```swift
// SELECT book.*, person.*
+2 -2
View File
@@ -304,7 +304,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.25/Structs/StatementArguments.html):
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -587,7 +587,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.25/Structs/StatementArguments.html):
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
+1 -1
View File
@@ -77,7 +77,7 @@ try dbQueue.read { db in
}
```
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.25/Structs/DatabaseMigrator.html) for more migrator methods.
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.26/Structs/DatabaseMigrator.html) for more migrator methods.
## The `eraseDatabaseOnSchemaChange` Option
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '5.25.0'
s.version = '5.26.1'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+11 -1
View File
@@ -733,6 +733,10 @@
56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; };
56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; };
56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; };
56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
56B7EE842863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
56B7EE852863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
56B7EE862863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
@@ -1595,6 +1599,7 @@
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = "<group>"; };
56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = "<group>"; };
56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = "<group>"; };
56B7EE822863781300C0525F /* WALSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshot.swift; sourceTree = "<group>"; };
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = "<group>"; };
@@ -2375,8 +2380,9 @@
56A238781B9C75030082EB20 /* Statement.swift */,
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
5605F1471C672E4000235C62 /* Support */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
56B7EE822863781300C0525F /* WALSnapshot.swift */,
5605F1471C672E4000235C62 /* Support */,
);
path = Core;
sourceTree = "<group>";
@@ -2976,6 +2982,7 @@
565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */,
5656A8AF2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */,
565490C21D5AE236005622CB /* Row.swift in Sources */,
56B7EE852863781300C0525F /* WALSnapshot.swift in Sources */,
565490C71D5AE236005622CB /* StatementColumnConvertible.swift in Sources */,
565490D91D5AE252005622CB /* Migration.swift in Sources */,
56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
@@ -3145,6 +3152,7 @@
5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
56DDDDF5242F87C60025E381 /* ValueObservationScheduler.swift in Sources */,
56B7EE842863781300C0525F /* WALSnapshot.swift in Sources */,
560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */,
56A2FA3B24424F4700E97D23 /* Export.swift in Sources */,
569BBA4F229170F900478429 /* Inflections+English.swift in Sources */,
@@ -3753,6 +3761,7 @@
AAA4DCA5230F1E0600C74B15 /* FTS3TokenizerDescriptor.swift in Sources */,
AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */,
56DDDDF7242F87C70025E381 /* ValueObservationScheduler.swift in Sources */,
56B7EE862863781300C0525F /* WALSnapshot.swift in Sources */,
AAA4DCA7230F1E0600C74B15 /* TableRecord.swift in Sources */,
56A2FA3D24424F4800E97D23 /* Export.swift in Sources */,
AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */,
@@ -4125,6 +4134,7 @@
569BBA4E229170F800478429 /* Inflections+English.swift in Sources */,
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */,
5617294E223533F40006E219 /* EncodableRecord.swift in Sources */,
56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */,
5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */,
56A2FA3624424D2A00E97D23 /* Export.swift in Sources */,
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
+9 -1
View File
@@ -275,7 +275,15 @@ public struct Configuration {
///
/// Default: nil
public var writeTargetQueue: DispatchQueue? = nil
#if os(iOS)
/// Sets whether GRDB will release memory when entering the background or
/// upon receiving a memory warning in iOS.
///
/// Default: true
public var automaticMemoryManagement = true
#endif
// MARK: - Factory Configuration
/// Creates a factory configuration
+2 -33
View File
@@ -553,38 +553,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
_readOnlyDepth > 0 || configuration.readonly
}
// MARK: - Snapshots
#if SQLITE_ENABLE_SNAPSHOT
/// Returns a snapshot that must be freed with `sqlite3_snapshot_free`.
///
/// See <https://www.sqlite.org/c3ref/snapshot.html>
func takeVersionSnapshot() throws -> UnsafeMutablePointer<sqlite3_snapshot> {
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
let code = withUnsafeMutablePointer(to: &snapshot) {
sqlite3_snapshot_get(sqliteConnection, "main", $0)
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
if let snapshot = snapshot {
return snapshot
} else {
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
}
}
func wasChanged(since initialSnapshot: UnsafeMutablePointer<sqlite3_snapshot>) throws -> Bool {
let secondSnapshot = try takeVersionSnapshot()
defer {
sqlite3_snapshot_free(secondSnapshot)
}
let cmp = sqlite3_snapshot_cmp(initialSnapshot, secondSnapshot)
assert(cmp <= 0, "Unexpected snapshot ordering")
return cmp < 0
}
#endif
// MARK: - Recording of the selected region
func recordingSelection<T>(_ region: inout DatabaseRegion, _ block: () throws -> T) rethrows -> T {
@@ -1216,7 +1184,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// MARK: - Memory Management
func releaseMemory() {
public func releaseMemory() {
SchedulingWatchdog.preconditionValidQueue(self)
sqlite3_db_release_memory(sqliteConnection)
schemaCache.clear()
internalStatementCache.clear()
+50 -19
View File
@@ -103,7 +103,9 @@ public final class DatabasePool: DatabaseWriter {
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
#if os(iOS)
setupMemoryManagement()
if configuration.automaticMemoryManagement {
setupMemoryManagement()
}
#endif
}
@@ -154,13 +156,6 @@ public final class DatabasePool: DatabaseWriter {
return configuration
}
/// Blocks the current thread until all database connections have
/// executed the *body* block.
fileprivate func forEachConnection(_ body: (Database) -> Void) {
writer.sync(body)
readerPool?.forEach { $0.sync(body) }
}
}
#if swift(>=5.6) && canImport(_Concurrency)
@@ -172,19 +167,49 @@ extension DatabasePool {
// MARK: - Memory management
/// Free as much memory as possible.
/// Frees as much memory as possible, by disposing non-essential memory from
/// the writer connection, and closing all reader connections.
///
/// This method blocks the current thread until all database accesses
/// are completed.
/// This method is synchronous, and blocks the current thread until all
/// database accesses are completed.
///
/// - warning: This method can prevent concurrent reads from executing,
/// until it returns. Prefer ``releaseMemoryEventually()`` if you intend
/// to keep on using the database while releasing memory.
public func releaseMemory() {
// Release writer memory
writer.sync { $0.releaseMemory() }
// Release readers memory by closing all connections
// Release readers memory by closing all connections.
//
// We must use a barrier in order to guarantee that memory has been
// freed (reader connections closed) when the method exits, as
// documented.
//
// Without the barrier, connections would only close _eventually_ (after
// their eventual concurrent jobs have completed).
readerPool?.barrier {
readerPool?.removeAll()
}
}
/// Eventually frees as much memory as possible, by disposing non-essential
/// memory from the writer connection, and closing all reader connections.
///
/// Unlike ``releaseMemory()``, this method does not prevent concurrent
/// database accesses when it is executing. But it does not notify when
/// non-essential memory has been freed.
public func releaseMemoryEventually() {
// Release readers memory by eventually closing all reader connections
// (they will close after their current jobs have completed).
readerPool?.removeAll()
// Release writer memory eventually.
writer.async { db in
db.releaseMemory()
}
}
#if os(iOS)
/// Listens to UIApplicationDidEnterBackgroundNotification and
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
@@ -216,12 +241,20 @@ extension DatabasePool {
let task: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
if task == .invalid {
// Perform releaseMemory() synchronously.
// Release memory synchronously
releaseMemory()
} else {
// Perform releaseMemory() asynchronously.
DispatchQueue.global().async {
self.releaseMemory()
// Release memory eventually.
//
// We don't know when reader connections will be closed (because
// they may be currently in use), so we don't quite know when
// reader memory will be freed (which would be the ideal timing for
// ending our background task).
//
// So let's just end the background task after the writer connection
// has freed its memory. That's better than nothing.
releaseMemoryEventually()
writer.async { _ in
application.endBackgroundTask(task)
}
}
@@ -229,9 +262,7 @@ extension DatabasePool {
@objc
private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
DispatchQueue.global().async {
self.releaseMemory()
}
releaseMemoryEventually()
}
#endif
}
+9 -7
View File
@@ -43,7 +43,9 @@ public final class DatabaseQueue: DatabaseWriter {
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
#if os(iOS)
setupMemoryManagement()
if configuration.automaticMemoryManagement {
setupMemoryManagement()
}
#endif
}
@@ -117,12 +119,12 @@ extension DatabaseQueue {
let task: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
if task == .invalid {
// Perform releaseMemory() synchronously.
// Release memory synchronously
releaseMemory()
} else {
// Perform releaseMemory() asynchronously.
DispatchQueue.global().async {
self.releaseMemory()
// Release memory asynchronously
writer.async { db in
db.releaseMemory()
application.endBackgroundTask(task)
}
}
@@ -130,8 +132,8 @@ extension DatabaseQueue {
@objc
private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
DispatchQueue.global().async {
self.releaseMemory()
writer.async { db in
db.releaseMemory()
}
}
#endif
+2 -27
View File
@@ -14,14 +14,6 @@ public final class DatabaseSnapshot: DatabaseReader {
serializedDatabase.configuration
}
#if SQLITE_ENABLE_SNAPSHOT
typealias Version = UnsafeMutablePointer<sqlite3_snapshot>
// Support for ValueObservation in DatabasePool
let version: Version?
#else
typealias Version = Void
#endif
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
var configuration = DatabasePool.readerConfiguration(configuration)
configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction
@@ -31,8 +23,8 @@ public final class DatabaseSnapshot: DatabaseReader {
configuration: configuration,
defaultLabel: defaultLabel,
purpose: purpose)
let version: Version? = try serializedDatabase.sync { db in
try serializedDatabase.sync { db in
// Assert WAL mode
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode")
guard journalMode == "wal" else {
@@ -44,29 +36,12 @@ public final class DatabaseSnapshot: DatabaseReader {
// Acquire snapshot isolation
try db.internalCachedStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
#if SQLITE_ENABLE_SNAPSHOT
// We must expect an error: https://www.sqlite.org/c3ref/snapshot_get.html
// > At least one transaction must be written to it first.
return try? db.takeVersionSnapshot()
#else
return nil
#endif
}
#if SQLITE_ENABLE_SNAPSHOT
self.version = version
#endif
}
deinit {
// Leave snapshot isolation
serializedDatabase.reentrantSync { db in
#if SQLITE_ENABLE_SNAPSHOT
if let version = version {
sqlite3_snapshot_free(version)
}
#endif
try? db.commit()
}
}
+1 -1
View File
@@ -287,7 +287,7 @@ extension Row {
/// The result is nil if the row does not contain the column.
public subscript(_ columnName: String) -> DatabaseValueConvertible? {
// IMPLEMENTATION NOTE
// This method has a single know use case: checking if the value is nil,
// This method has a single known use case: checking if the value is nil,
// as in:
//
// if row["foo"] != nil { ... }
+85
View File
@@ -0,0 +1,85 @@
/// An instance of WALSnapshot records the state of a WAL mode database for some
/// specific point in history.
///
/// We use `WALSnapshot` to help `ValueObservation` check for changes
/// that would happen between the initial fetch, and the start of the
/// actual observation. This class has no other purpose, and is not intended to
/// become public.
///
/// It does not work with SQLCipher, because SQLCipher does not support
/// `SQLITE_ENABLE_SNAPSHOT` correctly: we have linker errors.
/// See <https://github.com/ericsink/SQLitePCL.raw/issues/452>.
///
/// With custom SQLite builds, it only works if `SQLITE_ENABLE_SNAPSHOT`
/// is defined.
///
/// With system SQLite, it can only work when the SDK exposes the C apis and
/// their availability, which means XCode 14 (identified with Swift 5.7).
///
/// Yes, this is an awfully complex logic.
///
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
final class WALSnapshot {
#if os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7)
init?(_ db: Database) {
return nil
}
func compare(_ other: WALSnapshot) -> CInt {
preconditionFailure("snapshots are not available")
}
#else
private let snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
/// Returns nil if `SQLITE_ENABLE_SNAPSHOT` is not enabled, or if an
/// error occurs.
init?(_ db: Database) {
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
let code: CInt = withUnsafeMutablePointer(to: &snapshot) {
#if GRDBCUSTOMSQLITE
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
#else
// iOS 10.0 is always true because our minimum requirement is iOS 11.
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
} else {
return SQLITE_ERROR
}
#endif
}
guard code == SQLITE_OK, let s = snapshot else {
return nil
}
self.snapshot = s
}
deinit {
#if GRDBCUSTOMSQLITE
sqlite3_snapshot_free(snapshot)
#else
// iOS 10.0 is always true because our minimum requirement is iOS 11.
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
sqlite3_snapshot_free(snapshot)
}
#endif
}
/// Compares two WAL snapshots.
///
/// `a.compare(b) < 0` iff a is older than b.
///
/// See <https://www.sqlite.org/c3ref/snapshot_cmp.html>.
func compare(_ other: WALSnapshot) -> CInt {
#if GRDBCUSTOMSQLITE
return sqlite3_snapshot_cmp(snapshot, other.snapshot)
#else
// iOS 10.0 is always true because our minimum requirement is iOS 11.
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
return sqlite3_snapshot_cmp(snapshot, other.snapshot)
} else {
preconditionFailure("snapshots are not available")
}
#endif
}
#endif // os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7)
}
@@ -186,6 +186,9 @@ final class ValueConcurrentObserver<Reducer: ValueReducer> {
// 1. Start the observation without waiting for a write access (the expected
// benefit of `DatabasePool`).
// 2. Make sure we do not miss a change (a documented guarantee)
//
// Support for `SQLITE_ENABLE_SNAPSHOT` is implemented by our
// `WALSnapshot` class.
extension ValueConcurrentObserver {
// Starts the observation
func start() -> DatabaseCancellable {
@@ -234,7 +237,6 @@ extension ValueConcurrentObserver {
}
}
#if SQLITE_ENABLE_SNAPSHOT
// MARK: - Starting the Observation (with SQLITE_ENABLE_SNAPSHOT)
extension ValueConcurrentObserver {
@@ -248,14 +250,23 @@ extension ValueConcurrentObserver {
// transaction to complete.
//
// Fetch value & tracked region in a synchronous way.
//
// TODO: we currently perform the initial read from a snapshot, because
// it is a handy way to keep a read transaction open until we grab a
// write access, and compare the database versions. The problem is that
// we do not control the number of created shapshots: we should instead
// use a reader from the pool.
let initialSnapshot = try databaseAccess.dbPool.makeSnapshot()
let (fetchedValue, initialRegion): (Reducer.Fetched, DatabaseRegion) = try initialSnapshot.read { db in
let (fetchedValue, initialRegion, initialWALSnapshot) = try initialSnapshot.read {
db -> (Reducer.Fetched, DatabaseRegion, WALSnapshot?) in
// swiftlint:disable:previous closure_parameter_position
switch trackingMode {
case let .constantRegion(regions):
let fetchedValue = try databaseAccess.fetch(db)
let region = try DatabaseRegion.union(regions)(db)
let initialRegion = try region.observableRegion(db)
return (fetchedValue, initialRegion)
return (fetchedValue, initialRegion, WALSnapshot(db))
case .constantRegionRecordedFromSelection,
.nonConstantRegionRecordedFromSelection:
@@ -264,7 +275,7 @@ extension ValueConcurrentObserver {
try databaseAccess.fetch(db)
}
let initialRegion = try region.observableRegion(db)
return (fetchedValue, initialRegion)
return (fetchedValue, initialRegion, WALSnapshot(db))
}
}
@@ -280,6 +291,7 @@ extension ValueConcurrentObserver {
asyncStartObservation(
from: databaseAccess,
initialSnapshot: initialSnapshot,
initialWALSnapshot: initialWALSnapshot,
initialRegion: initialRegion)
return initialValue
@@ -293,6 +305,12 @@ extension ValueConcurrentObserver {
// for observing the database is to be able to fetch the initial value
// without having to wait for an eventual long-running write
// transaction to complete.
//
// TODO: we currently perform the initial read from a snapshot, because
// it is a handy way to keep a read transaction open until we grab a
// write access, and compare the database versions. The problem is that
// we do not control the number of created shapshots: we should instead
// use a reader from the pool.
do {
let initialSnapshot = try databaseAccess.dbPool.makeSnapshot()
initialSnapshot.asyncRead { dbResult in
@@ -344,6 +362,7 @@ extension ValueConcurrentObserver {
self.asyncStartObservation(
from: databaseAccess,
initialSnapshot: initialSnapshot,
initialWALSnapshot: WALSnapshot(db),
initialRegion: initialRegion)
} catch {
self.notifyError(error)
@@ -357,6 +376,7 @@ extension ValueConcurrentObserver {
private func asyncStartObservation(
from databaseAccess: DatabaseAccess,
initialSnapshot: DatabaseSnapshot,
initialWALSnapshot: WALSnapshot?,
initialRegion: DatabaseRegion)
{
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
@@ -371,13 +391,17 @@ extension ValueConcurrentObserver {
try writerDB.isolated(readOnly: true) {
// Keep DatabaseSnaphot alive until we have compared
// database versions. It prevents database checkpointing,
// and keeps versions (`sqlite3_snapshot`) valid
// and keeps WAL snapshots (`sqlite3_snapshot`) valid
// and comparable.
let isModified: Bool = try withExtendedLifetime(initialSnapshot) {
guard let initialVersion = initialSnapshot.version else {
let isModified: Bool = withExtendedLifetime(initialSnapshot) {
guard let initialWALSnapshot = initialWALSnapshot,
let currentWALSnapshot = WALSnapshot(writerDB)
else {
return true
}
return try writerDB.wasChanged(since: initialVersion)
let ordering = initialWALSnapshot.compare(currentWALSnapshot)
assert(ordering <= 0, "Unexpected snapshot ordering")
return ordering < 0
}
if isModified {
@@ -438,156 +462,6 @@ extension ValueConcurrentObserver {
}
}
#else
// MARK: - Starting the Observation (without SQLITE_ENABLE_SNAPSHOT)
extension ValueConcurrentObserver {
/// Synchronously starts the observation, and returns the initial value.
///
/// Unlike `asyncStart()`, this method does not notify the initial value or error.
private func syncStart(from databaseAccess: DatabaseAccess) throws -> Reducer.Value {
// Start from a read access. The whole point of using a DatabasePool
// for observing the database is to be able to fetch the initial value
// without having to wait for an eventual long-running write
// transaction to complete.
//
// Fetch in a synchronous reentrant way, in case this method is called
// from a database access.
let fetchedValue = try databaseAccess.dbPool.unsafeReentrantRead { db in
try db.isolated(readOnly: true) {
try databaseAccess.fetch(db)
}
}
// Reduce
let initialValue: Reducer.Value = reduceQueue.sync {
guard let initialValue = reducer._value(fetchedValue) else {
fatalError("Broken contract: reducer has no initial value")
}
return initialValue
}
// Start observation
asyncStartObservation(from: databaseAccess)
return initialValue
}
/// Asynchronously starts the observation
///
/// Unlike `syncStart()`, this method does notify the initial value or error.
private func asyncStart(from databaseAccess: DatabaseAccess) {
// Start from a read access. The whole point of using a DatabasePool
// for observing the database is to be able to fetch the initial value
// without having to wait for an eventual long-running write
// transaction to complete.
databaseAccess.dbPool.asyncRead { dbResult in
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
do {
// Fetch
let fetchedValue = try databaseAccess.fetch(dbResult.get())
// Reduce
//
// Reducing is performed asynchronously, so that we do not lock
// a database dispatch queue longer than necessary.
self.reduceQueue.async {
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
guard let initialValue = self.reducer._value(fetchedValue) else {
fatalError("Broken contract: reducer has no initial value")
}
// Notify
self.scheduler.schedule {
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange }
guard let onChange = onChangeOpt else { return /* Cancelled */ }
onChange(initialValue)
}
// Start observation
self.asyncStartObservation(from: databaseAccess)
}
} catch {
self.notifyError(error)
}
}
}
private func asyncStartObservation(from databaseAccess: DatabaseAccess) {
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
let eventsOpt = self.lock.synchronized { self.notificationCallbacks?.events }
guard let events = eventsOpt else { return /* Cancelled */ }
// We don't know if database has changed or not.
// So we assume it did, so that we are sure that we do
// not miss a database change.
events.databaseDidChange?()
do {
// Fetch
let fetchedValue: Reducer.Fetched
switch self.trackingMode {
case let .constantRegion(regions):
fetchedValue = try writerDB.isolated(readOnly: true) {
try databaseAccess.fetch(writerDB)
}
let region = try DatabaseRegion.union(regions)(writerDB)
let observedRegion = try region.observableRegion(writerDB)
events.willTrackRegion?(observedRegion)
self.startObservation(writerDB, observedRegion: observedRegion)
case .constantRegionRecordedFromSelection,
.nonConstantRegionRecordedFromSelection:
var region = DatabaseRegion()
fetchedValue = try writerDB.recordingSelection(&region) {
try writerDB.isolated(readOnly: true) {
try databaseAccess.fetch(writerDB)
}
}
let observedRegion = try region.observableRegion(writerDB)
events.willTrackRegion?(observedRegion)
self.startObservation(writerDB, observedRegion: observedRegion)
}
// Reduce
//
// Reducing is performed asynchronously, so that we do not lock
// the writer dispatch queue longer than necessary.
//
// Important: reduceQueue.async guarantees the same ordering
// between transactions and notifications!
self.reduceQueue.async {
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
let value = self.reducer._value(fetchedValue)
// Notify
if let value = value {
self.scheduler.schedule {
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange }
guard let onChange = onChangeOpt else { return /* Cancelled */ }
onChange(value)
}
}
}
} catch {
self.stopDatabaseObservation(writerDB)
self.notifyError(error)
}
}
}
}
#endif
// MARK: - Observing Database Transactions
extension ValueConcurrentObserver: TransactionObserver {
+8 -2
View File
@@ -214,6 +214,8 @@
5653EB8120961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */; };
5653EB8220961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; };
5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; };
56564F3928637C9900A19E9F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56564F3828637C9900A19E9F /* WALSnapshot.swift */; };
56564F3A28637C9900A19E9F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56564F3828637C9900A19E9F /* WALSnapshot.swift */; };
5656A7F622946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A7F422946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; };
5656A7F722946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A7F422946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; };
5656A8512295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8262295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift */; };
@@ -913,6 +915,7 @@
5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = "<group>"; };
5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = "<group>"; };
5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = "<group>"; };
56564F3828637C9900A19E9F /* WALSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshot.swift; sourceTree = "<group>"; };
5656A7F422946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationQueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
5656A8262295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLInterpolation+QueryInterface.swift"; sourceTree = "<group>"; };
5656A8282295BD56001FF3FF /* FTS5+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS5+QueryInterface.swift"; sourceTree = "<group>"; };
@@ -1830,8 +1833,9 @@
56A238781B9C75030082EB20 /* Statement.swift */,
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
5605F1471C672E4000235C62 /* Support */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
56564F3828637C9900A19E9F /* WALSnapshot.swift */,
5605F1471C672E4000235C62 /* Support */,
);
path = Core;
sourceTree = "<group>";
@@ -1961,8 +1965,8 @@
DC37742D19C8CC90004FCF85 /* GRDB */ = {
isa = PBXGroup;
children = (
56A2386F1B9C75030082EB20 /* Core */,
56A2FA3724424F4200E97D23 /* Export.swift */,
56A2386F1B9C75030082EB20 /* Core */,
5614089D221596A100DAD589 /* Fixit */,
5698AC291D9E5A480056AF8C /* FTS */,
56A238911B9C750B0082EB20 /* Migration */,
@@ -2360,6 +2364,7 @@
56A6EB2526076F6A00C27594 /* SQL.swift in Sources */,
5656A8762295BD56001FF3FF /* RequestProtocols.swift in Sources */,
568ECB3625D91CEF00B71526 /* SQLSubquery.swift in Sources */,
56564F3A28637C9900A19E9F /* WALSnapshot.swift in Sources */,
561729552235340E0006E219 /* EncodableRecord.swift in Sources */,
5656A87E2295BD56001FF3FF /* SQLAssociation.swift in Sources */,
F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */,
@@ -2731,6 +2736,7 @@
56A6EB2426076F6A00C27594 /* SQL.swift in Sources */,
5656A8752295BD56001FF3FF /* RequestProtocols.swift in Sources */,
568ECB3525D91CEF00B71526 /* SQLSubquery.swift in Sources */,
56564F3928637C9900A19E9F /* WALSnapshot.swift in Sources */,
561729562235340E0006E219 /* EncodableRecord.swift in Sources */,
5656A87D2295BD56001FF3FF /* SQLAssociation.swift in Sources */,
F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */,
+7 -7
View File
@@ -57,7 +57,7 @@ ifeq ($(XCODEVERSION),14.0)
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=12.4"
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=16.0"
#MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore
OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks'
OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK'
GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1'
else ifeq ($(XCODEVERSION),13.4)
MAX_SWIFT_VERSION = 5.6
@@ -66,7 +66,7 @@ else ifeq ($(XCODEVERSION),13.4)
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=13.7"
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=15.4"
#MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore
OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks'
OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK'
GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1'
else ifeq ($(XCODEVERSION),13.3)
MAX_SWIFT_VERSION = 5.6
@@ -75,7 +75,7 @@ else ifeq ($(XCODEVERSION),13.3)
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=13.7"
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=15.4"
#MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore
OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks'
OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK'
GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1'
else ifeq ($(XCODEVERSION),13.2)
MAX_SWIFT_VERSION = 5.5
@@ -84,7 +84,7 @@ else ifeq ($(XCODEVERSION),13.2)
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=13.7"
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=15.2"
#MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore
OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks'
OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK'
GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1'
else ifeq ($(XCODEVERSION),13.1)
MAX_SWIFT_VERSION = 5.5
@@ -586,10 +586,10 @@ ifdef JAZZY
--author 'Gwendal Roué' \
--author_url https://github.com/groue \
--github_url https://github.com/groue/GRDB.swift \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.25.0 \
--module-version 5.25.0 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.26.1 \
--module-version 5.26.1 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/5.25/ \
--root-url http://groue.github.io/GRDB.swift/docs/5.26/ \
--output Documentation/Reference \
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
else
+45 -21
View File
@@ -11,13 +11,13 @@
---
**Latest release**: June 11, 2022 • [version 5.25.0](https://github.com/groue/GRDB.swift/tree/v5.25.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
**Latest release**: September 8, 2022 • [version 5.26.1](https://github.com/groue/GRDB.swift/tree/v5.26.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
**Requirements**: iOS 11.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ &bull; SQLite 3.8.5+ &bull; Swift 5.3+ / Xcode 12+
| Swift version | GRDB version |
| -------------- | ----------------------------------------------------------- |
| **Swift 5.3+** | **v5.25.0** |
| **Swift 5.3+** | **v5.26.1** |
| Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) |
| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
| Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
@@ -321,7 +321,7 @@ Documentation
#### Reference
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.25/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.26/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
#### Getting Started
@@ -617,7 +617,7 @@ do {
>
> :warning: **Warning**: The SQLite version that ships with old operating systems (prior to OSX 10.12, tvOS 10.0, and watchOS 3.0) outputs statement arguments in the [trace events](#how-do-i-print-a-request-as-sql), regardless of the `publicStatementArguments` flag.
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.25/Structs/Configuration.html) for more details and configuration options.
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.26/Structs/Configuration.html) for more details and configuration options.
SQLite API
@@ -674,7 +674,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.25/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details.
@@ -932,7 +932,7 @@ try dbQueue.read { db in
let dictionary = try Dictionary(uniqueKeysWithValues: cursor)
```
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.25/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.26/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
```swift
// Prints all Github links
@@ -1011,7 +1011,7 @@ let rows = try Row.fetchAll(db,
arguments: ["name": "Arthur"])
```
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.25/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
@@ -1296,7 +1296,7 @@ GRDB ships with built-in support for the following value types:
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.25/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html):
```swift
let url: URL = ...
@@ -1767,7 +1767,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
}
```
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.25/Structs/Configuration.html) configuration flag:
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.26/Structs/Configuration.html) configuration flag:
```swift
// fatal error: A transaction has been left opened at the end of a database access
@@ -1879,7 +1879,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.25/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
```swift
insertStatement.arguments = ["name": "Arthur", "score": 1000]
@@ -1962,7 +1962,7 @@ See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates)
> :point_up: **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so.
For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.25/Classes/Statement.html).
For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.26/Classes/Statement.html).
### Prepared Statements Cache
@@ -2705,7 +2705,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set<Place>
try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place?
```
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.25/Structs/StatementArguments.html) for more information about the query arguments.
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html) for more information about the query arguments.
> :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
@@ -3145,7 +3145,7 @@ protocol EncodableRecord {
}
```
See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.25/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.25/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies.
See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies.
### Date and UUID Coding Strategies
@@ -3167,7 +3167,7 @@ protocol EncodableRecord {
}
```
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.25/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.25/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.25/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase).
@@ -4692,7 +4692,7 @@ Player // SELECT * FROM player
```
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.25/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -5598,7 +5598,7 @@ try Player.customRequest().fetchAll(db) // [Player]
- The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.25/Structs/AnyFetchRequest.html): a type-erased request.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.26/Structs/AnyFetchRequest.html): a type-erased request.
## Joined Queries Support
@@ -6900,7 +6900,7 @@ DatabaseRegion helps [ValueObservation] and [DatabaseRegionObservation] track ch
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.25/Structs/DatabaseRegion.html).
For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.26/Structs/DatabaseRegion.html).
#### The DatabaseRegionConvertible Protocol
@@ -7718,12 +7718,36 @@ dbPool.releaseMemory()
This method blocks the current thread until all current database accesses are completed, and the memory collected.
> :warning: **Warning**: If `DatabasePool.releaseMemory()` is called while a long read is performed concurrently, then no other read access will be possible until this long read has completed, and the memory has been released. If this does not suit your application needs, look for the asynchronous options below:
You can release memory in an asynchronous way as well:
```swift
// On a DatabaseQueue
dbQueue.asyncWriteWithoutTransaction { db in
db.releaseMemory()
}
// On a DatabasePool
dbPool.releaseMemoryEventually()
```
`DatabasePool.releaseMemoryEventually()` does not block the current thread, and does not prevent concurrent database accesses. In exchange for this convenience, you don't know when memory has been freed.
### Memory Management on iOS
**The iOS operating system likes applications that do not consume much memory.**
[Database queues](#database-queues) and [pools](#database-pools) automatically call the `releaseMemory` method when the application receives a memory warning, and when the application enters background.
[Database queues](#database-queues) and [pools](#database-pools) automatically free non-essential memory when the application receives a memory warning, and when the application enters background.
You can opt out of this automatic memory management:
```swift
var config = Configuration()
config.automaticMemoryManagement = false
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) // or DatabasePool
```
## Data Protection
@@ -8240,7 +8264,7 @@ When this is the case, there are two possible explanations:
try db.execute(sql: "UPDATE player SET name = ?", arguments: [name])
```
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.25/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.26/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
@@ -8381,7 +8405,7 @@ This chapter has [moved](Documentation/Concurrency.md#database-snapshots).
#### DatabaseWriter and DatabaseReader Protocols
This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.25/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.25/Protocols/DatabaseWriter.html).
This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.26/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.26/Protocols/DatabaseWriter.html).
#### Asynchronous APIs
@@ -8434,7 +8458,7 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests].
[Sharing a Database]: Documentation/SharingADatabase.md
[FAQ]: #faq
[Database Observation]: #database-changes-observation
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.25/Structs/SQLRequest.html
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.26/Structs/SQLRequest.html
[SQL literal]: Documentation/SQLInterpolation.md#sql-literal
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
[Query Interface Organization]: Documentation/QueryInterfaceOrganization.md
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>5.25.0</string>
<string>5.26.1</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -41,6 +41,85 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
XCTAssertEqual(openConnectionCount, 0)
}
#if os(iOS)
func testDatabasePoolReleasesMemoryOnPressureEvent() throws {
// Create a database pool, and expect a reader connection to be closed
let expectation = self.expectation(description: "Reader connection closed")
var configuration = Configuration()
configuration.SQLiteConnectionWillClose = { conn in
if sqlite3_db_readonly(conn, nil) != 0 {
expectation.fulfill()
}
}
let dbPool = try makeDatabasePool(configuration: configuration)
// Precondition: there is one reader.
try dbPool.read { _ in }
// Simulate memory warning.
NotificationCenter.default.post(
name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"),
object: nil)
// Postcondition: reader connection was closed
withExtendedLifetime(dbPool) { _ in
waitForExpectations(timeout: 0.5)
}
}
func testDatabasePoolDoesNotReleaseMemoryOnPressureEventIfDisabled() throws {
// Create a database pool, and do not expect any reader connection to be closed
let expectation = self.expectation(description: "Reader connection closed")
expectation.isInverted = true
var configuration = Configuration()
configuration.automaticMemoryManagement = false
configuration.SQLiteConnectionWillClose = { conn in
if sqlite3_db_readonly(conn, nil) != 0 {
expectation.fulfill()
}
}
let dbPool = try makeDatabasePool(configuration: configuration)
// Precondition: there is one reader.
try dbPool.read { _ in }
// Simulate memory warning.
NotificationCenter.default.post(
name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"),
object: nil)
// Postcondition: no reader connection was closed
withExtendedLifetime(dbPool) { _ in
waitForExpectations(timeout: 0.5)
}
}
// Regression test for <https://github.com/groue/GRDB.swift/pull/1253#issuecomment-1177166630>
func testDatabasePoolDoesNotPreventConcurrentReadsOnPressureEvent() throws {
let dbPool = try makeDatabasePool()
// Start a read that blocks
let semaphore = DispatchSemaphore(value: 0)
dbPool.asyncRead { _ in
semaphore.wait()
}
// Simulate memory warning.
NotificationCenter.default.post(
name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"),
object: nil)
// Make sure we can read
try dbPool.read { _ in }
// Cleanup
semaphore.signal()
}
#endif
// TODO: fix flaky test
// func testDatabasePoolReleaseMemoryClosesReaderConnections() throws {
// let countQueue = DispatchQueue(label: "GRDB")
+58 -60
View File
@@ -418,39 +418,38 @@ class ValueObservationTests: GRDBTestCase {
return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!
}
#if SQLITE_ENABLE_SNAPSHOT
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .async(onQueue: .main),
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, [0, 1])
}
let expectedCounts: [Int]
#if os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7)
// Optimization not available
expectedCounts = [0, 0, 1]
#elseif GRDBCUSTOMSQLITE
// Optimization available
expectedCounts = [0, 1]
#else
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 3
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .async(onQueue: .main),
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, [0, 0, 1])
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
// Optimization available
expectedCounts = [0, 1]
} else {
// Optimization not available
expectedCounts = [0, 0, 1]
}
#endif
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = expectedCounts.count
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .async(onQueue: .main),
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, expectedCounts)
}
}
func testAllowedSnapshotOptimizationWithImmediateScheduler() throws {
@@ -477,39 +476,38 @@ class ValueObservationTests: GRDBTestCase {
return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!
}
#if SQLITE_ENABLE_SNAPSHOT
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .immediate,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, [0, 1])
}
let expectedCounts: [Int]
#if os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7)
// Optimization not available
expectedCounts = [0, 0, 1]
#elseif GRDBCUSTOMSQLITE
// Optimization available
expectedCounts = [0, 1]
#else
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 3
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .immediate,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, [0, 0, 1])
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
// Optimization available
expectedCounts = [0, 1]
} else {
// Optimization not available
expectedCounts = [0, 0, 1]
}
#endif
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = expectedCounts.count
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .immediate,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, expectedCounts)
}
}
// MARK: - Cancellation