Compare commits

...
62 Commits
Author SHA1 Message Date
Gwendal Roué 8e50383371 v2.6.1 2018-01-19 16:24:09 +01:00
Gwendal Roué ffc5352840 Fix transaction observer crash 2018-01-19 16:17:38 +01:00
Gwendal Roué 53e849cbec v2.6.0 2018-01-18 13:05:07 +01:00
Gwendal Roué b71d57d7ec Merge pull request #288 from groue/TransactionObserverInvalidation
Enhance Database Observation
2018-01-18 13:04:41 +01:00
Gwendal Roué 4fe2b2542f Cleanup 2018-01-18 12:54:02 +01:00
Gwendal Roué 8c7895d8ab Have Makefile accept both Xcode9.0 and Xcode9.0.1 2018-01-18 12:47:29 +01:00
Gwendal Roué ad15f4dc59 Fix .travis.yml for Xcode9 2018-01-17 13:51:19 +01:00
Gwendal Roué c4ef161a83 Rename Statement.region and Request.region to fetchedRegion 2018-01-17 06:54:10 +01:00
Gwendal Roué bb48025947 Derived requests ought to preserve database region: fix failing tests 2018-01-16 20:39:19 +01:00
Gwendal Roué 389a7f28c4 Derived requests ought to preserve database region: failing tests 2018-01-16 20:39:13 +01:00
Gwendal Roué 714cc1c734 DatabaseRegion() is public 2018-01-16 19:57:30 +01:00
Gwendal Roué 8d0da7f870 DatabaseRegion documentation 2018-01-16 18:47:59 +01:00
Gwendal Roué e42e74103d DatabaseRegion documentation 2018-01-16 18:46:55 +01:00
Gwendal Roué 4bcdb91895 AnyRequest and all derived requests preserve database region, and counting method 2018-01-16 14:11:05 +01:00
Gwendal Roué 938977bbca Cleanup DatabaseRegion: no more public intersection, no more public way to specify rowids 2018-01-16 13:58:55 +01:00
Gwendal Roué 581c1c46e2 More TODO 2018-01-16 11:28:48 +01:00
Gwendal Roué 768b2ab620 More TODO 2018-01-16 09:30:12 +01:00
Gwendal Roué 4eff5ab357 More TODO 2018-01-16 09:06:53 +01:00
Gwendal Roué 888892b92f Cleanup 2018-01-16 09:04:06 +01:00
Gwendal Roué ba4f146c9c Cleanup 2018-01-16 08:55:48 +01:00
Gwendal Roué 8359dd2ae2 Cleanup 2018-01-16 08:54:12 +01:00
Gwendal Roué 0be80db8f9 Cleanup 2018-01-16 08:51:42 +01:00
Gwendal Roué 72de142519 Cleanup 2018-01-16 08:50:49 +01:00
Gwendal Roué 0a7468f56d Cleanup 2018-01-16 08:34:54 +01:00
Gwendal Roué 33b5c6c616 Rename DatabaseSelectionInfo to DatabaseRegion 2018-01-16 08:23:08 +01:00
Gwendal Roué 4003d7600d DatabaseSelectionInfo documentation WIP 2018-01-15 23:41:49 +01:00
Gwendal Roué a7122ba8bb Unit tests for DatabaseSelectionInfo.isModified methods 2018-01-15 23:09:52 +01:00
Gwendal Roué dc8c85d3db Odd failing tests for DatabaseSelectionInfo and the rowid column. Consequences not cleared out yet. 2018-01-15 22:44:09 +01:00
Gwendal Roué fc1b4a6f35 Complete refactoring of SelectStatement.SelectionInfo into DatabaseSelectionInfo 2018-01-15 22:28:43 +01:00
Gwendal Roué af42623654 Fix SPM tests 2018-01-15 07:22:01 +01:00
Gwendal Roué ab1a672336 Disable test that fails on iOS 8.1 (SQLite 3.7.13) 2018-01-14 23:31:19 +01:00
Gwendal Roué 4501d7dcde TransactionObserver: provide default implementation for rarely used and stabilized databaseWillChange() and databaseWillCommit() methods 2018-01-14 22:58:12 +01:00
Gwendal Roué 5d463d6bff Goal achieved! FetchedRecordsController uses ignoreDatabaseChangesUntilNextTransaction, and checks changed rowIds in order to avoid useless fetch requests 2018-01-14 22:41:27 +01:00
Gwendal Roué 9c8a9fbe32 SelectionInfo.rowIds contains the rowIds fetched by a request 2018-01-14 22:05:18 +01:00
Gwendal Roué 1a89b2eae5 Test that sqlite authorizer uses "ROWID" as the name of the rowid column 2018-01-14 20:15:55 +01:00
Gwendal Roué fd65e72bbb CHANGELOG 2018-01-14 19:41:05 +01:00
Gwendal Roué 33e8d0875d Remove update hook when no observer is active. Allow truncate optimization when deletions are not observed. 2018-01-14 19:34:11 +01:00
Gwendal Roué 19e75576a8 Documentation for TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() 2018-01-14 17:36:51 +01:00
Gwendal Roué 980860b2e9 Documentation for TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() 2018-01-14 17:35:17 +01:00
Gwendal Roué eee3e36238 Test TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() 2018-01-14 17:08:53 +01:00
Gwendal Roué eaadd37e87 TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() is public 2018-01-14 17:08:42 +01:00
Gwendal Roué a1e508b1df TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() 2018-01-14 16:45:36 +01:00
Gwendal Roué 2c8f9dffdd TODO GRDB3 2018-01-12 10:06:26 +01:00
Gwendal Roué 92fd3bf8ae TODO: TransactionObserver.stopObservingUntilNextTransaction() 2018-01-12 09:48:57 +01:00
Gwendal Roué c940675bf3 Fix typo 2018-01-12 09:12:35 +01:00
Gwendal Roué 2a147d5029 Travis: test Xcode 9.2 and Xcode 9.0 2018-01-12 08:19:02 +01:00
Gwendal Roué 0d236ae32c Row adopts RandomAccessCollection 2018-01-12 08:18:50 +01:00
Gwendal Roué cf4654108e More doc for filter(key:) and filter(keys:) 2018-01-12 07:19:26 +01:00
Gwendal Roué 7e9eed9374 v2.5.0 2018-01-11 21:16:54 +01:00
Gwendal Roué 383581938a Cleanup 2018-01-11 20:14:01 +01:00
Gwendal Roué df50da9024 Cleanup 2018-01-11 20:12:02 +01:00
Gwendal Roué d3a65303a1 Cleanup 2018-01-11 20:06:59 +01:00
Gwendal Roué 9a2bf923d2 Update CHANGELOG and README for new key-filtering requests 2018-01-11 20:04:49 +01:00
Gwendal Roué 9b27c0c651 WIP TableMapping.filter(key: [:]) and TableMapping.filter(keys: [[:], ]) 2018-01-11 19:34:28 +01:00
Gwendal Roué 2af85e7347 WIP TableMapping.filter(key:1) and TableMapping.filter(keys: [1, 2, 3]) 2018-01-11 18:09:01 +01:00
Gwendal Roué 071f0f4443 Cleanup 2018-01-10 08:50:45 +01:00
Gwendal Roué 903e8c96aa '^foo' is no longer an invalid FTS5 pattern in upcoming SQLite 3.22.0 2018-01-10 07:40:02 +01:00
Gwendal Roué 79a5fb9c15 Cleanup 2018-01-08 08:44:42 +01:00
Gwendal Roué 46ef4b27bb Fix failing test 2018-01-07 15:29:24 +01:00
Gwendal Roué 1838797d38 CHANGELOG 2018-01-07 14:25:36 +01:00
Gwendal Roué c7d500b8ba Optimize database event notifications for simple statements without side effect 2018-01-07 14:25:29 +01:00
Gwendal Roué 95a09cb644 Only notify observed events to transaction observers 2018-01-07 13:33:35 +01:00
54 changed files with 3692 additions and 702 deletions

No files matched your search

+104 -46
View File
@@ -15,140 +15,198 @@ jobs:
###########################################
## Test GRDB
# Test GRDBOSX (Xcode 9.1)
# Test GRDBOSX (Xcode 9.2)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBOSX (Xcode 9.1, macOS)
- TID=GRDBOSX (Xcode 9.2, macOS)
script: make test_framework_GRDBOSX
# Test GRDBWatchOS (Xcode 9.1)
# Test GRDBWatchOS (Xcode 9.2)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBWatchOS (Xcode 9.1, watchOS)
- TID=GRDBWatchOS (Xcode 9.2, watchOS)
script: make test_framework_GRDBWatchOS
# Test GRDBiOS (Xcode 9.1, iOS <MAXIMUM VERSION>)
# Test GRDBiOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBiOS (Xcode 9.1, iOS <MAX>)
- TID=GRDBiOS (Xcode 9.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget
# Test GRDBiOS (Xcode 9.1, iOS <MINIMUM VERSION>))
# Test GRDBiOS (Xcode 9.2, iOS <MINIMUM VERSION>))
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBiOS (Xcode 9.1, iOS <MIN>)
- TID=GRDBiOS (Xcode 9.2, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
# Test GRDB [SPM] (Xcode 9.1, macOS)
# Test GRDB [SPM] (Xcode 9.2, macOS)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDB [SPM] (Xcode 9.1, macOS)
- TID=GRDB [SPM] (Xcode 9.2, macOS)
script: make test_SPM
# Test GRDBOSX (Xcode 9.0)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBOSX (Xcode 9.0, macOS)
script: make test_framework_GRDBOSX
# Test GRDBiOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBiOS (Xcode 9.0, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget
###########################################
## Test GRDB (Custom SQLite)
# Test GRDBCustomSQLiteOSX (Xcode 9.1)
# Test GRDBCustomSQLiteOSX (Xcode 9.2)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBCustomSQLiteOSX (Xcode 9.1, macOS)
- TID=GRDBCustomSQLiteOSX (Xcode 9.2, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
# Test GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MAXIMUM VERSION>)
# Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MAX>)
- TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
# Test GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MINIMUM VERSION>))
# Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MINIMUM VERSION>))
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MIN>)
- TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
# Test GRDBCustomSQLiteOSX (Xcode 9.0)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBCustomSQLiteOSX (Xcode 9.0, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
# Test GRDBCustomSQLiteiOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9.0, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
###########################################
## Test GRDB (SQLCipher)
# Test GRDBCipherOSX (Xcode 9.1)
# Test GRDBCipherOSX (Xcode 9.2)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBCipherOSX (Xcode 9.1, macOS)
- TID=GRDBCipherOSX (Xcode 9.2, macOS)
script: make test_framework_GRDBCipherOSX
# Test GRDBCipheriOS (Xcode 9.1, iOS <MAXIMUM VERSION>)
# Test GRDBCipheriOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBCipheriOS (Xcode 9.1, iOS <MAX>)
- TID=GRDBCipheriOS (Xcode 9.2, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
# Test GRDBCipheriOS (Xcode 9.1, iOS <MINIMUM VERSION>))
# Test GRDBCipheriOS (Xcode 9.2, iOS <MINIMUM VERSION>))
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBCipheriOS (Xcode 9.1, iOS <MIN>)
- TID=GRDBCipheriOS (Xcode 9.2, iOS <MIN>)
script: make test_framework_GRDBCipheriOS_minTarget
# Test GRDBCipherOSX (Xcode 9.0)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBCipherOSX (Xcode 9.0, macOS)
script: make test_framework_GRDBCipherOSX
# Test GRDBCipheriOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBCipheriOS (Xcode 9.0, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
###########################################
## Test Installation Methods
# Manual Install
# Manual Install (Xcode 9.2)
- stage: Test Installation
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=Manual Install
- TID=Manual Install (Xcode 9.2)
script: make test_install_manual
# Manual Install (GRDBCipher)
# Manual Install (GRDBCipher, Xcode 9.2)
- stage: Test Installation
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=Manual Install (GRDBCipher)
- TID=Manual Install (GRDBCipher, Xcode 9.2)
script: make test_install_GRDBCipher
# Cocoapods Lint
# Cocoapods Lint (Xcode 9.2)
- stage: Test Installation
osx_image: xcode9.1
osx_image: xcode9.2
install:
- gem install cocoapods # Since Travis is not always on latest version
env:
- TID=Cocoapods
- TID=Cocoapods (Xcode 9.2)
script: make test_CocoaPodsLint
# SPM Install
# Cocoapods Lint (Xcode 9.0)
- stage: Test Installation
osx_image: xcode9.1
osx_image: xcode9
install:
- gem install cocoapods # Since Travis is not always on latest version
env:
- TID=SPM
- TID=Cocoapods (Xcode 9.0)
script: make test_CocoaPodsLint
# SPM Install (Xcode 9.2)
- stage: Test Installation
osx_image: xcode9.2
env:
- TID=SPM (Xcode 9.2)
script: make test_install_SPM
## Carthage Build
## Commented out until `make test_CarthageBuild` performs *reliably*.
## See https://github.com/groue/GRDB.swift/pull/262
# - stage: Test Installation
# osx_image: xcode9.1
# osx_image: xcode9.2
# before_install:
# - brew update
# - brew outdated carthage || brew upgrade carthage
+145 -2
View File
@@ -1,6 +1,149 @@
Release Notes
=============
## 2.6.1
Released January 19, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.6.0...v2.6.1)
**Fixed**
Fixed a crash that could happen when a transaction observer uses the stopObservingDatabaseChangesUntilNextTransaction().
## 2.6.0
Released January 18, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.5.0...v2.6.0)
### New
- Database observation has been enhanced:
- `TransactionObserver.stopObservingDatabaseChangesUntilNextTransaction()` allows transaction observers to stop observing the database for the remaining extent of a transaction.
- GRDB no longer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt) when no transaction observers are interested in deleted rows.
- FetchedRecordsController now avoids checking for changes in untracked rowIds.
- `DatabaseRegion` is a new public type that helps transaction observers recognize impactful database changes. This type is not documented in the main documentation. For more information, see [DatabaseRegion reference](http://groue.github.io/GRDB.swift/docs/2.6/Structs/DatabaseRegion.html), and look at [FetchedRecordsController implementation](https://github.com/groue/GRDB.swift/blob/master/GRDB/Record/FetchedRecordsController.swift).
- `TransactionObserver` protocol provides default implementations for rarely used callbacks.
- `Row` adopts RandomAccessCollection
### API diff
```diff
extension TransactionObserver {
+ func stopObservingDatabaseChangesUntilNextTransaction()
+
+ // Default implementation
+ func databaseWillCommit() throws
+
+ #if SQLITE_ENABLE_PREUPDATE_HOOK
+ // Default implementation
+ func databaseWillChange(with event: DatabasePreUpdateEvent)
+ #endif
}
+struct DatabaseRegion: Equatable {
+ var isEmpty: Bool
+
+ init()
+
+ func union(_ other: DatabaseRegion) -> DatabaseRegion
+ mutating func formUnion(_ other: DatabaseRegion)
+
+ func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool
+ func isModified(by event: DatabaseEvent) -> Bool
+}
class SelectStatement {
+ var fetchedRegion: DatabaseRegion
+
+ @available(*, deprecated, renamed:"DatabaseRegion")
+ typealias SelectionInfo = DatabaseRegion
+
+ @available(*, deprecated, renamed:"fetchedRegion")
+ var selectionInfo: DatabaseRegion
}
enum DatabaseEventKind {
- func impacts(_ selectionInfo: SelectStatement.SelectionInfo) -> Bool
+ @available(*, deprecated, message: "Use DatabaseRegion.isModified(byEventsOfKind:) instead")
+ func impacts(_ region: DatabaseRegion) -> Bool
}
protocol Request {
+ // Default implementation
+ func fetchedRegion(_ db: Database) throws -> DatabaseRegion
}
+extension Row: RandomAccessCollection {
+}
+extension RowIndex: Strideable {
}
```
## 2.5.0
Released January 11, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.4.2...v2.5.0)
### Fixed
- [Transaction observers](https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol) used to be notified of some database changes they were not interested into, in case of complex statements with side effects (foreign key cascades or sql triggers). This has been fixed.
### New
- The query interface has learned to build requests from any key (primary keys and unique keys) ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#fetching-by-key)):
```swift
// SELECT * FROM players WHERE id = 1
let request = Player.filter(key: 1)
let player = try request.fetchOne(db) // Player?
// SELECT * FROM countries WHERE isoCode IN ('FR', 'US')
let request = Country.filter(keys: ["FR", "US"])
let countries = try request.fetchAll(db) // [Country]
// SELECT * FROM players WHERE email = 'arthur@example.com'
let request = Player.filter(key: ["email": "arthur@example.com"])
let player = try request.fetchOne(db) // Player?
```
This feature has been introduced in order to ease the use of [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB):
```swift
// New
Player.filter(key: 1).rx
.fetchOne(in: dbQueue)
.subscribe(onNext: { player: Player? in
print("Player 1 has changed")
})
```
### API diff
```diff
extension TableMapping {
+ static func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<Self>
+ static func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible
+ static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<Self>
+ static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<Self>
}
extension QueryInterfaceRequest where T: TableMapping {
+ func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<T>
+ func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<T> where Sequence.Element: DatabaseValueConvertible
+ func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<T>
+ func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<T>
}
extension RowConvertible where Self: TableMapping {
- static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self?
+ static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self?
}
```
## 2.4.2
Released January 6, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.4.1...v2.4.2)
@@ -125,14 +268,14 @@ Released October 24, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/comp
### API diff
```diff
extension Request {
extension Request {
+ func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest
}
struct SQLRequest {
+ let sql: String
+ let arguments: StatementArguments?
+ let adapter: RowAdapter?
}
}
```
+1 -1
View File
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```sh
cd [GRDB directory]
git checkout v2.4.2
git checkout v2.6.1
git submodule update --init SQLiteCustom/src
````
+2 -2
View File
@@ -497,7 +497,7 @@ Build a `value BETWEEN min AND max` expression from Swift ranges:
#### The COUNT Function
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.4/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.4/Functions.html) functions:
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.6/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.6/Functions.html) functions:
```swift
// SQLExpression: COUNT(email)
@@ -588,4 +588,4 @@ You may want to compare it to another protocol, SQLSpecificExpressible, which ha
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `cast` function, it is Database.ColumnType.
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/SQLExpression.html) protocol.
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/2.6/Protocols/SQLExpression.html) protocol.
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '2.4.2'
s.version = '2.6.1'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
+14 -6
View File
@@ -24,7 +24,7 @@
5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */; };
5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; };
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; };
5605F1881C69111300235C62 /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; };
5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; };
5605F1931C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; };
@@ -349,6 +349,9 @@
5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; };
5698AD3B1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; };
569C1EB51CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; };
569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; };
569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; };
569EF0E4200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; };
56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; };
56A2383A1B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */; };
56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */; };
@@ -533,7 +536,7 @@
56D496B31D8133E3008276D7 /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; };
56D496B51D813413008276D7 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
56D496B61D813434008276D7 /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
56D496B61D813434008276D7 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
56D496B71D81344B008276D7 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; };
56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; };
56D496B91D81346F008276D7 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; };
@@ -724,7 +727,7 @@
5605F1521C672E4000235C62 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = "<group>"; };
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+RawRepresentable.swift"; sourceTree = "<group>"; };
5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementSelectionInfoTests.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = "<group>"; };
5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = "<group>"; };
5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceSelectQueryDefinition.swift; sourceTree = "<group>"; };
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
@@ -862,6 +865,7 @@
5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = "<group>"; };
5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = "<group>"; };
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = "<group>"; };
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = "<group>"; };
56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = "<group>"; };
56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueInMemoryTests.swift; sourceTree = "<group>"; };
56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseErrorTests.swift; sourceTree = "<group>"; };
@@ -1352,11 +1356,11 @@
569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */,
563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */,
569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */,
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */,
56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */,
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */,
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */,
56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */,
5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */,
);
name = Private;
sourceTree = "<group>";
@@ -1467,6 +1471,7 @@
560A37A31C8F625000949E71 /* DatabasePool.swift */,
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
@@ -2189,6 +2194,7 @@
566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
565490C81D5AE252005622CB /* CGFloat.swift in Sources */,
56F5ABDC1D814330001F60CB /* URL.swift in Sources */,
569EF0E4200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
565490D31D5AE252005622CB /* (null) in Sources */,
566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
566B910F1FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
@@ -2290,6 +2296,7 @@
5659F4A31EA8D997004A4992 /* Result.swift in Sources */,
56B964BC1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
5605F1661C672E4000235C62 /* NSNull.swift in Sources */,
569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */,
@@ -2447,7 +2454,7 @@
56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */,
56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */,
56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */,
5605F1881C69111300235C62 /* StatementSelectionInfoTests.swift in Sources */,
5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */,
56176C6D1EACCCC9000F3F2B /* FTS5RecordTests.swift in Sources */,
569178491CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */,
562393761DEE104400A6B01F /* MapCursorTests.swift in Sources */,
@@ -2550,7 +2557,7 @@
5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */,
562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
56D496B61D813434008276D7 /* StatementSelectionInfoTests.swift in Sources */,
56D496B61D813434008276D7 /* DatabaseRegionTests.swift in Sources */,
562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */,
56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */,
56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */,
@@ -2606,6 +2613,7 @@
566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
56CEB4F11EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */,
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */,
+21
View File
@@ -215,6 +215,27 @@ extension Database {
schemaCache.set(foreignKeys: foreignKeys, forTable: tableName)
return foreignKeys
}
/// Returns the actual name of the database table
func canonicalName(table: String) throws -> String {
if let canonicalName = schemaCache.canonicalName(table: table) {
return canonicalName
}
guard let canonicalName = try String.fetchOne(self, """
SELECT name FROM (
SELECT name, type FROM sqlite_master
UNION
SELECT name, type FROM sqlite_temp_master)
WHERE type = 'table' AND LOWER(name) = ?
""", arguments: [table.lowercased()])
else {
throw DatabaseError(message: "no such table: \(table)")
}
schemaCache.set(canonicalName: canonicalName, forTable: table)
return canonicalName
}
}
extension Database {
+1 -1
View File
@@ -270,7 +270,7 @@ extension Database {
setupBusyMode()
setupDefaultFunctions()
setupDefaultCollations()
observationBroker.setup()
observationBroker.installCommitAndRollbackHooks()
}
private func setupTrace() {
+299
View File
@@ -0,0 +1,299 @@
/// DatabaseRegion defines a region in the database. DatabaseRegion is dedicated
/// to help transaction observers recognize impactful database changes in their
/// `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods.
///
/// A database region is the union of any number of "table regions", which can
/// cover a full table, or the combination of columns and rows (identified by
/// their rowids):
///
/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 |
/// |-------| |-------| |-------| |-------| |-------|
/// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | |
/// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | |
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
///
/// You don't create a database region directly. Instead, you use one of
/// those methods:
///
/// - `SelectStatement.fetchedRegion`:
///
/// let statement = db.makeSelectStatement("SELECT name, score FROM players")
/// print(statement.fetchedRegion)
/// // prints "players(name,score)"
///
/// - `Request.fetchedRegion(_:)`
///
/// let request = Player.filter(key: 1)
/// try print(request.fetchedRegion(db))
/// // prints "players(*)[1]"
///
/// Database regions returned by requests can be more precise than regions
/// returned by select statements. Especially, regions returned by statements
/// don't know about rowids:
///
/// // A plain statement
/// let statement = db.makeSelectStatement("SELECT * FROM players WHERE id = 1")
/// statement.fetchedRegion // "players(*)"
///
/// // A query interface request that executes the same statement:
/// let request = Player.filter(key: 1)
/// try request.fetchedRegion(db) // "players(*)[1]"
public struct DatabaseRegion {
private let tableRegions: [String: TableRegion]?
private init(tableRegions: [String: TableRegion]?) {
self.tableRegions = tableRegions
}
/// Returns whether the region is empty.
public var isEmpty: Bool {
guard let tableRegions = tableRegions else { return false }
return tableRegions.isEmpty
}
/// The full database: (All columns in all tables) × (all rows)
static let fullDatabase = DatabaseRegion(tableRegions: nil)
/// The empty database region
public init() {
self.init(tableRegions: [:])
}
/// A full table: (all columns in the table) × (all rows)
init(table: String) {
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
}
/// Full columns in a table: (some columns in a table) × (all rows)
init(table: String, columns: Set<String>) {
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)])
}
/// Full rows in a table: (all columns in a table) × (some rows)
init(table: String, rowIds: Set<Int64>) {
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)])
}
/// Returns the intersection of this region and the given one.
///
/// This method is not public because there is no known public use case for
/// this intersection. It is currently only used as support for
/// the isModified(byEventsOfKind:) method.
func intersection(_ other: DatabaseRegion) -> DatabaseRegion {
guard let tableRegions = tableRegions else { return other }
guard let otherTableRegions = other.tableRegions else { return self }
var tableRegionsIntersection: [String: TableRegion] = [:]
for (table, tableRegion) in tableRegions {
guard let otherTableRegion = otherTableRegions
.first(where: { (otherTable, _) in otherTable == table })?
.value else { continue }
let tableRegionIntersection = tableRegion.intersection(otherTableRegion)
guard !tableRegionIntersection.isEmpty else { continue }
tableRegionsIntersection[table] = tableRegionIntersection
}
return DatabaseRegion(tableRegions: tableRegionsIntersection)
}
/// Only keeps those rowIds in the given table
func tableIntersection(_ table: String, rowIds: Set<Int64>) -> DatabaseRegion {
guard var tableRegions = tableRegions else {
return DatabaseRegion(table: table, rowIds: rowIds)
}
guard let tableRegion = tableRegions[table] else {
return self
}
let intersection = tableRegion.intersection(TableRegion(columns: nil, rowIds: rowIds))
if intersection.isEmpty {
tableRegions.removeValue(forKey: table)
} else {
tableRegions[table] = intersection
}
return DatabaseRegion(tableRegions: tableRegions)
}
/// Returns the union of this region and the given one.
public func union(_ other: DatabaseRegion) -> DatabaseRegion {
guard let tableRegions = tableRegions else { return .fullDatabase }
guard let otherTableRegions = other.tableRegions else { return .fullDatabase }
var tableRegionsUnion: [String: TableRegion] = [:]
let tableNames = Set(tableRegions.map { $0.key }).union(Set(otherTableRegions.map { $0.key }))
for table in tableNames {
let tableRegion = tableRegions[table]
let otherTableRegion = otherTableRegions[table]
let tableRegionUnion: TableRegion
switch (tableRegion, otherTableRegion) {
case (nil, nil):
preconditionFailure()
case (nil, let tableRegion?), (let tableRegion?, nil):
tableRegionUnion = tableRegion
case (let tableRegion?, let otherTableRegion?):
tableRegionUnion = tableRegion.union(otherTableRegion)
}
tableRegionsUnion[table] = tableRegionUnion
}
return DatabaseRegion(tableRegions: tableRegionsUnion)
}
/// Inserts the given region into this region
public mutating func formUnion(_ other: DatabaseRegion) {
self = union(other)
}
}
extension DatabaseRegion {
// MARK: - Database Events
/// Returns whether the content in the region would be impacted if the
/// database were modified by an event of this kind.
public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool {
return !intersection(eventKind.modifiedRegion).isEmpty
}
/// Returns whether the content in the region is impacted by this event.
///
/// - precondition: event has been filtered by the same region
/// in the TransactionObserver.observes(eventsOfKind:) method, by calling
/// region.isModified(byEventsOfKind:)
public func isModified(by event: DatabaseEvent) -> Bool {
guard let tableRegions = tableRegions else {
return true
}
switch tableRegions.count {
case 1:
// The precondition applies here:
//
// The region contains a single table. Due to the
// filtering of events performed in observes(eventsOfKind:), the
// event argument is guaranteed to be about the fetched table.
// We thus only have to check for rowIds.
assert(event.tableName == tableRegions[tableRegions.startIndex].key) // sanity check
guard let rowIds = tableRegions[tableRegions.startIndex].value.rowIds else {
return true
}
return rowIds.contains(event.rowID)
default:
guard let tableRegion = tableRegions[event.tableName] else {
// Shouldn't happen if the precondition is met.
fatalError("precondition failure: event was not filtered out in observes(eventsOfKind:) by region.isModified(byEventsOfKind:)")
}
guard let rowIds = tableRegion.rowIds else {
return true
}
return rowIds.contains(event.rowID)
}
}
}
extension DatabaseRegion: Equatable {
public static func == (lhs: DatabaseRegion, rhs: DatabaseRegion) -> Bool {
switch (lhs.tableRegions, rhs.tableRegions) {
case (nil, nil):
return true
case (let ltableRegions?, let rtableRegions?):
let ltableNames = Set(ltableRegions.map { $0.key })
let rtableNames = Set(rtableRegions.map { $0.key })
guard ltableNames == rtableNames else {
return false
}
for tableName in ltableNames {
if ltableRegions[tableName]! != rtableRegions[tableName]! {
return false
}
}
return true
default:
return false
}
}
}
extension DatabaseRegion: CustomStringConvertible {
public var description: String {
guard let tableRegions = tableRegions else {
return "full database"
}
if tableRegions.isEmpty {
return "empty"
}
return tableRegions
.sorted(by: { (l, r) in l.key < r.key })
.map { (table, tableRegion) in
var desc = table
if let columns = tableRegion.columns {
desc += "(" + columns.sorted().joined(separator: ",") + ")"
} else {
desc += "(*)"
}
if let rowIds = tableRegion.rowIds {
desc += "[" + rowIds.sorted().map { "\($0)" }.joined(separator: ",") + "]"
}
return desc
}
.joined(separator: ",")
}
}
private struct TableRegion: Equatable {
var columns: Set<String>? // nil means "all columns"
var rowIds: Set<Int64>? // nil means "all rowids"
var isEmpty: Bool {
if let columns = columns, columns.isEmpty { return true }
if let rowIds = rowIds, rowIds.isEmpty { return true }
return false
}
static func == (lhs: TableRegion, rhs: TableRegion) -> Bool {
if lhs.columns != rhs.columns { return false }
if lhs.rowIds != rhs.rowIds { return false }
return true
}
func intersection(_ other: TableRegion) -> TableRegion {
let columnsIntersection: Set<String>?
switch (self.columns, other.columns) {
case (nil, let columns), (let columns, nil):
columnsIntersection = columns
case (let columns?, let other?):
columnsIntersection = columns.intersection(other)
}
let rowIdsIntersection: Set<Int64>?
switch (self.rowIds, other.rowIds) {
case (nil, let rowIds), (let rowIds, nil):
rowIdsIntersection = rowIds
case (let rowIds?, let other?):
rowIdsIntersection = rowIds.intersection(other)
}
return TableRegion(columns: columnsIntersection, rowIds: rowIdsIntersection)
}
func union(_ other: TableRegion) -> TableRegion {
let columnsUnion: Set<String>?
switch (self.columns, other.columns) {
case (nil, _), (_, nil):
columnsUnion = nil
case (let columns?, let other?):
columnsUnion = columns.union(other)
}
let rowIdsUnion: Set<Int64>?
switch (self.rowIds, other.rowIds) {
case (nil, _), (_, nil):
rowIdsUnion = nil
case (let rowIds?, let other?):
rowIdsUnion = rowIds.union(other)
}
return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion)
}
}
+20 -4
View File
@@ -2,6 +2,9 @@
protocol DatabaseSchemaCache {
mutating func clear()
func canonicalName(table: String) -> String?
mutating func set(canonicalName: String, forTable table: String)
func primaryKey(_ table: String) -> PrimaryKeyInfo?
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String)
@@ -17,18 +20,28 @@ protocol DatabaseSchemaCache {
/// A thread-unsafe database schema cache
struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
private var canonicalNames: [String: String] = [:]
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
private var columns: [String: [ColumnInfo]] = [:]
private var indexes: [String: [IndexInfo]] = [:]
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
mutating func clear() {
canonicalNames = [:]
primaryKeys = [:]
columns = [:]
indexes = [:]
foreignKeys = [:]
}
func canonicalName(table: String) -> String? {
return canonicalNames[table]
}
mutating func set(canonicalName: String, forTable table: String) {
canonicalNames[table] = table
}
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
return primaryKeys[table]
}
@@ -66,15 +79,18 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
struct EmptyDatabaseSchemaCache: DatabaseSchemaCache {
func clear() { }
func canonicalName(table: String) -> String? { return nil }
func set(canonicalName: String, forTable table: String) { }
func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil }
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
func columns(in table: String) -> [ColumnInfo]? { return nil }
mutating func set(columns: [ColumnInfo], forTable table: String) { }
func set(columns: [ColumnInfo], forTable table: String) { }
func indexes(on table: String) -> [IndexInfo]? { return nil }
mutating func set(indexes: [IndexInfo], forTable table: String) { }
func set(indexes: [IndexInfo], forTable table: String) { }
func foreignKeys(on table: String) -> [ForeignKeyInfo]? { return nil }
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { }
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { }
}
+65 -38
View File
@@ -22,6 +22,13 @@ public protocol Request {
///
/// - parameter db: A database connection.
func fetchCount(_ db: Database) throws -> Int
/// The database region that the request looks into.
///
/// This method has a default implementation.
///
/// - parameter db: A database connection.
func fetchedRegion(_ db: Database) throws -> DatabaseRegion
}
extension Request {
@@ -48,6 +55,14 @@ extension Request {
let (statement, adapter) = try prepare(db)
return SQLRequest(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached)
}
/// The database region that the request looks into.
///
/// - parameter db: A database connection.
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
let (statement, _) = try prepare(db)
return statement.fetchedRegion
}
}
extension Request {
@@ -65,7 +80,7 @@ extension Request {
/// - parameter type: The fetched type T
/// - returns: A typed request bound to type T.
public func asRequest<T>(of type: T.Type) -> AnyTypedRequest<T> {
return AnyTypedRequest { try self.prepare($0) }
return AnyTypedRequest(self)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -78,6 +93,9 @@ extension Request {
/// An adapted request.
public struct AdaptedRequest<Base: Request> : Request {
private let base: Base
private let adapter: (Database) throws -> RowAdapter
/// Creates an adapted request from a base request and a closure that builds
/// a row adapter from a database connection.
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
@@ -85,10 +103,6 @@ public struct AdaptedRequest<Base: Request> : Request {
self.adapter = adapter
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let (statement, baseAdapter) = try base.prepare(db)
if let baseAdapter = baseAdapter {
@@ -98,15 +112,13 @@ public struct AdaptedRequest<Base: Request> : Request {
}
}
/// The number of rows fetched by the request.
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
return try base.fetchCount(db)
}
private let base: Base
private let adapter: (Database) throws -> RowAdapter
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try base.fetchedRegion(db)
}
}
/// A type-erased Request.
@@ -114,26 +126,36 @@ public struct AdaptedRequest<Base: Request> : Request {
/// An instance of AnyRequest forwards its operations to an underlying request,
/// hiding its specifics.
public struct AnyRequest : Request {
private let base: Request
/// Creates a new request that wraps and forwards operations to `request`.
public init(_ request: Request) {
self._prepare = { try request.prepare($0) }
base = request
}
/// Creates a new request whose `prepare()` method wraps and forwards
/// operations the argument closure.
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
_prepare = prepare
struct PrepareRequest: Request {
let base: (Database) throws -> (SelectStatement, RowAdapter?)
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try base(db)
}
}
base = PrepareRequest(base: prepare)
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try _prepare(db)
return try base.prepare(db)
}
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
public func fetchCount(_ db: Database) throws -> Int {
return try base.fetchCount(db)
}
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try base.fetchedRegion(db)
}
}
/// A Request built from raw SQL.
@@ -239,32 +261,28 @@ extension TypedRequest {
/// An adapted typed request.
public struct AdaptedTypedRequest<Base: TypedRequest> : TypedRequest {
/// The type that can convert raw database rows to fetched values
public typealias RowDecoder = Base.RowDecoder
private let base: AdaptedRequest<Base>
/// Creates an adapted request from a base request and a closure that builds
/// a row adapter from a database connection.
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
adaptedRequest = AdaptedRequest(base, adapter)
self.base = AdaptedRequest(base, adapter)
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try adaptedRequest.prepare(db)
return try base.prepare(db)
}
/// The number of rows fetched by the request.
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
return try adaptedRequest.fetchCount(db)
return try base.fetchCount(db)
}
private let adaptedRequest: AdaptedRequest<Base>
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try base.fetchedRegion(db)
}
}
/// A type-erased TypedRequest.
@@ -274,27 +292,36 @@ public struct AdaptedTypedRequest<Base: TypedRequest> : TypedRequest {
public struct AnyTypedRequest<T> : TypedRequest {
/// The type that can convert raw database rows to fetched values
public typealias RowDecoder = T
private let base: Request
/// Support for Request.asRequest(of:)
/// Not public because not type-safe.
fileprivate init(_ request: Request) {
base = request
}
/// Creates a new request that wraps and forwards operations to `request`.
public init<Request>(_ request: Request) where Request: TypedRequest, Request.RowDecoder == RowDecoder {
self._prepare = { try request.prepare($0) }
base = request
}
/// Creates a new request whose `prepare()` method wraps and forwards
/// operations the argument closure.
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
_prepare = prepare
base = AnyRequest(prepare)
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try _prepare(db)
return try base.prepare(db)
}
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
public func fetchCount(_ db: Database) throws -> Int {
return try base.fetchCount(db)
}
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try base.fetchedRegion(db)
}
}
extension TypedRequest where RowDecoder: RowConvertible {
+14 -20
View File
@@ -738,7 +738,7 @@ extension Row : ExpressibleByDictionaryLiteral {
}
}
extension Row : Collection {
extension Row : RandomAccessCollection {
// MARK: - Row as a Collection of (ColumnName, DatabaseValue) Pairs
@@ -761,18 +761,6 @@ extension Row : Collection {
impl.columnName(atUncheckedIndex: index),
impl.databaseValue(atUncheckedIndex: index))
}
/// Returns the position immediately after `i`.
///
/// - Precondition: `(startIndex..<endIndex).contains(i)`
public func index(after i: RowIndex) -> RowIndex {
return RowIndex(i.index + 1)
}
/// Replaces `i` with its successor.
public func formIndex(after i: inout RowIndex) {
i = RowIndex(i.index + 1)
}
}
/// Row adopts Equatable.
@@ -789,10 +777,7 @@ extension Row : Equatable {
return false
}
var liter = lhs.makeIterator()
var riter = rhs.makeIterator()
while let (lcol, lval) = liter.next(), let (rcol, rval) = riter.next() {
for ((lcol, lval), (rcol, rval)) in zip(lhs, rhs) {
guard lcol == rcol else {
return false
}
@@ -842,22 +827,31 @@ extension Row: CustomStringConvertible {
// MARK: - RowIndex
/// Indexes to (columnName, dbValue) pairs in a database row.
/// Indexes to (ColumnName, DatabaseValue) pairs in a database row.
public struct RowIndex : Comparable {
let index: Int
init(_ index: Int) { self.index = index }
/// Equality operator
public static func == (lhs: RowIndex, rhs: RowIndex) -> Bool {
return lhs.index == rhs.index
}
// Comparison operator
public static func < (lhs: RowIndex, rhs: RowIndex) -> Bool {
return lhs.index < rhs.index
}
}
// Support for Row: RandomAccessCollection
extension RowIndex: Strideable {
public func distance(to other: RowIndex) -> Int {
return other.index - index
}
public func advanced(by n: Int) -> RowIndex {
return RowIndex(index + n)
}
}
// MARK: - RowImpl
+16 -14
View File
@@ -16,14 +16,15 @@ import Dispatch
/// of the dispatch queue, a SchedulingWatchdog that allows that database only.
///
/// Later on, the queue can be shared by several databases with the method
/// allowing(databases:execute:). See SerializedDatabase.sync() for
/// an example.
/// inheritingAllowedDatabases(from:execute:). See SerializedDatabase.sync()
/// for an example.
///
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
/// dispatch queue.
final class SchedulingWatchdog {
private static let specificKey = DispatchSpecificKey<SchedulingWatchdog>()
private(set) var allowedDatabases: [Database]
private var databaseObservationBroker: DatabaseObservationBroker?
private init(allowedDatabase database: Database) {
allowedDatabases = [database]
@@ -36,27 +37,28 @@ final class SchedulingWatchdog {
return queue
}
// Temporarily allows `databases` while executing `body`
func allowing<T>(databases: [Database], execute body: () throws -> T) rethrows -> T {
func inheritingAllowedDatabases<T>(from other: SchedulingWatchdog, execute body: () throws -> T) rethrows -> T {
let backup = allowedDatabases
allowedDatabases.append(contentsOf: databases)
allowedDatabases.append(contentsOf: other.allowedDatabases)
defer { allowedDatabases = backup }
return try body()
}
static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(allows(db), message, file: file, line: line)
}
static func allows(_ db: Database) -> Bool {
return current?.allows(db) ?? false
}
func allows(_ db: Database) -> Bool {
return allowedDatabases.contains { $0 === db }
GRDBPrecondition(current?.allows(db) ?? false, message, file: file, line: line)
}
static var current: SchedulingWatchdog? {
return DispatchQueue.getSpecific(key: specificKey)
}
static var currentDatabaseObservationBroker: DatabaseObservationBroker? {
get { return current?.databaseObservationBroker }
set { current!.databaseObservationBroker = newValue }
}
func allows(_ db: Database) -> Bool {
return allowedDatabases.contains { $0 === db }
}
}
+3 -3
View File
@@ -90,7 +90,7 @@ final class SerializedDatabase {
// Case 3
return try queue.sync {
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
try block(db)
}
}
@@ -136,7 +136,7 @@ final class SerializedDatabase {
// Case 3
return try queue.sync {
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
try block(db)
}
}
@@ -151,7 +151,7 @@ final class SerializedDatabase {
/// Returns true if any only if the current dispatch queue is valid.
var onValidQueue: Bool {
return SchedulingWatchdog.allows(db)
return SchedulingWatchdog.current?.allows(db) ?? false
}
/// Executes the block in the current queue.
+10 -78
View File
@@ -292,8 +292,14 @@ extension AuthorizedStatement {
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
/// }
public final class SelectStatement : Statement, AuthorizedStatement {
/// Information about the table and columns read by a SelectStatement
public private(set) var selectionInfo: SelectionInfo
@available(*, deprecated, renamed:"DatabaseRegion")
public typealias SelectionInfo = DatabaseRegion
@available(*, deprecated, renamed:"fetchedRegion")
public var selectionInfo: DatabaseRegion { return fetchedRegion }
/// The database region that the statement looks into.
public private(set) var fetchedRegion: DatabaseRegion
/// Creates a prepared statement.
///
@@ -314,7 +320,7 @@ public final class SelectStatement : Statement, AuthorizedStatement {
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
{
self.selectionInfo = SelectionInfo()
self.fetchedRegion = DatabaseRegion()
try super.init(
database: database,
statementStart: statementStart,
@@ -324,7 +330,7 @@ public final class SelectStatement : Statement, AuthorizedStatement {
GRDBPrecondition(authorizer.invalidatesDatabaseSchemaCache == false, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
GRDBPrecondition(authorizer.transactionEffect == nil, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
self.selectionInfo = authorizer.selectionInfo
self.fetchedRegion = authorizer.region
}
/// The number of columns in the resulting rows.
@@ -364,68 +370,6 @@ public final class SelectStatement : Statement, AuthorizedStatement {
prepare(withArguments: arguments)
reset()
}
/// Information about the table and columns read by a SelectStatement
public struct SelectionInfo : CustomStringConvertible {
/// Selection is unknown when a statement uses the COUNT function,
/// and SQLite version < 3.19:
///
/// `SELECT COUNT(*) FROM t1` -> unknown selection
private let isUnknown: Bool
/// `SELECT a, b FROM t1` -> ["t1": ["a", "b"]]
private var columns: [String: Set<String>] = [:]
/// `SELECT COUNT(*) FROM t1` -> ["t1"]
private var tables: Set<String> = []
/// The unknown selection
static let unknown = SelectionInfo(isUnknown: true)
mutating func insert(allColumnsOfTable table: String) {
tables.insert(table)
}
mutating func insert(column: String, ofTable table: String) {
columns[table, default: []].insert(column)
}
/// Returns true if isUnknown is true
func contains(anyColumnFrom table: String) -> Bool {
if isUnknown { return true }
return tables.contains(table) || columns.index(forKey: table) != nil
}
/// Returns true if isUnknown is true
func contains(anyColumnIn columns: Set<String>, from table: String) -> Bool {
if isUnknown { return true }
return tables.contains(table) || !(self.columns[table]?.isDisjoint(with: columns) ?? true)
}
init() {
self.init(isUnknown: false)
}
private init(isUnknown: Bool) {
self.isUnknown = isUnknown
}
public var description: String {
if isUnknown {
return "unknown"
}
return tables.union(columns.keys)
.sorted()
.map { table -> String in
if let columns = columns[table] {
return "\(table)(\(columns.sorted().joined(separator: ",")))"
} else {
return "\(table)(*)"
}
}
.joined(separator: ",")
}
}
}
/// A cursor that iterates a database statement without producing any value.
@@ -489,10 +433,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
/// is executed.
private(set) var invalidatesDatabaseSchemaCache: Bool
/// If true, the statement needs support from TruncateOptimizationBlocker
/// when executed
private(set) var needsTruncateOptimizationPreventionDuringExecution: Bool
private(set) var transactionEffect: TransactionEffect?
private(set) var databaseEventKinds: [DatabaseEventKind]
@@ -516,7 +456,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
authorizer: StatementCompilationAuthorizer) throws
{
self.invalidatesDatabaseSchemaCache = false
self.needsTruncateOptimizationPreventionDuringExecution = false
self.databaseEventKinds = []
try super.init(
database: database,
@@ -524,7 +463,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
statementEnd: statementEnd,
prepFlags: prepFlags)
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
self.needsTruncateOptimizationPreventionDuringExecution = authorizer.needsTruncateOptimizationPreventionDuringExecution
self.transactionEffect = authorizer.transactionEffect
self.databaseEventKinds = authorizer.databaseEventKinds
}
@@ -539,10 +477,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
reset()
database.updateStatementWillExecute(self)
if needsTruncateOptimizationPreventionDuringExecution {
database.authorizer = TruncateOptimizationBlocker()
}
while true {
switch sqlite3_step(sqliteStatement) {
case SQLITE_ROW:
@@ -565,12 +499,10 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
continue
case SQLITE_DONE:
database.authorizer = nil
try database.updateStatementDidExecute(self)
return
case let code:
database.authorizer = nil
try database.updateStatementDidFail(self)
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
}
+15 -16
View File
@@ -18,7 +18,7 @@ protocol StatementAuthorizer : class {
/// A class that gathers information about one statement during its compilation.
final class StatementCompilationAuthorizer : StatementAuthorizer {
/// What this statements reads
var selectionInfo = SelectStatement.SelectionInfo()
var region = DatabaseRegion()
/// What this statements writes
var databaseEventKinds: [DatabaseEventKind] = []
@@ -32,9 +32,6 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
/// savepoint statement.
var transactionEffect: UpdateStatement.TransactionEffect?
/// True if statement may trigger the truncate optimization
var needsTruncateOptimizationPreventionDuringExecution = false
private var isDropStatement = false
func authorize(
@@ -69,10 +66,10 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
if columnName.isEmpty {
// SELECT COUNT(*) FROM table
selectionInfo.insert(allColumnsOfTable: tableName)
region.formUnion(DatabaseRegion(table: tableName))
} else {
// SELECT column FROM table
selectionInfo.insert(column: columnName, ofTable: tableName)
region.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
}
return SQLITE_OK
@@ -84,12 +81,17 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
case SQLITE_DELETE:
if isDropStatement { return SQLITE_OK }
guard let cString1 = cString1 else { return SQLITE_OK }
// Deletions from sqlite_master and sqlite_temp_master are not like
// other deletions: the update hook does not notify them, and they
// are prevented when the truncate optimization is disabled.
// Let's authorize such deletions by returning SQLITE_OK:
guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK }
guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK }
// Now we prevent the truncate optimization so that transaction
// observers are notified of individual row deletions.
databaseEventKinds.append(.delete(tableName: String(cString: cString1)))
// Prevent the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
// See also TruncateOptimizationBlocker
needsTruncateOptimizationPreventionDuringExecution = true
return SQLITE_IGNORE
case SQLITE_UPDATE:
@@ -129,11 +131,11 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
// Before SQLite 3.19.0, `SELECT COUNT(*) FROM table` does not
// trigger any authorization callback that tells about the
// counted table: any use of the COUNT function makes the
// selection undetermined.
// region undetermined (the full database).
guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK }
guard let cString2 = cString2 else { return SQLITE_OK }
if sqlite3_stricmp(cString2, "COUNT") == 0 {
selectionInfo = .unknown
region = .fullDatabase
}
return SQLITE_OK
@@ -159,11 +161,8 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
/// which makes transaction observers unable to observe individual deletions
/// when user runs `DELETE FROM t` statements.
//
/// Warning: to perform well, this authorizer requires that:
//
/// - It is used during statement execution, not during statement compilation.
/// - Statement compilation was authorized with a StatementCompilationAuthorizer
/// that has set its needsTruncateOptimizationPreventionDuringExecution flag.
/// Warning: to perform well, this authorizer must be used during statement
/// execution, not during statement compilation.
final class TruncateOptimizationBlocker : StatementAuthorizer {
func authorize(
_ actionCode: Int32,
+351 -123
View File
@@ -51,11 +51,7 @@ extension Database {
// Ignore individual changes and transaction rollbacks
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false }
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
func databaseDidChange(with event: DatabaseEvent) { }
func databaseWillCommit() throws { }
func databaseDidRollback(_ db: Database) { }
// On commit, run closure
@@ -80,6 +76,8 @@ extension Database {
}
}
// MARK: - DatabaseObservationBroker
/// This class provides support for transaction observers.
///
/// Let's have a detailed look at how a transaction observer is notified:
@@ -163,73 +161,136 @@ extension Database {
/// After the statement *has been executed*, the broker calls
/// observer.databaseDidCommit().
class DatabaseObservationBroker {
unowned var database: Database
var savepointStack = SavepointStack()
var transactionState: TransactionState = .none
var transactionObservations = [TransactionObservation]()
var activeTransactionObservations = [TransactionObservation]()
private unowned var database: Database
private var savepointStack = SavepointStack()
private var transactionState: TransactionState = .none
private var transactionObservations: [TransactionObservation] = []
private var statementObservations: [StatementObservation] = [] {
didSet { observesDatabaseChanges = !statementObservations.isEmpty }
}
private var observesDatabaseChanges: Bool = false {
didSet {
if observesDatabaseChanges == oldValue { return }
if observesDatabaseChanges {
installUpdateHook()
} else {
uninstallUpdateHook()
}
}
}
init(_ database: Database) {
self.database = database
}
func setup() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
do {
try broker.databaseWillCommit()
broker.transactionState = .commit
// Next step: updateStatementDidExecute()
return 0
} catch {
broker.transactionState = .cancelledCommit(error)
// Next step: sqlite3_rollback_hook callback
return 1
}
}, brokerPointer)
sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
switch broker.transactionState {
case .cancelledCommit:
// Next step: updateStatementDidFail()
break
default:
broker.transactionState = .rollback
// Next step: updateStatementDidExecute()
}
}, brokerPointer)
}
// MARK: - Transaction observers
func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent) {
transactionObservations.append(TransactionObservation(observer: transactionObserver, extent: extent))
if transactionObservations.count == 1 {
installUpdateHook()
}
}
func remove(transactionObserver: TransactionObserver) {
transactionObservations.removeFirst { $0.isWrapping(transactionObserver) }
if transactionObservations.isEmpty {
uninstallUpdateHook()
}
func disableUntilNextTransaction(transactionObserver: TransactionObserver) {
if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver)}) {
observation.isDisabled = true
statementObservations.removeFirst { $0.0 === observation }
}
}
// MARK: - Statement execution
func updateStatementWillExecute(_ statement: UpdateStatement) {
// Activate the transaction observers that are interested in the actions
// performed by the statement.
let databaseEventKinds = statement.databaseEventKinds
activeTransactionObservations = transactionObservations.filter { observer in
return databaseEventKinds.contains(where: observer.observes)
// Transaction observers may disable themselves during statement
// execution: see TransactionObserver.stopObservingDatabaseChangesUntilNextTransaction()
//
// This convenient method uses cooperation from SchedulingWatchdog in
// order to access the broker that is executing a database statement in
// the current thread.
SchedulingWatchdog.currentDatabaseObservationBroker = self
// Fill statementObservations with observations that are interested in
// the kind of events performed by the statement.
//
// Those statementObservations will be notified of individual changes
// in databaseWillChange() and databaseDidChange().
let eventKinds = statement.databaseEventKinds
// If any observer observes row deletions, we'll have to disable
// [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
// so that observers are notified.
var observesRowDeletion = false
switch eventKinds.count {
case 0:
// Statement has no effect on any database table.
//
// For example: PRAGMA foreign_keys = ON
statementObservations = []
case 1:
// We'll execute a simple statement without any side effect.
// Eventual database events will thus all have the same kind. All
// detabase events can be notified to interested observations.
//
// For example, if one observes all deletions in the table T, then
// all individual deletions of DELETE FROM T are notified:
let eventKind = eventKinds[0]
statementObservations = transactionObservations.flatMap { observation in
guard observation.observes(eventsOfKind: eventKind) else {
// observation is not interested
return nil
}
if case .delete = eventKind {
observesRowDeletion = true
}
// observation will be notified of all individual events
return (observation, DatabaseEventPredicate.true)
}
default:
// We'll execute a complex statement with side effects performed by
// an SQL trigger or a foreign key action. Eventual database events
// may not all have the same kind: we need to filter them before
// notifying interested observations.
//
// For example, if DELETE FROM T1 generates deletions in T1 and T2
// by the mean of a foreign key action, then when one only observes
// deletions in T1, one must not be notified of deletions in T2:
statementObservations = transactionObservations.flatMap { observation in
let observedKinds = eventKinds.filter(observation.observes)
if observedKinds.isEmpty {
// observation is not interested
return nil
}
for eventKind in observedKinds {
if case .delete = eventKind {
observesRowDeletion = true
break
}
}
// observation will only be notified of individual events that
// match one of the observed kinds.
return (observation, DatabaseEventPredicate.matching(observedKinds))
}
}
if observesRowDeletion {
database.authorizer = TruncateOptimizationBlocker()
} else {
database.authorizer = nil
}
}
func updateStatementDidFail(_ statement: UpdateStatement) throws {
// Wait for next statement
activeTransactionObservations = []
// Undo updateStatementWillExecute
statementObservations = []
SchedulingWatchdog.currentDatabaseObservationBroker = nil
database.authorizer = nil
// Reset transactionState before databaseDidRollback eventually
// executes other statements.
@@ -251,9 +312,11 @@ class DatabaseObservationBroker {
}
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
// Wait for next statement
activeTransactionObservations = []
// Undo updateStatementWillExecute
statementObservations = []
SchedulingWatchdog.currentDatabaseObservationBroker = nil
database.authorizer = nil
// Has statement any effect on transaction/savepoints?
if let transactionEffect = statement.transactionEffect {
switch transactionEffect {
@@ -267,7 +330,7 @@ class DatabaseObservationBroker {
// BEGIN DEFERRED TRANSACTION; COMMIT
//
// This special case has a dedicated handling:
return try emptyDeferredTransactionDidCommit()
return try databaseDidCommitEmptyDeferredTransaction()
}
case .rollbackTransaction:
@@ -287,7 +350,7 @@ class DatabaseObservationBroker {
// SAVEPOINT foo; RELEASE SAVEPOINT foo
//
// This special case has a dedicated handling:
return try emptyDeferredTransactionDidCommit()
return try databaseDidCommitEmptyDeferredTransaction()
}
if savepointStack.isEmpty {
@@ -319,30 +382,38 @@ class DatabaseObservationBroker {
private func databaseWillChange(with event: DatabasePreUpdateEvent) {
if savepointStack.isEmpty {
// Notify now
for observation in activeTransactionObservations {
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
observation.databaseWillChange(with: event)
}
} else {
// Buffer
savepointStack.eventsBuffer.append((event: event.copy(), observations: activeTransactionObservations))
savepointStack.eventsBuffer.append((event: event.copy(), statementObservations: statementObservations))
}
}
#endif
// Called from sqlite3_update_hook
private func databaseDidChange(with event: DatabaseEvent) {
// We're about to call the databaseDidChange(with:) method of observers
// In this method, observers can call stopObservingDatabaseChangesUntilNextTransaction()
// which requires SchedulingWatchdog.currentDatabaseObservationBroker
// not to be nil. This is time for an assertion!
assert(SchedulingWatchdog.currentDatabaseObservationBroker != nil)
if savepointStack.isEmpty {
// Notify now
for observation in activeTransactionObservations {
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
observation.databaseDidChange(with: event)
}
} else {
// Buffer
savepointStack.eventsBuffer.append((event: event.copy(), observations: activeTransactionObservations))
savepointStack.eventsBuffer.append((event: event.copy(), statementObservations: statementObservations))
}
}
// Called from sqlite3_commit_hook and emptyDeferredTransactionDidCommit()
// MARK: - End of transaction
// Called from sqlite3_commit_hook and databaseDidCommitEmptyDeferredTransaction()
private func databaseWillCommit() throws {
notifyBufferedEvents()
for observation in transactionObservations {
@@ -350,17 +421,6 @@ class DatabaseObservationBroker {
}
}
private func notifyBufferedEvents() {
let eventsBuffer = savepointStack.eventsBuffer
savepointStack.clear()
for (event, observations) in eventsBuffer {
for observation in observations {
event.send(to: observation)
}
}
}
// Called from updateStatementDidExecute
private func databaseDidCommit() {
savepointStack.clear()
@@ -368,11 +428,11 @@ class DatabaseObservationBroker {
for observation in transactionObservations {
observation.databaseDidCommit(database)
}
cleanupTransactionObservations()
databaseDidEndTransaction()
}
// Called from updateStatementDidExecute
private func emptyDeferredTransactionDidCommit() throws {
private func databaseDidCommitEmptyDeferredTransaction() throws {
// A statement that ends a transaction has been executed. But for
// SQLite, no transaction at all has started, and sqlite3_commit_hook
// was not triggered:
@@ -404,6 +464,13 @@ class DatabaseObservationBroker {
// even if we actually execute an empty deferred transaction.
//
// For better or for worse, let's simulate a transaction:
// FIXME: clean up currentDatabaseObservationBroker management
SchedulingWatchdog.currentDatabaseObservationBroker = self
defer {
SchedulingWatchdog.currentDatabaseObservationBroker = nil
}
do {
try databaseWillCommit()
databaseDidCommit()
@@ -422,11 +489,78 @@ class DatabaseObservationBroker {
observation.databaseDidRollback(database)
}
}
cleanupTransactionObservations()
databaseDidEndTransaction()
}
/// Remove transaction observers that have stopped observing transaction,
/// and uninstall SQLite update hooks if there is no remaining observers.
private func databaseDidEndTransaction() {
transactionObservations = transactionObservations.filter { $0.isObserving }
// Undo disableUntilNextTransaction(transactionObserver:)
for observation in transactionObservations {
observation.isDisabled = false
}
}
private func notifyBufferedEvents() {
// FIXME: clean up currentDatabaseObservationBroker management
SchedulingWatchdog.currentDatabaseObservationBroker = self
defer {
SchedulingWatchdog.currentDatabaseObservationBroker = nil
}
// We're about to call the databaseDidChange(with:) method of observers
// In this method, observers can call stopObservingDatabaseChangesUntilNextTransaction()
// which requires SchedulingWatchdog.currentDatabaseObservationBroker
// not to be nil. This is time for an assertion!
assert(SchedulingWatchdog.currentDatabaseObservationBroker != nil)
let eventsBuffer = savepointStack.eventsBuffer
savepointStack.clear()
for (event, statementObservations) in eventsBuffer {
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
event.send(to: observation)
}
}
}
// MARK: - SQLite hooks
func installCommitAndRollbackHooks() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
do {
try broker.databaseWillCommit()
broker.transactionState = .commit
// Next step: updateStatementDidExecute()
return 0
} catch {
broker.transactionState = .cancelledCommit(error)
// Next step: sqlite3_rollback_hook callback
return 1
}
}, brokerPointer)
sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
switch broker.transactionState {
case .cancelledCommit:
// Next step: updateStatementDidFail()
break
default:
broker.transactionState = .rollback
// Next step: updateStatementDidExecute()
}
}, brokerPointer)
}
private func installUpdateHook() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_update_hook(database.sqliteConnection, { (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
broker.databaseDidChange(with: DatabaseEvent(
@@ -457,16 +591,7 @@ class DatabaseObservationBroker {
#endif
}
/// Remove transaction observers that have stopped observing transaction,
/// and uninstall SQLite update hooks if there is no remaining observers.
private func cleanupTransactionObservations() {
transactionObservations = transactionObservations.filter { $0.isObserving }
if transactionObservations.isEmpty {
uninstallUpdateHook()
}
}
/// The states that keep track of transaction completions
/// The various states of SQLite transactions
enum TransactionState {
case none
case commit
@@ -475,6 +600,8 @@ class DatabaseObservationBroker {
}
}
// MARK: - TransactionObserver
/// A transaction observer is notified of all changes and transactions committed
/// or rollbacked on a database.
///
@@ -487,13 +614,18 @@ public protocol TransactionObserver : class {
/// Notifies a database change (insert, update, or delete).
///
/// The change is pending until the end of the current transaction, notified
/// to databaseWillCommit, databaseDidCommit and databaseDidRollback.
/// The change is pending until the current transaction ends. See
/// databaseWillCommit, databaseDidCommit and databaseDidRollback.
///
/// This method is called on the database queue.
/// This method is called in a protected dispatch queue, serialized will all
/// database updates.
///
/// The event is only valid for the duration of this method call. If you
/// need to keep it longer, store a copy of its properties.
/// need to keep it longer, store a copy: `event.copy()`
///
/// The observer has an opportunity to stop receiving further change events
/// from the current transaction by calling the
/// stopObservingDatabaseChangesUntilNextTransaction() method.
///
/// - warning: this method must not change the database.
func databaseDidChange(with event: DatabaseEvent)
@@ -530,34 +662,80 @@ public protocol TransactionObserver : class {
/// This callback is mostly useful for calculating detailed change
/// information for a row, and provides the initial / final values.
///
/// This method is called on the database queue.
/// This method is called in a protected dispatch queue, serialized will all
/// database updates.
///
/// The event is only valid for the duration of this method call. If you
/// need to keep it longer, store a copy of its properties.
/// need to keep it longer, store a copy: `event.copy()`
///
/// - warning: this method must not change the database.
///
/// Availability Info:
/// **Availability Info**
///
/// Requires SQLite 3.13.0 +
/// Compiled with option SQLITE_ENABLE_PREUPDATE_HOOK
/// Requires SQLite 3.13.0 +
/// Compiled with option SQLITE_ENABLE_PREUPDATE_HOOK
///
/// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library
/// does not have this enabled, so you'll need to compile your own
/// copy using GRDBCustomSQLite. See the README.md in /SQLiteCustom/
///
/// The databaseDidChangeWithEvent callback is always available,
/// and may provide most/all of what you need.
/// (For example, FetchedRecordsController is built without using
/// this functionality.)
/// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library
/// does not have this enabled, so you'll need to compile your own
/// copy using GRDBCustomSQLite. See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md
///
/// The databaseDidChangeWithEvent callback is always available,
/// and may provide most/all of what you need.
/// (For example, FetchedRecordsController is built without databaseWillChange)
func databaseWillChange(with event: DatabasePreUpdateEvent)
#endif
}
extension TransactionObserver {
/// Default implementation does nothing
public func databaseWillCommit() throws {
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
/// Default implementation does nothing
public func databaseWillChange(with event: DatabasePreUpdateEvent) {
}
#endif
/// After this method has been called, the `databaseDidChange(with:)`
/// method won't be called until the next transaction.
///
/// For example:
///
/// class PlayerObserver: TransactionObserver {
/// var playersTableWasModified = false
///
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
/// return eventKind.tableName == "players"
/// }
///
/// func databaseDidChange(with event: DatabaseEvent) {
/// playersTableWasModified = true
///
/// // It is pointless to keep on tracking further changes:
/// stopObservingDatabaseChangesUntilNextTransaction()
/// }
/// }
///
/// - precondition: This method must be called from `databaseDidChange(with:)`.
public func stopObservingDatabaseChangesUntilNextTransaction() {
guard let broker = SchedulingWatchdog.currentDatabaseObservationBroker else {
fatalError("stopObservingDatabaseChangesUntilNextTransaction must be called from the databaseDidChange method")
}
broker.disableUntilNextTransaction(transactionObserver: self)
}
}
// MARK: - TransactionObservation
/// This class manages the observation extent of a transaction observer
final class TransactionObservation {
let extent: Database.TransactionObservationExtent
// A disabled observation is not interested in individual database changes.
// It is still interested in transactions commits & rollbacks.
var isDisabled: Bool = false
private weak var weakObserver: TransactionObserver?
private var strongObserver: TransactionObserver?
private var observer: TransactionObserver? { return strongObserver ?? weakObserver }
@@ -584,10 +762,19 @@ final class TransactionObservation {
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
if isDisabled { return false }
return observer?.observes(eventsOfKind: eventKind) ?? false
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) {
if isDisabled { return }
observer?.databaseWillChange(with: event)
}
#endif
func databaseDidChange(with event: DatabaseEvent) {
if isDisabled { return }
observer?.databaseDidChange(with: event)
}
@@ -601,7 +788,7 @@ final class TransactionObservation {
observer?.databaseDidCommit(db)
case .nextTransaction:
if let observer = self.observer {
// Observer most not get any further notification.
// Observer must not get any further notification.
// So we "forget" the observer before its `databaseDidCommit`
// implementation eventually triggers another database change.
strongObserver = nil
@@ -616,7 +803,7 @@ final class TransactionObservation {
observer?.databaseDidRollback(db)
case .nextTransaction:
if let observer = self.observer {
// Observer most not get any further notification.
// Observer must not get any further notification.
// So we "forget" the observer before its `databaseDidRollback`
// implementation eventually triggers another database change.
strongObserver = nil
@@ -624,16 +811,14 @@ final class TransactionObservation {
}
}
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) {
observer?.databaseWillChange(with: event)
}
#endif
}
/// A kind of database event. See Database.add(transactionObserver:)
/// and DatabaseWriter.add(transactionObserver:).
typealias StatementObservation = (TransactionObservation, DatabaseEventPredicate)
// MARK: - Database events
/// A kind of database event. See the TransactionObserver protocol for
/// more information.
public enum DatabaseEventKind {
/// The insertion of a row in a database table
case insert(tableName: String)
@@ -644,19 +829,21 @@ public enum DatabaseEventKind {
/// The update of a set of columns in a database table
case update(tableName: String, columnNames: Set<String>)
/// Returns whether event has any impact on tables and columns described
/// by selectionInfo.
public func impacts(_ selectionInfo: SelectStatement.SelectionInfo) -> Bool {
var modifiedRegion: DatabaseRegion {
switch self {
case .delete(let tableName):
return selectionInfo.contains(anyColumnFrom: tableName)
return DatabaseRegion(table: tableName)
case .insert(let tableName):
return selectionInfo.contains(anyColumnFrom: tableName)
return DatabaseRegion(table: tableName)
case .update(let tableName, let updatedColumnNames):
return selectionInfo.contains(anyColumnIn: updatedColumnNames, from: tableName)
return DatabaseRegion(table: tableName, columns: updatedColumnNames)
}
}
@available(*, deprecated, message: "Use DatabaseRegion.isModified(byEventsOfKind:) instead")
public func impacts(_ region: DatabaseRegion) -> Bool {
return region.isModified(byEventsOfKind: self)
}
}
extension DatabaseEventKind {
@@ -672,6 +859,7 @@ extension DatabaseEventKind {
protocol DatabaseEventProtocol {
func send(to observer: TransactionObservation)
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool
}
/// A database event, notified to TransactionObserver.
@@ -689,6 +877,8 @@ public struct DatabaseEvent {
case update = 23
}
private let impl: DatabaseEventImpl
/// The event kind
public let kind: Kind
@@ -722,14 +912,22 @@ public struct DatabaseEvent {
init(kind: Kind, rowID: Int64, databaseNameCString: UnsafePointer<Int8>?, tableNameCString: UnsafePointer<Int8>?) {
self.init(kind: kind, rowID: rowID, impl: MetalDatabaseEventImpl(databaseNameCString: databaseNameCString, tableNameCString: tableNameCString))
}
private let impl: DatabaseEventImpl
}
extension DatabaseEvent : DatabaseEventProtocol {
func send(to observer: TransactionObservation) {
observer.databaseDidChange(with: self)
}
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool {
switch (kind, databaseEventKind) {
case (.insert, .insert(let tableName)): return self.tableName == tableName
case (.delete, .delete(let tableName)): return self.tableName == tableName
case (.update, .update(let tableName, _)): return self.tableName == tableName
default:
return false
}
}
}
/// Protocol for internal implementation of DatabaseEvent
@@ -883,6 +1081,16 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
func send(to observer: TransactionObservation) {
observer.databaseWillChange(with: self)
}
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool {
switch (kind, databaseEventKind) {
case (.insert, .insert(let tableName)): return self.tableName == tableName
case (.delete, .delete(let tableName)): return self.tableName == tableName
case (.update, .update(let tableName, _)): return self.tableName == tableName
default:
return false
}
}
}
/// Protocol for internal implementation of DatabaseEvent
@@ -1008,6 +1216,25 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
#endif
// A predicate that filters database events
enum DatabaseEventPredicate {
// Yes filter
case `true`
// Only events that match one of those kinds
case matching([DatabaseEventKind])
func evaluate(_ event: DatabaseEventProtocol) -> Bool {
switch self {
case .true:
return true
case .matching(let kinds):
return kinds.contains { event.matchesKind($0) }
}
}
}
// MARK: - SavepointStack
/// The SQLite savepoint stack is described at
/// https://www.sqlite.org/lang_savepoint.html
///
@@ -1018,8 +1245,8 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
/// notifying transaction observers of database events that could be
/// rollbacked.
class SavepointStack {
/// The buffered events. See Database.didChange(with:)
var eventsBuffer: [(event: DatabaseEventProtocol, observations: [TransactionObservation])] = []
/// The buffered events (see DatabaseObservationBroker.databaseDidChange(with:))
var eventsBuffer: [(event: DatabaseEventProtocol, statementObservations: [StatementObservation])] = []
/// The savepoint stack, as an array of tuples (savepointName, index in the eventsBuffer array).
/// Indexes let us drop rollbacked events from the event buffer.
@@ -1072,3 +1299,4 @@ class SavepointStack {
}
}
}
+185 -7
View File
@@ -26,6 +26,11 @@ extension QueryInterfaceRequest : TypedRequest {
public func fetchCount(_ db: Database) throws -> Int {
return try query.fetchCount(db)
}
/// The database region that the request looks into.
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try query.fetchedRegion(db)
}
}
extension QueryInterfaceRequest {
@@ -104,13 +109,13 @@ extension QueryInterfaceRequest {
/// var request = Player.all()
/// request = request.filter(Column("email") == "arthur@example.com")
public func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<T> {
var query = self.query
if let whereExpression = query.whereExpression {
query.whereExpression = whereExpression && predicate.sqlExpression
} else {
query.whereExpression = predicate.sqlExpression
}
return QueryInterfaceRequest(query: query)
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
if let expression = expression {
return expression && predicate.sqlExpression
} else {
return predicate.sqlExpression
}
})
}
/// A new QueryInterfaceRequest with the provided *predicate* added to the
@@ -235,6 +240,125 @@ extension QueryInterfaceRequest {
}
}
extension QueryInterfaceRequest where T: TableMapping {
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM players WHERE id = 1
/// var request = Player.all()
/// request = request.filter(key: 1)
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<T> {
guard let key = key else {
return T.none()
}
return filter(keys: [key])
}
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM players WHERE id IN (1, 2, 3)
/// var request = Player.all()
/// request = request.filter(keys: [1, 2, 3])
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<T> where Sequence.Element: DatabaseValueConvertible {
let keys = Array(keys)
let makePredicate: (Column) -> SQLExpression
switch keys.count {
case 0:
return T.none()
case 1:
makePredicate = { $0 == keys[0] }
default:
makePredicate = { keys.contains($0) }
}
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
let primaryKey = try db.primaryKey(T.databaseTableName)
GRDBPrecondition(primaryKey.columns.count == 1, "Requesting by key requires a single-column primary key in the table \(T.databaseTableName)")
let keysPredicate = makePredicate(Column(primaryKey.columns[0]))
if let expression = expression {
return expression && keysPredicate
} else {
return keysPredicate
}
})
}
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR'
/// var request = Player.all()
/// request = request.filter(key: ["personId": 1, "countryCode": "FR"])
///
/// When executed, this request raises a fatal error if there is no unique
/// index on the key columns.
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<T> {
guard let key = key else {
return T.none()
}
return filter(keys: [key])
}
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ...
/// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...])
///
/// When executed, this request raises a fatal error if there is no unique
/// index on the key columns.
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<T> {
guard !keys.isEmpty else {
return T.none()
}
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
let keyPredicates: [SQLExpression] = try keys.map { key in
// Prevent filter(db, keys: [[:]])
GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary")
// Prevent filter(keys: [["foo": 1, "bar": 2]]) where
// ("foo", "bar") is not a unique key (primary key or columns of a
// unique index)
guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: T.databaseTableName) else {
fatalError("table \(T.databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))")
}
let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() }
let columnPredicates: [SQLExpression] = key
// Sort key columns in the same order as the unique index
.sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! }
.map { (column, value) in Column(column) == value }
return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty
}
let keysPredicate = SQLBinaryOperator.or.join(keyPredicates)! // not nil because keyPredicates is not empty
if let expression = expression {
return expression && keysPredicate
} else {
return keysPredicate
}
})
}
}
extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
// MARK: Deleting
@@ -308,6 +432,60 @@ extension TableMapping {
return all().filter(predicate)
}
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM players WHERE id = 1
/// let request = Player.filter(key: 1)
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public static func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<Self> {
return all().filter(key: key)
}
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM players WHERE id IN (1, 2, 3)
/// let request = Player.filter(keys: [1, 2, 3])
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public static func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible {
return all().filter(keys: keys)
}
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR'
/// let request = Passport.filter(key: ["personId": 1, "countryCode": "FR"])
///
/// When executed, this request raises a fatal error if there is no unique
/// index on the key columns.
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<Self> {
return all().filter(key: key)
}
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ...
/// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...])
///
/// When executed, this request raises a fatal error if there is no unique
/// index on the key columns.
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<Self> {
return all().filter(keys: keys)
}
/// Creates a QueryInterfaceRequest with the provided *predicate*.
///
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
@@ -1,10 +1,28 @@
// MARK: - QueryInterfaceSelectQueryDefinition
struct DatabasePromise<T> {
let resolve: (Database) throws -> T
init(value: T) {
self.resolve = { _ in value }
}
init(_ resolve: @escaping (Database) throws -> T) {
self.resolve = resolve
}
func map(_ transform: @escaping (Database, T) throws -> T) -> DatabasePromise {
return DatabasePromise { db in
try transform(db, self.resolve(db))
}
}
}
struct QueryInterfaceSelectQueryDefinition {
var selection: [SQLSelectable]
var isDistinct: Bool
var source: SQLSource?
var whereExpression: SQLExpression?
var wherePromise: DatabasePromise<SQLExpression?>
var groupByExpressions: [SQLExpression]
var orderings: [SQLOrderingTerm]
var isReversed: Bool
@@ -25,7 +43,7 @@ struct QueryInterfaceSelectQueryDefinition {
self.selection = selection
self.isDistinct = isDistinct
self.source = source
self.whereExpression = whereExpression
self.wherePromise = DatabasePromise(value: whereExpression)
self.groupByExpressions = groupByExpressions
self.orderings = orderings
self.isReversed = isReversed
@@ -33,7 +51,13 @@ struct QueryInterfaceSelectQueryDefinition {
self.limit = limit
}
func sql(_ arguments: inout StatementArguments?) -> String {
func mapWhereExpression(_ transform: @escaping (Database, SQLExpression?) throws -> SQLExpression?) -> QueryInterfaceSelectQueryDefinition {
var query = self
query.wherePromise = query.wherePromise.map(transform)
return query
}
func sql(_ db: Database, _ arguments: inout StatementArguments?) throws -> String {
var sql = "SELECT"
if isDistinct {
@@ -44,10 +68,10 @@ struct QueryInterfaceSelectQueryDefinition {
sql += " " + selection.map { $0.resultColumnSQL(&arguments) }.joined(separator: ", ")
if let source = source {
sql += " FROM " + source.sourceSQL(&arguments)
sql += try " FROM " + source.sourceSQL(db, &arguments)
}
if let whereExpression = whereExpression {
if let whereExpression = try wherePromise.resolve(db) {
sql += " WHERE " + whereExpression.expressionSQL(&arguments)
}
@@ -86,10 +110,10 @@ struct QueryInterfaceSelectQueryDefinition {
var arguments: StatementArguments? = StatementArguments()
if let source = source {
sql += " FROM " + source.sourceSQL(&arguments)
sql += try " FROM " + source.sourceSQL(db, &arguments)
}
if let whereExpression = whereExpression {
if let whereExpression = try wherePromise.resolve(db) {
sql += " WHERE " + whereExpression.expressionSQL(&arguments)
}
@@ -147,7 +171,7 @@ struct QueryInterfaceSelectQueryDefinition {
extension QueryInterfaceSelectQueryDefinition : Request {
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
var arguments: StatementArguments? = StatementArguments()
let sql = self.sql(&arguments)
let sql = try self.sql(db, &arguments)
let statement = try db.makeSelectStatement(sql)
try statement.setArgumentsWithValidation(arguments!)
return (statement, nil)
@@ -157,6 +181,42 @@ extension QueryInterfaceSelectQueryDefinition : Request {
return try Int.fetchOne(db, countQuery)!
}
/// The database region that the request looks into.
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
let (statement, _) = try prepare(db)
let region = statement.fetchedRegion
// Can we intersect the region with rowIds?
//
// Give up unless request feeds from a single database table
guard let source = source else {
return region
}
guard case .table(name: let tableName, alias: _) = source else {
return region
}
// Give up unless primary key is rowId
let primaryKeyInfo = try db.primaryKey(tableName)
guard primaryKeyInfo.isRowID else {
return region
}
// Give up unless there is a where clause
guard let whereExpression = try wherePromise.resolve(db) else {
return region
}
// The whereExpression knows better
guard let rowIds = whereExpression.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else {
return region
}
// Database regions are case-insensitive: use the canonical table name
let canonicalTableName = try db.canonicalName(table: tableName)
return region.tableIntersection(canonicalTableName, rowIds: rowIds)
}
private var countQuery: QueryInterfaceSelectQueryDefinition {
guard groupByExpressions.isEmpty && limit == nil else {
// SELECT ... GROUP BY ...
@@ -206,7 +266,7 @@ indirect enum SQLSource {
case table(name: String, alias: String?)
case query(query: QueryInterfaceSelectQueryDefinition, alias: String?)
func sourceSQL(_ arguments: inout StatementArguments?) -> String {
func sourceSQL(_ db: Database, _ arguments: inout StatementArguments?) throws -> String {
switch self {
case .table(let table, let alias):
if let alias = alias {
@@ -216,9 +276,9 @@ indirect enum SQLSource {
}
case .query(let query, let alias):
if let alias = alias {
return "(" + query.sql(&arguments) + ") AS " + alias.quotedDatabaseIdentifier
return try "(" + query.sql(db, &arguments) + ") AS " + alias.quotedDatabaseIdentifier
} else {
return "(" + query.sql(&arguments) + ")"
return try "(" + query.sql(db, &arguments) + ")"
}
}
}
@@ -265,6 +265,56 @@ public struct SQLExpressionBinary : SQLExpression {
return SQLExpressionNot(self)
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
switch op {
case .equal, .is:
// Look for `id == 1` or `id IS 1`?
switch (lhs, rhs) {
case (let column as Column, let dbValue as DatabaseValue),
(let dbValue as DatabaseValue, let column as Column):
// Look for `id == 1`, `rowid == 1`, `1 == id`, `1 == rowid`
var rowIdNames = [Column.rowID.name.lowercased()]
if let rowIdName = rowIdName {
rowIdNames.append(rowIdName.lowercased())
}
guard rowIdNames.contains(column.name.lowercased()) else {
return nil
}
if let rowId = Int64.fromDatabaseValue(dbValue) {
return [rowId]
} else {
return []
}
default:
return nil
}
case .and:
let lids = lhs.matchedRowIds(rowIdName: rowIdName)
let rids = rhs.matchedRowIds(rowIdName: rowIdName)
switch (lids, rids) {
case (nil, nil): return nil
case let (ids?, nil), let (nil, ids?): return ids
case let (lids?, rids?): return lids.intersection(rids)
}
case .or:
let lids = lhs.matchedRowIds(rowIdName: rowIdName)
let rids = rhs.matchedRowIds(rowIdName: rowIdName)
switch (lids, rids) {
case let (lids?, rids?): return lids.union(rids)
default: return nil
}
default:
return nil
}
}
}
// MARK: - SQLExpressionContains
@@ -296,6 +346,34 @@ struct SQLExpressionContains : SQLExpression {
var negated: SQLExpression {
return SQLExpressionContains(expression, collection, negated: !isNegated)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
// Look for `id IN (1, 2, 3)`
guard let column = expression as? Column,
let array = collection as? SQLExpressionsArray else
{
return nil
}
var rowIdNames = [Column.rowID.name.lowercased()]
if let rowIdName = rowIdName {
rowIdNames.append(rowIdName.lowercased())
}
guard rowIdNames.contains(column.name.lowercased()) else {
return nil
}
var rowIDs: Set<Int64> = []
for expression in array.expressions {
guard let dbValue = expression as? DatabaseValue else { return nil }
if let rowId = Int64.fromDatabaseValue(dbValue) {
rowIDs.insert(rowId)
}
}
return rowIDs
}
}
// MARK: - SQLExpressionBetween
+12
View File
@@ -53,6 +53,11 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi
/// let expression = [1,2,3].contains(Column("id")) // id IN (1,2,3)
/// expression.negated // id NOT IN (1,2,3)
var negated: SQLExpression { get }
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns the rowIds matched by the expression.
func matchedRowIds(rowIdName: String?) -> Set<Int64>?
}
extension SQLExpression {
@@ -67,6 +72,13 @@ extension SQLExpression {
public var negated: SQLExpression {
return SQLExpressionNot(self)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The default implementation returns nil
public func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
return nil
}
}
// SQLExpression: SQLExpressible
+21 -27
View File
@@ -104,8 +104,8 @@ public final class FetchedRecordsController<Record: RowConvertible> {
{
self.itemsAreIdenticalFactory = itemsAreIdenticalFactory
self.request = request
(self.selectionInfo, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
try FetchedRecordsController.fetchSelectionInfoAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
(self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
try FetchedRecordsController.fetchRegionAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
}
self.databaseWriter = databaseWriter
self.queue = queue
@@ -133,7 +133,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
let initialItems = try Item<Record>.fetchAll(db, request)
fetchedItems = initialItems
if let fetchAndNotifyChanges = fetchAndNotifyChanges {
let observer = FetchedRecordsObserver(selectionInfo: self.selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
let observer = FetchedRecordsObserver(region: self.region, fetchAndNotifyChanges: fetchAndNotifyChanges)
self.observer = observer
observer.items = initialItems
db.add(transactionObserver: observer)
@@ -162,8 +162,8 @@ public final class FetchedRecordsController<Record: RowConvertible> {
/// main queue unless stated otherwise in the controller's initializer).
public func setRequest<Request>(_ request: Request) throws where Request: TypedRequest, Request.RowDecoder == Record {
self.request = request
(self.selectionInfo, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
try FetchedRecordsController.fetchSelectionInfoAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
(self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
try FetchedRecordsController.fetchRegionAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
}
// No observer: don't look for changes
@@ -179,7 +179,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
// and notify eventual changes
let initialItems = fetchedItems
databaseWriter.write { db in
let observer = FetchedRecordsObserver(selectionInfo: selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
let observer = FetchedRecordsObserver(region: region, fetchAndNotifyChanges: fetchAndNotifyChanges)
self.observer = observer
observer.items = initialItems
db.add(transactionObserver: observer)
@@ -299,7 +299,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
onChange: onChange,
didChange: didChange,
didProcessTransaction: didProcessTransaction)
let observer = FetchedRecordsObserver(selectionInfo: selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
let observer = FetchedRecordsObserver(region: region, fetchAndNotifyChanges: fetchAndNotifyChanges)
self.observer = observer
if let initialItems = initialItems {
observer.items = initialItems
@@ -378,8 +378,8 @@ public final class FetchedRecordsController<Record: RowConvertible> {
/// The request
fileprivate var request: Request
/// The observed selection info
private var selectionInfo : SelectStatement.SelectionInfo
/// The observed database region
private var region : DatabaseRegion
/// The eventual current database observer
private var observer: FetchedRecordsObserver<Record>?
@@ -387,16 +387,15 @@ public final class FetchedRecordsController<Record: RowConvertible> {
/// The eventual error handler
fileprivate var errorHandler: ((FetchedRecordsController<Record>, Error) -> ())?
private static func fetchSelectionInfoAndComparator(
private static func fetchRegionAndComparator(
_ db: Database,
request: Request,
itemsAreIdenticalFactory: ItemComparatorFactory<Record>) throws
-> (SelectStatement.SelectionInfo, ItemComparator<Record>)
-> (DatabaseRegion, ItemComparator<Record>)
{
let (statement, _) = try request.prepare(db)
let selectionInfo = statement.selectionInfo
let region = try request.fetchedRegion(db)
let itemsAreIdentical = try itemsAreIdenticalFactory(db)
return (selectionInfo, itemsAreIdentical)
return (region, itemsAreIdentical)
}
}
@@ -522,15 +521,15 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
var needsComputeChanges: Bool
var items: [Item<Record>]! // ought to be not nil when observer has started tracking transactions
let queue: DispatchQueue // protects items
let selectionInfo: SelectStatement.SelectionInfo
let region: DatabaseRegion
var fetchAndNotifyChanges: (FetchedRecordsObserver<Record>) -> ()
init(selectionInfo: SelectStatement.SelectionInfo, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver<Record>) -> ()) {
init(region: DatabaseRegion, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver<Record>) -> ()) {
self.isValid = true
self.items = nil
self.needsComputeChanges = false
self.queue = DispatchQueue(label: "GRDB.FetchedRecordsObserver")
self.selectionInfo = selectionInfo
self.region = region
self.fetchAndNotifyChanges = fetchAndNotifyChanges
}
@@ -539,22 +538,17 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return eventKind.impacts(selectionInfo)
return region.isModified(byEventsOfKind: eventKind)
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
/// Part of the TransactionObserverType protocol
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
/// Part of the TransactionObserverType protocol
func databaseDidChange(with event: DatabaseEvent) {
needsComputeChanges = true
if region.isModified(by: event) {
needsComputeChanges = true
stopObservingDatabaseChangesUntilNextTransaction()
}
}
/// Part of the TransactionObserverType protocol
func databaseWillCommit() throws { }
/// Part of the TransactionObserverType protocol
func databaseDidRollback(_ db: Database) {
needsComputeChanges = false
+2 -2
View File
@@ -572,7 +572,7 @@ extension MutablePersistable {
// Avoid hitting the database
return 0
}
return try filter(db, keys: keys).deleteAll(db)
return try filter(keys: keys).deleteAll(db)
}
/// Delete a record, identified by its primary key; returns whether a
@@ -623,7 +623,7 @@ extension MutablePersistable {
// Avoid hitting the database
return 0
}
return try filter(db, keys: keys).deleteAll(db)
return try filter(keys: keys).deleteAll(db)
}
/// Delete a record, identified by a unique key (the primary key or any key
+11 -8
View File
@@ -78,7 +78,7 @@ extension RowConvertible where Self: TableMapping {
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> RecordCursor<Self> where Sequence.Element: DatabaseValueConvertible {
return try filter(db, keys: keys).fetchCursor(db)
return try filter(keys: keys).fetchCursor(db)
}
/// Returns an array of records, given their primary keys.
@@ -98,7 +98,7 @@ extension RowConvertible where Self: TableMapping {
// Avoid hitting the database
return []
}
return try filter(db, keys: keys).fetchAll(db)
return try filter(keys: keys).fetchAll(db)
}
/// Returns a single record given its primary key.
@@ -115,7 +115,7 @@ extension RowConvertible where Self: TableMapping {
// Avoid hitting the database
return nil
}
return try filter(db, keys: [key]).fetchOne(db)
return try filter(key: key).fetchOne(db)
}
}
@@ -139,7 +139,7 @@ extension RowConvertible where Self: TableMapping {
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> RecordCursor<Self> {
return try filter(db, keys: keys).fetchCursor(db)
return try filter(keys: keys).fetchCursor(db)
}
/// Returns an array of records identified by the provided unique keys
@@ -155,12 +155,11 @@ extension RowConvertible where Self: TableMapping {
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> [Self] {
let keys = Array(keys)
if keys.isEmpty {
// Avoid hitting the database
return []
}
return try filter(db, keys: keys).fetchAll(db)
return try filter(keys: keys).fetchAll(db)
}
/// Returns a single record identified by a unique key (the primary key or
@@ -173,7 +172,11 @@ extension RowConvertible where Self: TableMapping {
/// - key: A dictionary of values.
/// - returns: An optional record.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self? {
return try filter(db, keys: [key]).fetchOne(db)
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self? {
guard let key = key else {
// Avoid hitting the database
return nil
}
return try filter(key: key).fetchOne(db)
}
}
-62
View File
@@ -68,65 +68,3 @@ extension TableMapping {
}
}
extension TableMapping {
// MARK: Key Requests
static func filter<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible {
let primaryKey = try db.primaryKey(databaseTableName)
let columns = primaryKey.columns.map { Column($0) }
GRDBPrecondition(columns.count == 1, "table \(databaseTableName) has multiple columns in its primary key")
let column = columns[0]
let keys = Array(keys)
switch keys.count {
case 0:
return none()
case 1:
return filter(column == keys[0])
default:
return filter(keys.contains(column))
}
}
// Raises a fatal error if there is no unique index on the columns (unless
// fatalErrorOnMissingUniqueIndex is false, for testability).
//
// TODO: think about
// - allowing non unique keys in Type.fetchOne(db, key: ...) ???
// - allowing non unique keys in Type.fetchAll/Cursor(db, keys: ...)
// - forbidding nil values: Player.deleteOne(db, key: ["email": nil]) may delete several rows (case of a nullable unique key)
static func filter(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> QueryInterfaceRequest<Self> {
// SELECT * FROM table WHERE ((a=? AND b=?) OR (c=? AND d=?) OR ...)
let keyPredicates: [SQLExpression] = try keys.map { key in
// Prevent filter(db, keys: [[:]])
GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary")
// Prevent filter(db, keys: [["foo": 1, "bar": 2]]) where
// ("foo", "bar") is not a unique key (primary key or columns of a
// unique index)
guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else {
let message = "table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))"
if fatalErrorOnMissingUniqueIndex {
fatalError(message)
} else {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: message)
}
}
let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() }
let columnPredicates: [SQLExpression] = key
// Sort key columns in the same order as the unique index
.sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! }
.map { (column, value) in Column(column) == value }
return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty
}
guard let predicate = SQLBinaryOperator.or.join(keyPredicates) else {
// No key
return none()
}
return filter(predicate)
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDBCipher'
s.version = '2.4.2'
s.version = '2.6.1'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
+16 -10
View File
@@ -86,7 +86,7 @@
560FC5A21CB00B880014AA8E /* DatabaseFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */; };
560FC5A41CB00B880014AA8E /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; };
560FC5A51CB00B880014AA8E /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
560FC5A61CB00B880014AA8E /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
560FC5A61CB00B880014AA8E /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
560FC5A71CB00B880014AA8E /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
560FC5B21CB031E30014AA8E /* StatementColumnConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */; };
560FC5B31CB031EA0014AA8E /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; };
@@ -319,7 +319,7 @@
567156601CB16729007DC145 /* DatabaseFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */; };
567156611CB16729007DC145 /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; };
567156621CB16729007DC145 /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
567156631CB16729007DC145 /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
567156631CB16729007DC145 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
567156641CB16729007DC145 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
567156671CB16729007DC145 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 560FC54D1CB003810014AA8E /* GRDBCipher.framework */; };
5671FC211DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; };
@@ -462,6 +462,8 @@
569C1EB41CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; };
569C1EB61CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; };
569C1EB71CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; };
569EF0E9200D387000A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */; };
569EF0EA200D387000A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */; };
56A4CDB11D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
56A4CDB21D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
56A4CDB51D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
@@ -577,7 +579,7 @@
56AFCA731CB1AA9900F48B96 /* DatabaseQueueInMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */; };
56AFCA741CB1AA9900F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; };
56AFCA751CB1AA9900F48B96 /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
56AFCA761CB1AA9900F48B96 /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
56AFCA761CB1AA9900F48B96 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
56AFCA771CB1AA9900F48B96 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
56AFCA831CB1AAC900F48B96 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */; };
56AFCA891CB1ABC800F48B96 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; };
@@ -637,7 +639,7 @@
56AFCACC1CB1ABC800F48B96 /* DatabaseQueueInMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */; };
56AFCACD1CB1ABC800F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; };
56AFCACE1CB1ABC800F48B96 /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
56AFCACF1CB1ABC800F48B96 /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
56AFCACF1CB1ABC800F48B96 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
56AFCAD01CB1ABC800F48B96 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
56AFCAD21CB1ABC800F48B96 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */; };
56B021CA1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; };
@@ -793,7 +795,7 @@
5605F1521C672E4000235C62 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = "<group>"; };
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+RawRepresentable.swift"; sourceTree = "<group>"; };
5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementSelectionInfoTests.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = "<group>"; };
5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = "<group>"; };
5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceSelectQueryDefinition.swift; sourceTree = "<group>"; };
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
@@ -926,6 +928,7 @@
5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = "<group>"; };
5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = "<group>"; };
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = "<group>"; };
569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = "<group>"; };
56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = "<group>"; };
56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueInMemoryTests.swift; sourceTree = "<group>"; };
56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseErrorTests.swift; sourceTree = "<group>"; };
@@ -1378,11 +1381,11 @@
569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */,
563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */,
569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */,
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */,
56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */,
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */,
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */,
56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */,
5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */,
);
name = Private;
sourceTree = "<group>";
@@ -1493,6 +1496,7 @@
560A37A31C8F625000949E71 /* DatabasePool.swift */,
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
@@ -1942,6 +1946,7 @@
560FC5221CB003810014AA8E /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
560FC5231CB003810014AA8E /* Configuration.swift in Sources */,
566475CD1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
569EF0E9200D387000A9FA45 /* DatabaseRegion.swift in Sources */,
5698AC381D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */,
5659F4991EA8D989004A4992 /* Pool.swift in Sources */,
@@ -2133,7 +2138,7 @@
5690C3271D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */,
560FC5A51CB00B880014AA8E /* CGFloatTests.swift in Sources */,
56FF45571D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */,
560FC5A61CB00B880014AA8E /* StatementSelectionInfoTests.swift in Sources */,
560FC5A61CB00B880014AA8E /* DatabaseRegionTests.swift in Sources */,
5698AC8A1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */,
5698AC041D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */,
5690C3381D23E7D200E59934 /* FoundationDateTests.swift in Sources */,
@@ -2280,7 +2285,7 @@
5622060A1E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */,
562205F71E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */,
56DAA2D41DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
567156631CB16729007DC145 /* StatementSelectionInfoTests.swift in Sources */,
567156631CB16729007DC145 /* DatabaseRegionTests.swift in Sources */,
562393621DEE06D300A6B01F /* CursorTests.swift in Sources */,
567156641CB16729007DC145 /* GRDBTestCase.swift in Sources */,
);
@@ -2315,6 +2320,7 @@
56AFC9F51CB1A8BB00F48B96 /* Date.swift in Sources */,
56AFC9F71CB1A8BB00F48B96 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
566475D01D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
569EF0EA200D387000A9FA45 /* DatabaseRegion.swift in Sources */,
5698AC3B1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */,
5659F49C1EA8D989004A4992 /* Pool.swift in Sources */,
@@ -2513,7 +2519,7 @@
6340BF851E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */,
56AFCA751CB1AA9900F48B96 /* CGFloatTests.swift in Sources */,
562393531DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
56AFCA761CB1AA9900F48B96 /* StatementSelectionInfoTests.swift in Sources */,
56AFCA761CB1AA9900F48B96 /* DatabaseRegionTests.swift in Sources */,
5698ACA31DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
5691784A1CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */,
56AFCA771CB1AA9900F48B96 /* GRDBTestCase.swift in Sources */,
@@ -2652,7 +2658,7 @@
6340BF861E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */,
567A80591D41350C00C7DCEC /* IndexInfoTests.swift in Sources */,
562393541DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
56AFCACF1CB1ABC800F48B96 /* StatementSelectionInfoTests.swift in Sources */,
56AFCACF1CB1ABC800F48B96 /* DatabaseRegionTests.swift in Sources */,
56AFCAD01CB1ABC800F48B96 /* GRDBTestCase.swift in Sources */,
5698ACA41DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
565EFAF41D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */,
+12 -6
View File
@@ -175,6 +175,8 @@
5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; };
5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; };
5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; };
569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */; };
569EF0E7200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */; };
56A4CDB31D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
56A5EF121EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */; };
@@ -305,7 +307,7 @@
F3BA80511CFB2B59003DC1BA /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; };
F3BA80521CFB2B59003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */; };
F3BA80531CFB2B59003DC1BA /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; };
F3BA80541CFB2B59003DC1BA /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
F3BA80541CFB2B59003DC1BA /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
F3BA80661CFB2E55003DC1BA /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; };
F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238711B9C75030082EB20 /* Database.swift */; };
F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238731B9C75030082EB20 /* DatabaseError.swift */; };
@@ -346,7 +348,7 @@
F3BA80A61CFB2F91003DC1BA /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
F3BA80AC1CFB2FA6003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */; };
F3BA80AD1CFB2FA6003DC1BA /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; };
F3BA80AE1CFB2FA6003DC1BA /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
F3BA80AE1CFB2FA6003DC1BA /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
F3BA80AF1CFB2FB1003DC1BA /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
F3BA80B01CFB2FB2003DC1BA /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
F3BA80B11CFB2FC4003DC1BA /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; };
@@ -513,7 +515,7 @@
5605F1521C672E4000235C62 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = "<group>"; };
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+RawRepresentable.swift"; sourceTree = "<group>"; };
5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementSelectionInfoTests.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = "<group>"; };
5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = "<group>"; };
5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceSelectQueryDefinition.swift; sourceTree = "<group>"; };
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
@@ -637,6 +639,7 @@
5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = "<group>"; };
5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = "<group>"; };
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = "<group>"; };
569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = "<group>"; };
56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = "<group>"; };
56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueInMemoryTests.swift; sourceTree = "<group>"; };
56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseErrorTests.swift; sourceTree = "<group>"; };
@@ -1068,11 +1071,11 @@
569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */,
563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */,
569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */,
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */,
56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */,
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */,
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */,
56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */,
5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */,
);
name = Private;
sourceTree = "<group>";
@@ -1183,6 +1186,7 @@
560A37A31C8F625000949E71 /* DatabasePool.swift */,
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
@@ -1661,6 +1665,7 @@
F3BA800B1CFB286D003DC1BA /* Database.swift in Sources */,
F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */,
F3BA80161CFB2876003DC1BA /* Row.swift in Sources */,
569EF0E7200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */,
F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */,
564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */,
5659F49D1EA8D989004A4992 /* Pool.swift in Sources */,
@@ -1838,7 +1843,7 @@
561667081D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */,
565EFAF51D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */,
F3BA81231CFB3063003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */,
F3BA80541CFB2B59003DC1BA /* StatementSelectionInfoTests.swift in Sources */,
F3BA80541CFB2B59003DC1BA /* DatabaseRegionTests.swift in Sources */,
567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */,
F3BA81171CFB305E003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */,
F3BA810B1CFB3056003DC1BA /* Row+FoundationTests.swift in Sources */,
@@ -1895,6 +1900,7 @@
F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */,
F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */,
F3BA80721CFB2E55003DC1BA /* Row.swift in Sources */,
569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */,
F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */,
564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */,
5659F49A1EA8D989004A4992 /* Pool.swift in Sources */,
@@ -2057,7 +2063,7 @@
F3BA80E01CFB300F003DC1BA /* DatabaseTimestampTests.swift in Sources */,
56A5EF121EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
F3BA80B21CFB2FC5003DC1BA /* DatabaseTests.swift in Sources */,
F3BA80AE1CFB2FA6003DC1BA /* StatementSelectionInfoTests.swift in Sources */,
F3BA80AE1CFB2FA6003DC1BA /* DatabaseRegionTests.swift in Sources */,
F3BA81311CFB3064003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */,
5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */,
F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */,
@@ -41,7 +41,8 @@
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<Testables>
<TestableReference
skipped = "NO">
+13 -6
View File
@@ -13,7 +13,7 @@ default: test
# Requirements
# ============
#
# Xcode 8.3.3, with iOS8.1 Simulator installed
# Xcode >= 9.0, with iOS8.1 Simulator installed
# CocoaPods ~> 1.2.0 - https://cocoapods.org
# Carthage ~> 0.20.1 - https://github.com/carthage/carthage
# Jazzy ~> 0.7.4 - https://github.com/realm/jazzy
@@ -29,6 +29,7 @@ XCODEBUILD := set -o pipefail && $(shell command -v xcodebuild)
XCODEVERSION_FULL := $(word 2, $(shell xcodebuild -version))
XCODEVERSION_MAJOR := $(shell xcodebuild -version 2>&1 | grep Xcode | cut -d' ' -f2 | cut -d'.' -f1)
XCODEVERSION_MINOR := $(shell xcodebuild -version 2>&1 | grep Xcode | cut -d' ' -f2 | cut -d'.' -f2)
XCODEVERSION_PATCH := $(shell xcodebuild -version 2>&1 | grep Xcode | cut -d' ' -f2 | cut -d'.' -f3)
# The Xcode Version, containing only the "MAJOR.MINOR" (ex. "8.3" for Xcode 8.3, 8.3.1, etc.)
XCODEVERSION := $(XCODEVERSION_MAJOR).$(XCODEVERSION_MINOR)
@@ -49,9 +50,15 @@ MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=8.1"
ifeq ($(XCODEVERSION),9.2)
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.2"
else ifeq ($(XCODEVERSION),9.1)
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.1"
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.1"
else ifeq ($(XCODEVERSION),9.0)
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0"
ifeq ($(XCODEVERSION_PATCH),1)
# Xcode 9.0.1: @groue's personal computer
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0.1"
else
# Xcode 9.0: Travis https://docs.travis-ci.com/user/reference/osx/#Xcode-9.0
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0"
endif
else
# Xcode < 9.0 is not supported
endif
@@ -296,10 +303,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/v2.4.2 \
--module-version 2.4 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v2.6.0 \
--module-version 2.6 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/2.4/ \
--root-url http://groue.github.io/GRDB.swift/docs/2.6/ \
--output Documentation/Reference \
--podspec GRDB.swift.podspec
else
+104 -29
View File
@@ -3,7 +3,7 @@ GRDB 2 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](ht
### A toolkit for SQLite databases, with a focus on application development
**Latest release**: January 5, 2018 • version 2.4.2 • [CHANGELOG](CHANGELOG.md)
**Latest release**: January 19, 2018 • version 2.6.1 • [CHANGELOG](CHANGELOG.md)
**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ &bull; Swift 4.0 / Xcode 9+
@@ -14,7 +14,7 @@ GRDB 2 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](ht
| Swift 3 | [v1.0](https://github.com/groue/GRDB.swift/tree/v1.0) |
| Swift 3.1 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
| Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
| **Swift 4** | **v2.4.2** |
| **Swift 4** | **v2.6.1** |
Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips.
@@ -197,7 +197,7 @@ Documentation
**Reference**
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/2.4/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/2.6/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
**Getting Started**
@@ -265,7 +265,7 @@ The [Swift Package Manager](https://swift.org/package-manager/) automates the di
```swift
let package = Package(
dependencies: [
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.4.2")
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.6.1")
]
)
```
@@ -282,7 +282,7 @@ If you decide to use Carthage despite this warning, and get any Carthage-related
## Manually
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.4.2) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.4.2` command.
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.6.1) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.6.1` command.
2. Embed the `GRDB.xcodeproj` project in your own project.
@@ -379,7 +379,7 @@ let dbQueue = try DatabaseQueue(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.4/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.6/Structs/Configuration.html) for more details.
## Database Pools
@@ -460,7 +460,7 @@ let dbPool = try DatabasePool(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.4/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.6/Structs/Configuration.html) for more details.
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
@@ -650,7 +650,7 @@ Both arrays and cursors can iterate over database results. How do you choose one
- Cursors can not be used on any thread: you must consume them in a protected database queue.
- Cursors iterate database results in a lazy fashion, and don't consume much memory.
- Cursors can be iterated only one time.
- Cursors are granted with direct access to SQLite: you can especially expect the best performance from cursors of raw database rows and some primitive types like `Int`, `String`, or `Bool` that adopt the [StatementColumnConvertible](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/StatementColumnConvertible.html) protocol.
- Cursors are granted with direct access to SQLite: you can especially expect the best performance from cursors of raw database rows and some primitive types like `Int`, `String`, or `Bool` that adopt the [StatementColumnConvertible](http://groue.github.io/GRDB.swift/docs/2.6/Protocols/StatementColumnConvertible.html) protocol.
If you don't see, or don't care about the difference, use arrays. If you care about memory and performance, use cursors when appropriate.
@@ -663,7 +663,7 @@ Date.fetchCursor(...) // DatabaseValueCursor<Date>
Player.fetchCursor(...) // RecordCursor<Player>
```
All cursor types adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/2.4/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 methods: `contains`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `map`, `reduce`:
All cursor types adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/2.6/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 methods: `contains`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `map`, `reduce`:
```swift
// Iterate all Github links
@@ -734,7 +734,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/2.4/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/2.6/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:
@@ -1005,7 +1005,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/2.4/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/2.6/Structs/StatementArguments.html):
```swift
let url: URL = ...
@@ -1397,7 +1397,7 @@ try dbQueue.inDatabase { 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/2.4/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/2.6/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
```swift
updateStatement.arguments = ["name": "Arthur", "score": 1000]
@@ -1659,7 +1659,7 @@ row["consumed"] // "Hello"
row["produced"] // nil
```
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters:
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/2.6/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters:
### ColumnMapping
@@ -1786,8 +1786,8 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used
- `sqlite3_aggregate_context`, `sqlite3_create_function_v2`, `sqlite3_result_blob`, `sqlite3_result_double`, `sqlite3_result_error`, `sqlite3_result_error_code`, `sqlite3_result_int64`, `sqlite3_result_null`, `sqlite3_result_text`, `sqlite3_user_data`, `sqlite3_value_blob`, `sqlite3_value_bytes`, `sqlite3_value_double`, `sqlite3_value_int64`, `sqlite3_value_text`, `sqlite3_value_type`: see [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates)
- `sqlite3_backup_finish`, `sqlite3_backup_init`, `sqlite3_backup_step`: see [Backup](#backup)
- `sqlite3_bind_blob`, `sqlite3_bind_double`, `sqlite3_bind_int64`, `sqlite3_bind_null`, `sqlite3_bind_parameter_count`, `sqlite3_bind_parameter_name`, `sqlite3_bind_text`, `sqlite3_clear_bindings`, `sqlite3_column_blob`, `sqlite3_column_bytes`, `sqlite3_column_count`, `sqlite3_column_double`, `sqlite3_column_int64`, `sqlite3_column_name`, `sqlite3_column_text`, `sqlite3_column_type`, `sqlite3_exec`, `sqlite3_finalize`, `sqlite3_prepare_v2`, `sqlite3_reset`, `sqlite3_step`: see [Executing Updates](#executing-updates), [Fetch Queries](#fetch-queries), [Prepared Statements](#prepared-statements), [Values](#values)
- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.4/Structs/Configuration.html)
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/2.4/Classes/Database.html)
- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.6/Structs/Configuration.html)
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/2.6/Classes/Database.html)
- `sqlite3_close`, `sqlite3_close_v2`, `sqlite3_next_stmt`, `sqlite3_open_v2`: see [Database Connections](#database-connections)
- `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [FetchedRecordsController](#fetchedrecordscontroller)
- `sqlite3_config`: see [Error Log](#error-log)
@@ -1798,9 +1798,9 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used
- `sqlite3_last_insert_rowid`: see [Executing Updates](#executing-updates)
- `sqlite3_preupdate_count`, `sqlite3_preupdate_depth`, `sqlite3_preupdate_hook`, `sqlite3_preupdate_new`, `sqlite3_preupdate_old`: see [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks)
- `sqlite3_set_authorizer`: **reserved by GRDB**
- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/2.4/Classes/Statement.html)
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/2.4/Structs/Configuration.html)
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/2.4/Classes/DatabasePool.html)
- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/2.6/Classes/Statement.html)
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/2.6/Structs/Configuration.html)
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/2.6/Classes/DatabasePool.html)
Records
@@ -2125,7 +2125,7 @@ try Place.fetchAll(db, "SELECT ...", arguments:...) // [Place]
try Place.fetchOne(db, "SELECT ...", arguments:...) // Place?
```
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html) for more information about the query arguments.
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.6/Structs/StatementArguments.html) for more information about the query arguments.
## TableMapping Protocol
@@ -3099,6 +3099,22 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Player.filter(nameColumn != nil && heightColumn > 1.75)
```
- `filter(key:)` and `filter(keys:)` apply conditions on primary keys and unique keys:
```swift
// SELECT * FROM players WHERE id = 1
Player.filter(key: 1)
// SELECT * FROM countries WHERE isoCode IN ('FR', 'US')
Country.filter(keys: ["FR", "US"])
// SELECT * FROM citizenships WHERE playerID = 1 AND countryISOCode = 'FR'
Citizenship.filter(key: ["playerID": 1, "countryISOCode": "FR"])
// SELECT * FROM players WHERE email = 'arthur@example.com'
Player.filter(key: ["email": "arthur@example.com"])
```
- `matching(pattern)` performs [full-text search](#full-text-search).
```swift
@@ -3189,7 +3205,7 @@ Player // SELECT * FROM players
```
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.6/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM players WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -3493,6 +3509,44 @@ try Citizenship.fetchOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) // Ci
try Player.fetchOne(db, key: ["email": "arthur@example.com"]) // Player?
```
**When you want to build a request and plan to fetch from it later**, use the `filter(key:)` and `filter(keys:)` methods:
```swift
// SELECT * FROM players WHERE id = 1
let request = Player.filter(key: 1)
let player = try request.fetchOne(db) // Player?
// SELECT * FROM players WHERE id IN (1, 2, 3)
let request = Player.filter(keys: [1, 2, 3])
let players = try request.fetchAll(db) // [Player]
// SELECT * FROM players WHERE isoCode = 'FR'
let request = Country.filter(key: "FR")
let country = try request.fetchOne(db) // Country?
// SELECT * FROM countries WHERE isoCode IN ('FR', 'US')
let request = Country.filter(keys: ["FR", "US"])
let countries = try request.fetchAll(db) // [Country]
// SELECT * FROM citizenships WHERE playerID = 1 AND countryISOCode = 'FR'
let request = Citizenship.filter(key: ["playerID": 1, "countryISOCode": "FR"])
let citizenship = request.fetchOne(db) // Citizenship?
// SELECT * FROM players WHERE email = 'arthur@example.com'
let request = Player.filter(key: ["email": "arthur@example.com"])
let player = try request.fetchOne(db) // Player?
```
Those requests help observing the database with [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB):
```swift
Player.filter(key: 1).rx
.fetchOne(in: dbQueue)
.subscribe(onNext: { player: Player? in
print("Player 1 has changed")
})
```
## Fetching Aggregated Values
@@ -3658,9 +3712,9 @@ try request.fetchOne(db) // Player?
**To build custom requests**, you can create your own type that adopts the protocols, or derive requests from other requests, or use one of the built-in concrete types:
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.4/Structs/SQLRequest.html): a Request built from raw SQL
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/2.4/Structs/AnyRequest.html): a type-erased Request
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/2.4/Structs/AnyTypedRequest.html): a type-erased TypedRequest
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.6/Structs/SQLRequest.html): a Request built from raw SQL
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/2.6/Structs/AnyRequest.html): a type-erased Request
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/2.6/Structs/AnyTypedRequest.html): a type-erased TypedRequest
Use the `asRequest(of:)` method to define the type fetched by the request:
@@ -4090,7 +4144,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html):
FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.6/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -4303,7 +4357,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html):
FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.6/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -4759,6 +4813,27 @@ dbQueue.inDatabase { db in
- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed.
Finally, an observer may ignore all database changes until the end of the current transaction:
```swift
class PlayerObserver: TransactionObserver {
var playersTableWasModified = false
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return eventKind.tableName == "players"
}
func databaseDidChange(with event: DatabaseEvent) {
playersTableWasModified = true
// It is pointless to keep on tracking further changes:
stopObservingDatabaseChangesUntilNextTransaction()
}
}
```
After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChange(with:)` method will not be notified of any change for the remaining duration of the current transaction. This helps GRDB optimize database observation.
#### Support for SQLite Pre-Update Hooks
@@ -5130,7 +5205,7 @@ Alternatively, perform a manual installation of GRDB and SQLCipher:
```sh
cd [GRDB directory]
git checkout v2.4.2
git checkout v2.6.1
git submodule update --init SQLCipher/src
```
@@ -5237,7 +5312,7 @@ DROP TABLE students;
--' WHERE id = 1
```
To avoid those problems, **never embed raw values in your SQL queries**. The only correct technique is to provide [arguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html) to your SQL queries:
To avoid those problems, **never embed raw values in your SQL queries**. The only correct technique is to provide [arguments](http://groue.github.io/GRDB.swift/docs/2.6/Structs/StatementArguments.html) to your SQL queries:
```swift
// Good
@@ -5818,7 +5893,7 @@ try dbPool.write { db in
### DatabaseWriter and DatabaseReader Protocols
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/DatabaseWriter.html) protocols.
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.6/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.6/Protocols/DatabaseWriter.html) protocols.
These protocols provide a unified API that lets you write safe concurrent code that targets both classes.
@@ -5912,7 +5987,7 @@ If you absolutely need multiple connections, then:
- 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/2.4/Structs/Configuration.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/2.6/Structs/Configuration.html)
- [Ask questions](https://github.com/groue/GRDB.swift/issues)
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.4.2</string>
<string>2.6.1</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+1
View File
@@ -13,6 +13,7 @@
GRDB 3.0
- [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types.
- [ ] Rename Request to FetchRequest, because Request is a bad name: https://github.com/swift-server/http/pull/7#issuecomment-308448528
- [ ] Rename RowConvertible, TableMapping, MutablePersistable and Persistable so that their names contain Record: FetchableRecord, TableRecord, MutablePersistableRecord, PersistableRecord?
- [ ] Not sure: Consider introducing RowDecodable and RowEncodable on top of FetchableRecord and MutablePersistableRecord. This would allow keeping fetching and persistence methods private in some files.
@@ -192,12 +192,8 @@ private class UserTypedRequest2<T> : TypedRequest {
private class UserTransactionObserver : TransactionObserver {
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false }
func databaseDidChange(with event: DatabaseEvent) { }
func databaseWillCommit() throws { }
func databaseDidCommit(_ db: Database) { }
func databaseDidRollback(_ db: Database) { }
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
}
// MARK: - VirtualTableModule
+765
View File
@@ -0,0 +1,765 @@
import XCTest
#if GRDBCIPHER
@testable import GRDBCipher
#elseif GRDBCUSTOMSQLITE
@testable import GRDBCustomSQLite
#else
#if SWIFT_PACKAGE
import CSQLite
#else
import SQLite3
#endif
@testable import GRDB
#endif
class DatabaseRegionTests : GRDBTestCase {
func testRegionEquatable() {
// An array of distinct selection infos
let regions = [
DatabaseRegion.fullDatabase,
DatabaseRegion(),
DatabaseRegion(table: "foo"),
DatabaseRegion(table: "FOO"), // selection info is case-sensitive on table name
DatabaseRegion(table: "foo", columns: ["a", "b"]),
DatabaseRegion(table: "foo", columns: ["A", "B"]), // selection info is case-sensitive on columns names
DatabaseRegion(table: "foo", columns: ["b", "c"]),
DatabaseRegion(table: "foo", rowIds: [1, 2]),
DatabaseRegion(table: "foo", rowIds: [2, 3]),
DatabaseRegion(table: "bar")]
for (i1, s1) in regions.enumerated() {
for (i2, s2) in regions.enumerated() {
if i1 == i2 {
XCTAssertEqual(s1, s2)
} else {
XCTAssertNotEqual(s1, s2)
}
}
}
}
func testRegionUnion() {
let regions = [
DatabaseRegion.fullDatabase,
DatabaseRegion(),
DatabaseRegion(table: "foo"),
DatabaseRegion(table: "foo", columns: ["a", "b"]),
DatabaseRegion(table: "foo", columns: ["b", "c"]),
DatabaseRegion(table: "foo", rowIds: [1, 2]),
DatabaseRegion(table: "foo", rowIds: [2, 3]),
DatabaseRegion(table: "bar")]
var unions: [DatabaseRegion] = []
for s1 in regions {
for s2 in regions {
unions.append(s1.union(s2))
}
}
XCTAssertEqual(unions.map { $0.description }, [
"full database",
"full database",
"full database",
"full database",
"full database",
"full database",
"full database",
"full database",
"full database",
"empty",
"foo(*)",
"foo(a,b)",
"foo(b,c)",
"foo(*)[1,2]",
"foo(*)[2,3]",
"bar(*)",
"full database",
"foo(*)",
"foo(*)",
"foo(*)",
"foo(*)",
"foo(*)",
"foo(*)",
"bar(*),foo(*)",
"full database",
"foo(a,b)",
"foo(*)",
"foo(a,b)",
"foo(a,b,c)",
"foo(*)",
"foo(*)",
"bar(*),foo(a,b)",
"full database",
"foo(b,c)",
"foo(*)",
"foo(a,b,c)",
"foo(b,c)",
"foo(*)",
"foo(*)",
"bar(*),foo(b,c)",
"full database",
"foo(*)[1,2]",
"foo(*)",
"foo(*)",
"foo(*)",
"foo(*)[1,2]",
"foo(*)[1,2,3]",
"bar(*),foo(*)[1,2]",
"full database",
"foo(*)[2,3]",
"foo(*)",
"foo(*)",
"foo(*)",
"foo(*)[1,2,3]",
"foo(*)[2,3]",
"bar(*),foo(*)[2,3]",
"full database",
"bar(*)",
"bar(*),foo(*)",
"bar(*),foo(a,b)",
"bar(*),foo(b,c)",
"bar(*),foo(*)[1,2]",
"bar(*),foo(*)[2,3]",
"bar(*)"])
}
func testRegionUnionOfColumnsAndRows() {
let regions = [
DatabaseRegion(table: "foo", columns: ["a"]).intersection(DatabaseRegion(table: "foo", rowIds: [1])),
DatabaseRegion(table: "foo", columns: ["b"]).intersection(DatabaseRegion(table: "foo", rowIds: [2])),
]
var unions: [DatabaseRegion] = []
for s1 in regions {
for s2 in regions {
unions.append(s1.union(s2))
}
}
XCTAssertEqual(unions.map { $0.description }, ["foo(a)[1]", "foo(a,b)[1,2]", "foo(a,b)[1,2]", "foo(b)[2]"])
}
func testRegionIntersection() {
let regions = [
DatabaseRegion.fullDatabase,
DatabaseRegion(),
DatabaseRegion(table: "foo"),
DatabaseRegion(table: "foo", columns: ["a", "b"]),
DatabaseRegion(table: "foo", columns: ["b", "c"]),
DatabaseRegion(table: "foo", rowIds: [1, 2]),
DatabaseRegion(table: "foo", rowIds: [2, 3]),
DatabaseRegion(table: "bar")]
var intersection: [DatabaseRegion] = []
for s1 in regions {
for s2 in regions {
intersection.append(s1.intersection(s2))
}
}
XCTAssertEqual(intersection.map { $0.description }, [
"full database",
"empty",
"foo(*)",
"foo(a,b)",
"foo(b,c)",
"foo(*)[1,2]",
"foo(*)[2,3]",
"bar(*)",
"empty",
"empty",
"empty",
"empty",
"empty",
"empty",
"empty",
"empty",
"foo(*)",
"empty",
"foo(*)",
"foo(a,b)",
"foo(b,c)",
"foo(*)[1,2]",
"foo(*)[2,3]",
"empty",
"foo(a,b)",
"empty",
"foo(a,b)",
"foo(a,b)",
"foo(b)",
"foo(a,b)[1,2]",
"foo(a,b)[2,3]",
"empty",
"foo(b,c)",
"empty",
"foo(b,c)",
"foo(b)",
"foo(b,c)",
"foo(b,c)[1,2]",
"foo(b,c)[2,3]",
"empty",
"foo(*)[1,2]",
"empty",
"foo(*)[1,2]",
"foo(a,b)[1,2]",
"foo(b,c)[1,2]",
"foo(*)[1,2]",
"foo(*)[2]",
"empty",
"foo(*)[2,3]",
"empty",
"foo(*)[2,3]",
"foo(a,b)[2,3]",
"foo(b,c)[2,3]",
"foo(*)[2]",
"foo(*)[2,3]",
"empty",
"bar(*)",
"empty",
"empty",
"empty",
"empty",
"empty",
"empty",
"bar(*)"])
}
func testRegionIntersectionOfColumnsAndRows() {
let regions = [
DatabaseRegion(table: "foo", columns: ["a"]).intersection(DatabaseRegion(table: "foo", rowIds: [1])),
DatabaseRegion(table: "foo", columns: ["b"]).intersection(DatabaseRegion(table: "foo", rowIds: [2])),
]
var intersection: [DatabaseRegion] = []
for s1 in regions {
for s2 in regions {
intersection.append(s1.intersection(s2))
}
}
XCTAssertEqual(intersection.map { $0.description }, ["foo(a)[1]", "empty", "empty", "foo(b)[2]"])
}
func testSelectStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER, name TEXT)")
try db.execute("CREATE TABLE bar (id INTEGER, fooId INTEGER)")
do {
let statement = try db.makeSelectStatement("SELECT foo.name FROM FOO JOIN BAR ON fooId = foo.id")
let expectedRegion = DatabaseRegion(table: "foo", columns: ["name", "id"])
.union(DatabaseRegion(table: "bar", columns: ["fooId"]))
XCTAssertEqual(statement.fetchedRegion, expectedRegion)
XCTAssertEqual(statement.fetchedRegion.description, "bar(fooId),foo(id,name)")
}
do {
let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM foo")
if sqlite3_libversion_number() < 3019000 {
let expectedRegion = DatabaseRegion.fullDatabase
XCTAssertEqual(statement.fetchedRegion, expectedRegion)
XCTAssertEqual(statement.fetchedRegion.description, "full database")
} else {
let expectedRegion = DatabaseRegion(table: "foo")
XCTAssertEqual(statement.fetchedRegion, expectedRegion)
XCTAssertEqual(statement.fetchedRegion.description, "foo(*)")
}
}
}
}
func testRegionRowIds() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, a TEXT)")
struct Record: TableMapping {
static let databaseTableName = "foo"
}
// Undefined rowIds
do {
let request = Record.all()
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)")
}
do {
let request = Record.filter(Column("a") == 1)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)")
}
do {
let request = Record.filter(Column("id") >= 1)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)")
}
do {
let request = Record.filter((Column("id") == 1) || (Column("a") == "foo"))
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)")
}
// No rowId
do {
let request = Record.filter(Column("id") == nil)
try XCTAssertEqual(request.fetchedRegion(db).description, "empty")
}
do {
let request = Record.filter(Column("id") === nil)
try XCTAssertEqual(request.fetchedRegion(db).description, "empty")
}
do {
let request = Record.filter(nil == Column("id"))
try XCTAssertEqual(request.fetchedRegion(db).description, "empty")
}
do {
let request = Record.filter(nil === Column("id"))
try XCTAssertEqual(request.fetchedRegion(db).description, "empty")
}
do {
let request = Record.filter((Column("id") == 1) && (Column("id") == 2))
try XCTAssertEqual(request.fetchedRegion(db).description, "empty")
}
do {
let request = Record.filter(key: 1).filter(key: 2)
try XCTAssertEqual(request.fetchedRegion(db).description, "empty")
}
// Single rowId
do {
let request = Record.filter(Column("id") == 1)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(Column("id") === 1)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(Column("id") == 1 && Column("a") == "foo")
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(Column.rowID == 1)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(1 == Column("id"))
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(1 === Column("id"))
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(1 === Column.rowID)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(key: 1)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(key: 1).filter(key: 1)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(key: 1).filter(Column("a") == "foo")
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
// Multiple rowIds
do {
let request = Record.filter(Column("id") == 1 || Column.rowID == 2)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2]")
}
do {
let request = Record.filter((Column("id") == 1 && Column("a") == "foo") || Column.rowID == 2)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2]")
}
do {
let request = Record.filter([1, 2, 3].contains(Column("id")))
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
let request = Record.filter([1, 2, 3].contains(Column.rowID))
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
let request = Record.filter(keys: [1, 2, 3])
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
}
}
func testDatabaseRegionOfDerivedRequests() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, a TEXT)")
struct Record: TableMapping {
static let databaseTableName = "foo"
}
let request = Record.filter(keys: [1, 2, 3])
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
do {
let derivedRequest: AnyRequest = AnyRequest(request)
try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
let derivedRequest: AnyTypedRequest<Record> = AnyTypedRequest(request)
try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
let derivedRequest: AnyTypedRequest<Row> = request.asRequest(of: Row.self)
try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
let derivedRequest: AdaptedTypedRequest = request.adapted { db in SuffixRowAdapter(fromIndex: 1) }
try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
let derivedRequest: AdaptedRequest = AnyRequest(request).adapted { db in SuffixRowAdapter(fromIndex: 1) }
try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
// SQL request loses region info
let derivedRequest: SQLRequest = try request.asSQLRequest(db)
try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)")
}
}
}
func testUpdateStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)")
let statement = try db.makeUpdateStatement("UPDATE foo SET bar = 'bar', baz = 'baz' WHERE id = 1")
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
XCTAssertEqual(columnNames, Set(["bar", "baz"]))
}
}
func testRowIdNameInSelectStatement() throws {
// Here we test that sqlite authorizer gives the "ROWID" name to
// the rowid column, regardless of its name in the request (rowid, oid, _rowid_)
//
// See also testRowIdNameInUpdateStatement
guard sqlite3_libversion_number() < 3019003 else {
// This test fails on SQLite 3.19.3 (iOS 11.2) and SQLite 3.21.0 (custom build),
// but succeeds on SQLite 3.16.0 (iOS 10.3.1).
// TODO: evaluate the consequences
return
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (name TEXT)")
do {
let statement = try db.makeSelectStatement("SELECT rowid FROM FOO")
let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"])
XCTAssertEqual(statement.fetchedRegion, expectedRegion)
XCTAssertEqual(statement.fetchedRegion.description, "foo(ROWID)")
}
do {
let statement = try db.makeSelectStatement("SELECT _ROWID_ FROM FOO")
let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"])
XCTAssertEqual(statement.fetchedRegion, expectedRegion)
XCTAssertEqual(statement.fetchedRegion.description, "foo(ROWID)")
}
do {
let statement = try db.makeSelectStatement("SELECT oID FROM FOO")
let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"])
XCTAssertEqual(statement.fetchedRegion, expectedRegion)
XCTAssertEqual(statement.fetchedRegion.description, "foo(ROWID)")
}
}
}
func testRowIdNameInUpdateStatement() throws {
// Here we test that sqlite authorizer gives the "ROWID" name to
// the rowid column, regardless of its name in the request (rowid, oid, _rowid_)
//
// See also testRowIdNameInSelectStatement
guard sqlite3_libversion_number() > 3007013 else {
// This test fails on iOS 8.1 (SQLite 3.7.13)
// TODO: evaluate the consequences
return
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (name TEXT)")
do {
let statement = try db.makeUpdateStatement("UPDATE foo SET rowid = 1")
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
XCTAssertEqual(columnNames, ["ROWID"])
}
do {
let statement = try db.makeUpdateStatement("UPDATE foo SET _ROWID_ = 1")
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
XCTAssertEqual(columnNames, ["ROWID"])
}
do {
let statement = try db.makeUpdateStatement("UPDATE foo SET oID = 1")
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
XCTAssertEqual(columnNames, ["ROWID"])
}
}
}
func testInsertStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)")
let statement = try db.makeUpdateStatement("INSERT INTO foo (id, bar) VALUES (1, 'bar')")
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .insert(let tableName) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
}
}
func testDeleteStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)")
let statement = try db.makeUpdateStatement("DELETE FROM foo")
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .delete(let tableName) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
}
}
func testUpdateStatementInvalidatesDatabaseSchemaCache() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
let statement = try db.makeUpdateStatement("CREATE TABLE foo (id INTEGER)")
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
try statement.execute()
}
do {
let statement = try db.makeUpdateStatement("ALTER TABLE foo ADD COLUMN name TEXT")
XCTAssertTrue(statement.invalidatesDatabaseSchemaCache)
}
do {
let statement = try db.makeUpdateStatement("DROP TABLE foo")
XCTAssertTrue(statement.invalidatesDatabaseSchemaCache)
}
}
}
func testRegionIsModifiedByDatabaseEvent() {
do {
// Empty selection
let region = DatabaseRegion()
XCTAssertEqual(region.description, "empty")
do {
let eventKind = DatabaseEventKind.insert(tableName: "foo")
XCTAssertFalse(region.isModified(byEventsOfKind: eventKind))
// Can't test for individual events due to DatabaseRegion.isModified(by:) precondition
}
do {
let eventKind = DatabaseEventKind.delete(tableName: "foo")
XCTAssertFalse(region.isModified(byEventsOfKind: eventKind))
// Can't test for individual events due to DatabaseRegion.isModified(by:) precondition
}
do {
let eventKind = DatabaseEventKind.update(tableName: "foo", columnNames: ["a", "b"])
XCTAssertFalse(region.isModified(byEventsOfKind: eventKind))
// Can't test for individual events due to DatabaseRegion.isModified(by:) precondition
}
}
do {
// Full database selection
let region = DatabaseRegion.fullDatabase
XCTAssertEqual(region.description, "full database")
do {
let tableName = "foo"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.insert(tableName: tableName)
let event = DatabaseEvent(kind: .insert, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event))
}
}
do {
let tableName = "foo"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.delete(tableName: tableName)
let event = DatabaseEvent(kind: .delete, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event))
}
}
do {
let tableName = "foo"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.update(tableName: tableName, columnNames: ["a", "b"])
let event = DatabaseEvent(kind: .update, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event))
}
}
}
do {
// Complex selection
let region = DatabaseRegion(table: "foo")
.union(DatabaseRegion(table: "bar", columns: ["a"])
.intersection(DatabaseRegion(table: "bar", rowIds: [1])))
XCTAssertEqual(region.description, "bar(a)[1],foo(*)")
do {
let tableName = "foo"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.insert(tableName: tableName)
let event1 = DatabaseEvent(kind: .insert, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
let event2 = DatabaseEvent(kind: .insert, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event1))
XCTAssertTrue(region.isModified(by: event2))
}
}
do {
let tableName = "foo"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.delete(tableName: tableName)
let event1 = DatabaseEvent(kind: .delete, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
let event2 = DatabaseEvent(kind: .delete, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event1))
XCTAssertTrue(region.isModified(by: event2))
}
}
do {
let tableName = "foo"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.update(tableName: tableName, columnNames: ["a", "b"])
let event1 = DatabaseEvent(kind: .update, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
let event2 = DatabaseEvent(kind: .update, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event1))
XCTAssertTrue(region.isModified(by: event2))
}
}
do {
let tableName = "bar"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.insert(tableName: tableName)
let event1 = DatabaseEvent(kind: .insert, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
let event2 = DatabaseEvent(kind: .insert, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event1))
XCTAssertFalse(region.isModified(by: event2))
}
}
do {
let tableName = "bar"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.delete(tableName: tableName)
let event1 = DatabaseEvent(kind: .delete, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
let event2 = DatabaseEvent(kind: .delete, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event1))
XCTAssertFalse(region.isModified(by: event2))
}
}
do {
let tableName = "bar"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.update(tableName: tableName, columnNames: ["a", "b"])
let event1 = DatabaseEvent(kind: .update, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
let event2 = DatabaseEvent(kind: .update, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event1))
XCTAssertFalse(region.isModified(by: event2))
}
}
do {
let eventKind = DatabaseEventKind.update(tableName: "bar", columnNames: ["b", "c"])
XCTAssertFalse(region.isModified(byEventsOfKind: eventKind))
// Can't test for individual events due to DatabaseRegion.isModified(by:) precondition
}
do {
let eventKind = DatabaseEventKind.insert(tableName: "qux")
XCTAssertFalse(region.isModified(byEventsOfKind: eventKind))
// Can't test for individual events due to DatabaseRegion.isModified(by:) precondition
}
do {
let eventKind = DatabaseEventKind.delete(tableName: "qux")
XCTAssertFalse(region.isModified(byEventsOfKind: eventKind))
// Can't test for individual events due to DatabaseRegion.isModified(by:) precondition
}
do {
let eventKind = DatabaseEventKind.update(tableName: "qux", columnNames: ["a", "b"])
XCTAssertFalse(region.isModified(byEventsOfKind: eventKind))
// Can't test for individual events due to DatabaseRegion.isModified(by:) precondition
}
}
}
}
@@ -42,9 +42,6 @@ private class Observer : TransactionObserver {
allRecordedEvents.append(event.copy())
}
func databaseWillCommit() throws {
}
func databaseDidCommit(_ db: Database) {
}
+1 -1
View File
@@ -59,7 +59,7 @@ class FTS5PatternTests: GRDBTestCase {
func testInvalidFTS5Pattern() throws {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
let invalidRawPatterns = ["", "?!", "^", "^foo", "NOT", "(", "AND", "OR", "\"", "missing:foo"]
let invalidRawPatterns = ["", "?!", "^", "NOT", "(", "AND", "OR", "\"", "missing:foo"]
for rawPattern in invalidRawPatterns {
do {
_ = try db.makeFTS5Pattern(rawPattern: rawPattern, forTable: "books")
@@ -872,6 +872,42 @@ class FetchedRecordsControllerTests: GRDBTestCase {
XCTFail("Expected DatabaseError")
}
}
func testObservationOfSpecificRowIds() throws {
let dbQueue = try makeDatabaseQueue()
let generalController = try FetchedRecordsController(dbQueue, request: Person.all())
let specificController = try FetchedRecordsController(dbQueue, request: Person.filter(key: 1))
let generalExpectation = expectation(description: "expectation")
generalExpectation.expectedFulfillmentCount = 6
var generalChangeCount = 0
generalController.trackChanges(onChange: { (_, _, _) in
generalChangeCount += 1
generalExpectation.fulfill()
})
try generalController.performFetch()
let specificExpectation = expectation(description: "expectation")
specificExpectation.expectedFulfillmentCount = 3
var specificChangeCount = 0
specificController.trackChanges(onChange: { (_, _, _) in
specificChangeCount += 1
specificExpectation.fulfill()
})
try specificController.performFetch()
try dbQueue.inDatabase { db in
try db.execute("INSERT INTO persons (id, name) VALUES (?, ?)", arguments: [1, "Arthur"])
try db.execute("INSERT INTO persons (id, name) VALUES (?, ?)", arguments: [2, "Barbara"])
try db.execute("UPDATE persons SET name = ? WHERE id = ?", arguments: ["Craig", 1])
try db.execute("UPDATE persons SET name = ? WHERE id = ?", arguments: ["David", 2])
try db.execute("DELETE FROM persons")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(generalChangeCount, 6)
XCTAssertEqual(specificChangeCount, 3)
}
}
@@ -174,9 +174,6 @@ class MutablePersistablePersistenceConflictPolicyTests: GRDBTestCase {
transactionEvents.append(event.copy())
}
func databaseWillCommit() throws {
}
func databaseDidCommit(_ db: Database) {
events = transactionEvents
transactionEvents = []
@@ -186,11 +183,6 @@ class MutablePersistablePersistenceConflictPolicyTests: GRDBTestCase {
events = []
transactionEvents = []
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) {
}
#endif
}
let dbQueue = try makeDatabaseQueue()
@@ -310,6 +310,76 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalRowID()
try record1.insert(db)
let record2 = MinimalRowID()
try record2.insert(db)
do {
let cursor = try MinimalRowID.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try MinimalRowID.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try MinimalRowID.filter(keys: [["id": record1.id], ["id": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.id!, record1.id!)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalRowID()
try record1.insert(db)
let record2 = MinimalRowID()
try record2.insert(db)
do {
let fetchedRecords = try MinimalRowID.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try MinimalRowID.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
}
do {
let fetchedRecords = try MinimalRowID.filter(keys: [["id": record1.id], ["id": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.id, record1.id!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalRowID()
try record.insert(db)
let fetchedRecord = try MinimalRowID.filter(key: ["id": record.id]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.id == record.id)
}
}
// MARK: - Fetch With Primary Key
@@ -379,6 +449,75 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalRowID()
try record1.insert(db)
let record2 = MinimalRowID()
try record2.insert(db)
do {
let ids: [Int64] = []
let cursor = try MinimalRowID.filter(keys: ids).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let ids = [record1.id!, record2.id!]
let cursor = try MinimalRowID.filter(keys: ids).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalRowID()
try record1.insert(db)
let record2 = MinimalRowID()
try record2.insert(db)
do {
let ids: [Int64] = []
let fetchedRecords = try MinimalRowID.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let ids = [record1.id!, record2.id!]
let fetchedRecords = try MinimalRowID.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalRowID()
try record.insert(db)
do {
let id: Int64? = nil
let fetchedRecord = try MinimalRowID.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try MinimalRowID.filter(key: record.id).fetchOne(db)!
XCTAssertTrue(fetchedRecord.id == record.id)
}
}
}
// MARK: - Exists
@@ -321,6 +321,81 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalSingle()
record1.UUID = "theUUID1"
try record1.insert(db)
let record2 = MinimalSingle()
record2.UUID = "theUUID2"
try record2.insert(db)
do {
let cursor = try MinimalSingle.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.UUID!, record1.UUID!)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalSingle()
record1.UUID = "theUUID1"
try record1.insert(db)
let record2 = MinimalSingle()
record2.UUID = "theUUID2"
try record2.insert(db)
do {
let fetchedRecords = try MinimalSingle.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
}
do {
let fetchedRecords = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.UUID, record1.UUID!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
let fetchedRecord = try MinimalSingle.filter(key: ["UUID": record.UUID]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
}
}
// MARK: - Fetch With Primary Key
@@ -395,6 +470,80 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalSingle()
record1.UUID = "theUUID1"
try record1.insert(db)
let record2 = MinimalSingle()
record2.UUID = "theUUID2"
try record2.insert(db)
do {
let UUIDs: [String] = []
let cursor = try MinimalSingle.filter(keys: UUIDs).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let cursor = try MinimalSingle.filter(keys: UUIDs).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalSingle()
record1.UUID = "theUUID1"
try record1.insert(db)
let record2 = MinimalSingle()
record2.UUID = "theUUID2"
try record2.insert(db)
do {
let UUIDs: [String] = []
let fetchedRecords = try MinimalSingle.filter(keys: UUIDs).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let fetchedRecords = try MinimalSingle.filter(keys: UUIDs).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
do {
let id: String? = nil
let fetchedRecord = try MinimalSingle.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try MinimalSingle.filter(key: record.UUID).fetchOne(db)!
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
}
}
}
// MARK: - Exists
@@ -390,6 +390,79 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let cursor = try Person.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try Person.filter(keys: [["rowid": record1.id], ["rowid": record2.id]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try Person.filter(keys: [["rowid": record1.id], ["rowid": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.id!, record1.id!)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let fetchedRecords = try Person.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try Person.filter(keys: [["rowid": record1.id], ["rowid": record2.id]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
}
do {
let fetchedRecords = try Person.filter(keys: [["rowid": record1.id], ["rowid": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.id, record1.id!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Person(name: "Arthur")
try record.insert(db)
let fetchedRecord = try Person.filter(key: ["rowid": record.id]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.id == record.id)
XCTAssertTrue(fetchedRecord.name == record.name)
XCTAssertTrue(fetchedRecord.age == record.age)
XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond.
}
}
// MARK: - Fetch With Primary Key
@@ -462,6 +535,78 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let ids: [Int64] = []
let cursor = try Person.filter(keys: ids).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let ids = [record1.id!, record2.id!]
let cursor = try Person.filter(keys: ids).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let ids: [Int64] = []
let fetchedRecords = try Person.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let ids = [record1.id!, record2.id!]
let fetchedRecords = try Person.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Person(name: "Arthur")
try record.insert(db)
do {
let id: Int64? = nil
let fetchedRecord = try Person.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try Person.filter(key: record.id).fetchOne(db)!
XCTAssertTrue(fetchedRecord.id == record.id)
XCTAssertTrue(fetchedRecord.name == record.name)
XCTAssertTrue(fetchedRecord.age == record.age)
XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond.
}
}
}
// MARK: - Exists
@@ -344,6 +344,78 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Citizenship(personName: "Arthur", countryName: "France", native: true)
try record1.insert(db)
let record2 = Citizenship(personName: "Barbara", countryName: "France", native: false)
try record2.insert(db)
do {
let cursor = try Citizenship.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": record2.personName, "countryName": record2.countryName]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.personName }), Set([record1.personName, record2.personName]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": nil, "countryName": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.personName, record1.personName)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Citizenship(personName: "Arthur", countryName: "France", native: true)
try record1.insert(db)
let record2 = Citizenship(personName: "Barbara", countryName: "France", native: false)
try record2.insert(db)
do {
let fetchedRecords = try Citizenship.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": record2.personName, "countryName": record2.countryName]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.personName }), Set([record1.personName, record2.personName]))
}
do {
let fetchedRecords = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": nil, "countryName": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.personName, record1.personName!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Citizenship(personName: "Arthur", countryName: "France", native: true)
try record.insert(db)
let fetchedRecord = try Citizenship.filter(key: ["personName": record.personName, "countryName": record.countryName]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.personName == record.personName)
XCTAssertTrue(fetchedRecord.countryName == record.countryName)
XCTAssertTrue(fetchedRecord.native == record.native)
}
}
// MARK: - Exists
@@ -103,6 +103,20 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Item(email: "item@example.com")
try record.insert(db)
let fetchedRecord = try Item.filter(key: ["email": record.email]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.email == record.email)
}
}
// MARK: - Fetch With Primary Key
@@ -176,4 +190,78 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
}
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Item(name: "Table")
try record1.insert(db)
let id1 = db.lastInsertedRowID
let record2 = Item(name: "Chair")
try record2.insert(db)
let id2 = db.lastInsertedRowID
do {
let ids: [Int64] = []
let cursor = try Item.filter(keys: ids).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let ids = [id1, id2]
let cursor = try Item.filter(keys: ids).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.name! }), Set([record1, record2].map { $0.name! }))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Item(name: "Table")
try record1.insert(db)
let id1 = db.lastInsertedRowID
let record2 = Item(name: "Chair")
try record2.insert(db)
let id2 = db.lastInsertedRowID
do {
let ids: [Int64] = []
let fetchedRecords = try Item.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let ids = [id1, id2]
let fetchedRecords = try Item.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.name! }), Set([record1, record2].map { $0.name! }))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Item(name: "Table")
try record.insert(db)
let id = db.lastInsertedRowID
do {
let id: Int64? = nil
let fetchedRecord = try Item.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try Item.filter(key: id).fetchOne(db)!
XCTAssertTrue(fetchedRecord.name == record.name)
}
}
}
}
@@ -386,6 +386,79 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let cursor = try Person.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try Person.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try Person.filter(keys: [["id": record1.id], ["id": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.id!, record1.id!)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let fetchedRecords = try Person.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try Person.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
}
do {
let fetchedRecords = try Person.filter(keys: [["id": record1.id], ["id": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.id, record1.id!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Person(name: "Arthur")
try record.insert(db)
let fetchedRecord = try Person.filter(key: ["id": record.id]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.id == record.id)
XCTAssertTrue(fetchedRecord.name == record.name)
XCTAssertTrue(fetchedRecord.age == record.age)
XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond.
}
}
// MARK: - Fetch With Primary Key
@@ -458,6 +531,78 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let ids: [Int64] = []
let cursor = try Person.filter(keys: ids).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let ids = [record1.id!, record2.id!]
let cursor = try Person.filter(keys: ids).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let ids: [Int64] = []
let fetchedRecords = try Person.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let ids = [record1.id!, record2.id!]
let fetchedRecords = try Person.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Person(name: "Arthur")
try record.insert(db)
do {
let id: Int64? = nil
let fetchedRecord = try Person.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try Person.filter(key: record.id).fetchOne(db)!
XCTAssertTrue(fetchedRecord.id == record.id)
XCTAssertTrue(fetchedRecord.name == record.name)
XCTAssertTrue(fetchedRecord.age == record.age)
XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond.
}
}
}
// MARK: - Exists
@@ -336,6 +336,77 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let cursor = try Pet.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.UUID!, record1.UUID!)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let fetchedRecords = try Pet.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
}
do {
let fetchedRecords = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.UUID, record1.UUID!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
let fetchedRecord = try Pet.filter(key: ["UUID": record.UUID]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
XCTAssertTrue(fetchedRecord.name == record.name)
}
}
// MARK: - Fetch With Primary Key
@@ -406,6 +477,76 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let UUIDs: [String] = []
let cursor = try Pet.filter(keys: UUIDs).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let cursor = try Pet.filter(keys: UUIDs).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let UUIDs: [String] = []
let fetchedRecords = try Pet.filter(keys: UUIDs).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let fetchedRecords = try Pet.filter(keys: UUIDs).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
do {
let id: String? = nil
let fetchedRecord = try Pet.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try Pet.filter(key: record.UUID).fetchOne(db)!
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
XCTAssertTrue(fetchedRecord.name == record.name)
}
}
}
// MARK: - Exists
@@ -327,6 +327,81 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Email()
record1.email = "me@domain.com"
try record1.insert(db)
let record2 = Email()
record2.email = "you@domain.com"
try record2.insert(db)
do {
let cursor = try Email.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try Email.filter(keys: [["email": record1.email], ["email": record2.email]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.email }), Set([record1.email, record2.email]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try Email.filter(keys: [["email": record1.email], ["email": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.email, record1.email)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Email()
record1.email = "me@domain.com"
try record1.insert(db)
let record2 = Email()
record2.email = "you@domain.com"
try record2.insert(db)
do {
let fetchedRecords = try Email.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try Email.filter(keys: [["email": record1.email], ["email": record2.email]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.email }), Set([record1.email, record2.email]))
}
do {
let fetchedRecords = try Email.filter(keys: [["email": record1.email], ["email": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.email, record1.email!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Email()
record.email = "me@domain.com"
try record.insert(db)
let fetchedRecord = try Email.filter(key: ["email": record.email]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.email == record.email)
}
}
// MARK: - Fetch With Primary Key
@@ -401,6 +476,80 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Email()
record1.email = "me@domain.com"
try record1.insert(db)
let record2 = Email()
record2.email = "you@domain.com"
try record2.insert(db)
do {
let emails: [String] = []
let cursor = try Email.filter(keys: emails).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let emails = [record1.email!, record2.email!]
let cursor = try Email.filter(keys: emails).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.email! }), Set(emails))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Email()
record1.email = "me@domain.com"
try record1.insert(db)
let record2 = Email()
record2.email = "you@domain.com"
try record2.insert(db)
do {
let emails: [String] = []
let fetchedRecords = try Email.filter(keys: emails).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let emails = [record1.email!, record2.email!]
let fetchedRecords = try Email.filter(keys: emails).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.email }), Set(emails))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Email()
record.email = "me@domain.com"
try record.insert(db)
do {
let id: String? = nil
let fetchedRecord = try Email.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try Email.filter(key: record.email).fetchOne(db)!
XCTAssertTrue(fetchedRecord.email == record.email)
}
}
}
// MARK: - Exists
+3 -19
View File
@@ -15,29 +15,13 @@ private struct Person : RowConvertible, TableMapping {
class RecordUniqueIndexTests: GRDBTestCase {
func testKeyFilterRequiresUniqueIndex() throws {
func testKeyFilterAcceptsUniqueIndex() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
_ = try Person.filter(db, keys: [["id": nil]])
_ = try Person.filter(db, keys: [["email": nil]])
do {
_ = try Person.filter(db, keys: [["id": nil, "email": nil]], fatalErrorOnMissingUniqueIndex: false)
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_MISUSE)
XCTAssertEqual(error.message!, "table persons has no unique index on column(s) email, id")
XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) email, id")
}
do {
_ = try Person.filter(db, keys: [["name": nil]], fatalErrorOnMissingUniqueIndex: false)
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_MISUSE)
XCTAssertEqual(error.message!, "table persons has no unique index on column(s) name")
XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) name")
}
_ = try Person.filter(keys: [["id": nil]]).fetchOne(db)
_ = try Person.filter(keys: [["email": nil]]).fetchOne(db)
}
}
}
+17 -21
View File
@@ -21,33 +21,29 @@ class SchedulingWatchdogTests: GRDBTestCase {
dbQueue2.inDatabase { db2 = $0 }
dbQueue3.inDatabase { db3 = $0 }
XCTAssertFalse(SchedulingWatchdog.allows(db1))
XCTAssertFalse(SchedulingWatchdog.allows(db2))
XCTAssertFalse(SchedulingWatchdog.allows(db3))
XCTAssertNil(SchedulingWatchdog.current)
dbQueue1.inDatabase { _ in
XCTAssertTrue(SchedulingWatchdog.allows(db1))
XCTAssertFalse(SchedulingWatchdog.allows(db2))
XCTAssertFalse(SchedulingWatchdog.allows(db3))
XCTAssertTrue(SchedulingWatchdog.current!.allows(db1))
XCTAssertFalse(SchedulingWatchdog.current!.allows(db2))
XCTAssertFalse(SchedulingWatchdog.current!.allows(db3))
dbQueue2.inDatabase { _ in
XCTAssertTrue(SchedulingWatchdog.allows(db1))
XCTAssertTrue(SchedulingWatchdog.allows(db2))
XCTAssertFalse(SchedulingWatchdog.allows(db3))
XCTAssertTrue(SchedulingWatchdog.current!.allows(db1))
XCTAssertTrue(SchedulingWatchdog.current!.allows(db2))
XCTAssertFalse(SchedulingWatchdog.current!.allows(db3))
dbQueue3.inDatabase { _ in
XCTAssertTrue(SchedulingWatchdog.allows(db1))
XCTAssertTrue(SchedulingWatchdog.allows(db2))
XCTAssertTrue(SchedulingWatchdog.allows(db3))
XCTAssertTrue(SchedulingWatchdog.current!.allows(db1))
XCTAssertTrue(SchedulingWatchdog.current!.allows(db2))
XCTAssertTrue(SchedulingWatchdog.current!.allows(db3))
}
XCTAssertTrue(SchedulingWatchdog.allows(db1))
XCTAssertTrue(SchedulingWatchdog.allows(db2))
XCTAssertFalse(SchedulingWatchdog.allows(db3))
XCTAssertTrue(SchedulingWatchdog.current!.allows(db1))
XCTAssertTrue(SchedulingWatchdog.current!.allows(db2))
XCTAssertFalse(SchedulingWatchdog.current!.allows(db3))
}
XCTAssertTrue(SchedulingWatchdog.allows(db1))
XCTAssertFalse(SchedulingWatchdog.allows(db3))
XCTAssertFalse(SchedulingWatchdog.allows(db2))
XCTAssertTrue(SchedulingWatchdog.current!.allows(db1))
XCTAssertFalse(SchedulingWatchdog.current!.allows(db3))
XCTAssertFalse(SchedulingWatchdog.current!.allows(db2))
}
XCTAssertFalse(SchedulingWatchdog.allows(db1))
XCTAssertFalse(SchedulingWatchdog.allows(db2))
XCTAssertFalse(SchedulingWatchdog.allows(db3))
XCTAssertNil(SchedulingWatchdog.current)
}
func testDatabaseQueueFromDatabaseQueue() throws {
+19 -21
View File
@@ -128,28 +128,26 @@ class SelectStatementTests : GRDBTestCase {
}
}
func testSelectionInfo() throws {
func testRegion() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
class Observer: TransactionObserver {
private var didChange = false
var triggered = false
let selectionInfo: SelectStatement.SelectionInfo
let region: DatabaseRegion
init(selectionInfo: SelectStatement.SelectionInfo) {
self.selectionInfo = selectionInfo
init(region: DatabaseRegion) {
self.region = region
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return eventKind.impacts(selectionInfo)
return region.isModified(byEventsOfKind: eventKind)
}
func databaseDidChange(with event: DatabaseEvent) {
didChange = true
}
func databaseWillCommit() throws { }
func databaseDidCommit(_ db: Database) {
triggered = didChange
didChange = false
@@ -158,16 +156,12 @@ class SelectStatementTests : GRDBTestCase {
func databaseDidRollback(_ db: Database) {
didChange = false
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
}
try db.create(table: "table1") { t in
t.column("id", .integer).primaryKey()
t.column("id3", .integer).notNull().references("table3", column: "id", onDelete: .cascade, onUpdate: .cascade)
t.column("id4", .integer).references("table4", column: "id", onDelete: .setNull, onUpdate: .setNull)
t.column("id3", .integer).references("table3", column: "id", onDelete: .cascade, onUpdate: .cascade)
t.column("id4", .integer).references("table4", column: "id", onDelete: .setNull, onUpdate: .cascade)
t.column("a", .integer)
t.column("b", .integer)
}
@@ -185,7 +179,7 @@ class SelectStatementTests : GRDBTestCase {
try db.create(table: "table5") { t in
t.column("id", .integer).primaryKey()
}
try db.execute("CREATE TRIGGER table5trigger AFTER INSERT ON table5 BEGIN DELETE FROM table1; END")
try db.execute("CREATE TRIGGER table5trigger AFTER INSERT ON table5 BEGIN INSERT INTO table1 (id3, id4, a, b) VALUES (NULL, NULL, 0, 0); END")
let statements = try [
db.makeSelectStatement("SELECT * FROM table1"),
@@ -193,7 +187,7 @@ class SelectStatementTests : GRDBTestCase {
db.makeSelectStatement("SELECT table1.id, table1.a, table2.a FROM table1 JOIN table2 ON table1.id = table2.id"),
// This last request triggers its observer or not, depending on the SQLite version.
// Before SQLite 3.19.0, its selectionInfo is doubtful, and every database change is deemed impactful.
// Before SQLite 3.19.0, its region is doubtful, and every database change is deemed impactful.
// Starting SQLite 3.19.0, it knows that only table1 is involved.
//
// See doubtfulCountFunction below
@@ -202,11 +196,11 @@ class SelectStatementTests : GRDBTestCase {
let doubtfulCountFunction = (sqlite3_libversion_number() < 3019000)
let observers = statements.map { Observer(selectionInfo: $0.selectionInfo) }
let observers = statements.map { Observer(region: $0.fetchedRegion) }
if doubtfulCountFunction {
XCTAssertEqual(observers.map { $0.selectionInfo.description }, ["table1(a,b,id,id3,id4)","table1(a,id,id3)", "table1(a,id),table2(a,id)", "unknown"])
XCTAssertEqual(observers.map { $0.region.description }, ["table1(a,b,id,id3,id4)","table1(a,id,id3)", "table1(a,id),table2(a,id)", "full database"])
} else {
XCTAssertEqual(observers.map { $0.selectionInfo.description }, ["table1(a,b,id,id3,id4)","table1(a,id,id3)", "table1(a,id),table2(a,id)", "table1(*)"])
XCTAssertEqual(observers.map { $0.region.description }, ["table1(a,b,id,id3,id4)","table1(a,id,id3)", "table1(a,id),table2(a,id)", "table1(*)"])
}
for observer in observers {
@@ -239,12 +233,16 @@ class SelectStatementTests : GRDBTestCase {
try db.execute("UPDATE table4 SET id = 2 WHERE id = 1")
XCTAssertEqual(observers.map { $0.triggered }, [true, false, false, true])
try db.execute("DELETE FROM table3")
XCTAssertEqual(observers.map { $0.triggered }, [true, true, true, true])
try db.execute("DELETE FROM table4")
XCTAssertEqual(observers.map { $0.triggered }, [true, false, false, true])
try db.execute("INSERT INTO table4 (id) VALUES (1)")
try db.execute("DELETE FROM table4")
XCTAssertEqual(observers.map { $0.triggered }, [false, false, false, doubtfulCountFunction])
try db.execute("DELETE FROM table3")
XCTAssertEqual(observers.map { $0.triggered }, [true, true, true, true])
try db.execute("INSERT INTO table5 (id) VALUES (NULL)")
XCTAssertEqual(observers.map { $0.triggered }, [true, true, true, true])
}
@@ -1,89 +0,0 @@
import XCTest
#if GRDBCIPHER
@testable import GRDBCipher
#elseif GRDBCUSTOMSQLITE
@testable import GRDBCustomSQLite
#else
@testable import GRDB
#endif
class StatementSelectionInfoTests : GRDBTestCase {
func testSelectStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER, name TEXT)")
try db.execute("CREATE TABLE bar (id INTEGER, fooId INTEGER)")
let statement = try db.makeSelectStatement("SELECT foo.name FROM FOO JOIN BAR ON fooId = foo.id")
XCTAssertTrue(statement.selectionInfo.contains(anyColumnIn: ["id"], from: "foo"))
XCTAssertTrue(statement.selectionInfo.contains(anyColumnIn: ["name"], from: "foo"))
XCTAssertFalse(statement.selectionInfo.contains(anyColumnIn: ["id"], from: "bar"))
XCTAssertTrue(statement.selectionInfo.contains(anyColumnIn: ["fooId"], from: "bar"))
}
}
func testUpdateStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)")
let statement = try db.makeUpdateStatement("UPDATE foo SET bar = 'bar', baz = 'baz' WHERE id = 1")
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
XCTAssertEqual(columnNames, Set(["bar", "baz"]))
}
}
func testInsertStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)")
let statement = try db.makeUpdateStatement("INSERT INTO foo (id, bar) VALUES (1, 'bar')")
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .insert(let tableName) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
}
}
func testDeleteStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)")
let statement = try db.makeUpdateStatement("DELETE FROM foo")
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .delete(let tableName) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
}
}
func testUpdateStatementInvalidatesDatabaseSchemaCache() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
let statement = try db.makeUpdateStatement("CREATE TABLE foo (id INTEGER)")
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
try statement.execute()
}
do {
let statement = try db.makeUpdateStatement("ALTER TABLE foo ADD COLUMN name TEXT")
XCTAssertTrue(statement.invalidatesDatabaseSchemaCache)
}
do {
let statement = try db.makeUpdateStatement("DROP TABLE foo")
XCTAssertTrue(statement.invalidatesDatabaseSchemaCache)
}
}
}
}
@@ -26,9 +26,6 @@ private class Observer : TransactionObserver {
events.append(event.copy())
}
func databaseWillCommit() throws {
}
func databaseDidCommit(_ db: Database) {
lastCommittedEvents = events
events = []
+211 -1
View File
@@ -1556,5 +1556,215 @@ class TransactionObserverTests: GRDBTestCase {
XCTAssertEqual(observer.lastCommittedEvents.count, 2)
}
}
}
func testComplexFilteredDatabaseEvents() throws {
// When a statement impact several tables, only filtered events are
// notified
do {
let dbQueue = try makeDatabaseQueue()
// Observe deletions in table b
let observer = Observer(observes: { eventKind in
if case .delete(tableName: let tableName) = eventKind {
return tableName == "b"
}
return false
})
dbQueue.add(transactionObserver: observer)
// Delete from a and trigger b deletion
try dbQueue.inTransaction { db in
try db.execute("""
CREATE TABLE a(id INTEGER PRIMARY KEY);
CREATE TABLE b(id INTEGER PRIMARY KEY REFERENCES a(id) ON DELETE CASCADE);
INSERT INTO a (id) VALUES (42);
INSERT INTO b (id) VALUES (42);
DELETE FROM a;
""")
return .commit
}
XCTAssertEqual(observer.didChangeCount, 1)
XCTAssertEqual(observer.willCommitCount, 1)
XCTAssertEqual(observer.didCommitCount, 1)
XCTAssertEqual(observer.didRollbackCount, 0)
XCTAssertEqual(observer.lastCommittedEvents.count, 1)
XCTAssertTrue(match(event: observer.lastCommittedEvents[0], kind: .delete, tableName: "b", rowId: 42))
}
do {
let dbQueue = try makeDatabaseQueue()
// Observe deletions in table b
let observer = Observer(observes: { eventKind in
if case .delete(tableName: let tableName) = eventKind {
return tableName == "b"
}
return false
})
dbQueue.add(transactionObserver: observer)
// Insert into c and trigger b deletion
try dbQueue.inTransaction { db in
try db.execute("""
CREATE TABLE a(id INTEGER PRIMARY KEY);
CREATE TABLE b(id INTEGER PRIMARY KEY);
CREATE TABLE c(id INTEGER);
INSERT INTO b (id) VALUES (42);
CREATE TRIGGER t AFTER INSERT ON c BEGIN DELETE FROM b; END;
INSERT INTO c (id) VALUES (1);
""")
return .commit
}
XCTAssertEqual(observer.didChangeCount, 1)
XCTAssertEqual(observer.willCommitCount, 1)
XCTAssertEqual(observer.didCommitCount, 1)
XCTAssertEqual(observer.didRollbackCount, 0)
XCTAssertEqual(observer.lastCommittedEvents.count, 1)
XCTAssertTrue(match(event: observer.lastCommittedEvents[0], kind: .delete, tableName: "b", rowId: 42))
}
}
func testStopObservingDatabaseChangesUntilNextTransaction() throws {
let dbQueue = try makeDatabaseQueue()
class Observer: TransactionObserver {
var didChangeCount: Int = 0
var willCommitCount: Int = 0
var didCommitCount: Int = 0
var didRollbackCount: Int = 0
func resetCounts() {
didChangeCount = 0
willCommitCount = 0
didCommitCount = 0
didRollbackCount = 0
#if SQLITE_ENABLE_PREUPDATE_HOOK
willChangeCount = 0
#endif
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
var willChangeCount: Int = 0
func databaseWillChange(with event: DatabasePreUpdateEvent) {
willChangeCount += 1
}
#endif
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return true
}
func databaseDidChange(with event: DatabaseEvent) {
didChangeCount += 1
if event.tableName == "ignore" {
stopObservingDatabaseChangesUntilNextTransaction()
}
}
func databaseWillCommit() throws {
willCommitCount += 1
}
func databaseDidCommit(_ db: Database) {
didCommitCount += 1
}
func databaseDidRollback(_ db: Database) {
didRollbackCount += 1
}
}
let observer = Observer()
dbQueue.add(transactionObserver: observer)
try dbQueue.inDatabase { db in
try db.create(table: "ignore") { t in
// `INSERT INTO ignore DEFAULT VALUES` triggers an
// "ignore event" for Observer.
t.column("c").defaults(to: 1)
}
try db.create(table: "persons") { t in
t.column("name", .text)
}
}
try dbQueue.inDatabase { db in
// Don't ignore anything
do {
observer.resetCounts()
try db.inTransaction {
try db.execute("INSERT INTO persons (name) VALUES ('a')")
try db.execute("DELETE FROM persons")
return .commit
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
XCTAssertEqual(observer.willChangeCount, 2)
#endif
XCTAssertEqual(observer.didChangeCount, 2)
XCTAssertEqual(observer.willCommitCount, 1)
XCTAssertEqual(observer.didCommitCount, 1)
XCTAssertEqual(observer.didRollbackCount, 0)
}
// Ignore 1
do {
observer.resetCounts()
try db.inTransaction {
try db.execute("INSERT INTO ignore DEFAULT VALUES")
try db.execute("INSERT INTO persons (name) VALUES ('a')")
try db.execute("DELETE FROM persons")
return .commit
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
XCTAssertEqual(observer.willChangeCount, 1)
#endif
XCTAssertEqual(observer.didChangeCount, 1)
XCTAssertEqual(observer.willCommitCount, 1)
XCTAssertEqual(observer.didCommitCount, 1)
XCTAssertEqual(observer.didRollbackCount, 0)
}
// Ignore 2
do {
observer.resetCounts()
try db.inTransaction {
try db.execute("INSERT INTO persons (name) VALUES ('a')")
try db.execute("INSERT INTO ignore DEFAULT VALUES")
try db.execute("DELETE FROM persons")
return .commit
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
XCTAssertEqual(observer.willChangeCount, 2)
#endif
XCTAssertEqual(observer.didChangeCount, 2)
XCTAssertEqual(observer.willCommitCount, 1)
XCTAssertEqual(observer.didCommitCount, 1)
XCTAssertEqual(observer.didRollbackCount, 0)
}
// Ignore 3
do {
observer.resetCounts()
try db.inTransaction {
try db.execute("INSERT INTO persons (name) VALUES ('a')")
try db.execute("DELETE FROM persons")
try db.execute("INSERT INTO ignore DEFAULT VALUES")
return .commit
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
XCTAssertEqual(observer.willChangeCount, 3)
#endif
XCTAssertEqual(observer.didChangeCount, 3)
XCTAssertEqual(observer.willCommitCount, 1)
XCTAssertEqual(observer.didCommitCount, 1)
XCTAssertEqual(observer.didRollbackCount, 0)
}
}
}
}
@@ -43,18 +43,12 @@ class TruncateOptimizationTests: GRDBTestCase {
return true
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
func databaseDidChange(with event: DatabaseEvent) {
if case .delete = event.kind {
deletionEvents[event.tableName, default: 0] += 1
}
}
func databaseWillCommit() throws { }
func databaseDidCommit(_ db: Database) {
if !deletionEvents.isEmpty {
notify(deletionEvents)