Compare commits

...
166 Commits
Author SHA1 Message Date
Gwendal Roué 402b7001ee v2.7.0 2018-01-21 17:07:39 +01:00
Gwendal Roué f7d0979fb1 Remove ExtendingGRDB guide 2018-01-21 17:05:38 +01:00
Gwendal Roué 2289ed9d95 Cleanup Jazzy documentation from most redundant definitions and experimental APIs 2018-01-21 16:57:43 +01:00
Gwendal Roué dfcb44016f Enhance CHANGELOG 2018-01-21 15:19:55 +01:00
Gwendal Roué 37a434a615 Merge pull request #289 from groue/RecordBox
Bring changes tracking to any record type
2018-01-21 13:16:35 +01:00
Gwendal Roué 0ddcf1e401 RecordBox documentation 2018-01-21 13:14:14 +01:00
Gwendal Roué 0aa673f24e RecordBox consequence: more TODO 2018-01-21 12:05:41 +01:00
Gwendal Roué b3a24daa2f Documentation tweaks 2018-01-21 07:49:13 +01:00
Gwendal Roué 8c6954cd75 RecordBox documentation 2018-01-21 07:35:52 +01:00
Gwendal Roué 283f08de07 RecordBox changelog 2018-01-20 20:26:37 +01:00
Gwendal Roué d96543ddeb RecordBox documentation 2018-01-20 20:26:37 +01:00
Gwendal Roué 4b320f3cb5 RecordBox documentation 2018-01-20 20:26:37 +01:00
Gwendal Roué 69a6d3e3f3 RecordBox documentation 2018-01-20 20:26:36 +01:00
Gwendal Roué 93d4587732 RecordBox 2018-01-20 20:26:36 +01:00
Gwendal Roué 7481b9788a Run truncate optimization tests with and without transaction observer
This topic is sooo touchy...
2018-01-20 20:26:10 +01:00
Gwendal Roué acf3e0b397 TODO 2018-01-20 19:54:19 +01:00
Gwendal Roué 88ae0fa059 TODO 2018-01-20 17:59:54 +01:00
Gwendal Roué a1e63d9028 Fix management of current transaction observation broker (and discover a new SQLite oddity) 2018-01-20 16:11:05 +01:00
Gwendal Roué 2a1ad8d31c TODO 2018-01-20 09:09:32 +01:00
Gwendal Roué ba7cd2160f TODO 2018-01-20 06:09:44 +01:00
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
Gwendal Roué c6ab92e60a v2.4.2 2018-01-06 14:35:05 +01:00
Gwendal Roué c0d5f3019b generatePerformanceReport reads versions of tested libraries from info.plist files 2018-01-06 13:37:30 +01:00
Gwendal Roué b09d5c3833 Fix FMDB performance tests 2018-01-06 12:47:01 +01:00
Gwendal Roué 3eff1b48b1 Update copyright year 2018-01-06 12:33:32 +01:00
Gwendal Roué a12fffc4e7 Update documentation about readFromCurrentState 2018-01-06 10:04:41 +01:00
Gwendal Roué 94715130fc DatabaseWriter.readFromCurrentState(_:) now fails with a fatal error if a transaction is currently opened 2018-01-06 09:19:26 +01:00
Gwendal Roué 313188ca0e More TODO 2018-01-05 19:40:55 +01:00
Gwendal Roué 5a68b008c6 CHANGELOG 2018-01-02 13:34:23 +01:00
Gwendal Roué 6fe9098c76 Statement compilation cleanup 2018-01-02 13:10:11 +01:00
Gwendal Roué 631a914acd Fix failing test for schema cache shared between DatabasePool reader and writer (stop sharing cache) 2018-01-02 13:08:41 +01:00
Gwendal Roué d1f24c9722 More TODO 2017-12-28 17:48:15 +01:00
Gwendal Roué 7b76c9319a Failing test for schema cache shared between DatabasePool reader and writer 2017-12-28 14:16:36 +01:00
Gwendal Roué 63083c5d1e Less TODO 2017-12-28 13:56:54 +01:00
Gwendal Roué c51a3cd624 Statement compilation cleanup 2017-12-17 13:57:35 +01:00
Gwendal Roué 1fadb7485a Less TODO 2017-12-17 13:14:15 +01:00
Gwendal Roué 58e05d13d1 v2.4.1 2017-12-16 15:09:59 +01:00
Gwendal Roué d8c9692d4d Fix typo 2017-12-16 14:40:58 +01:00
Gwendal Roué f83ffd3a25 Remove unused file 2017-12-16 14:35:09 +01:00
Gwendal Roué d12ff2a92b Scripts that generate performance comparison report 2017-12-16 14:35:02 +01:00
Gwendal Roué 8709d6f9a9 FMDB 2.7.4 2017-12-16 14:25:24 +01:00
Gwendal Roué e2806c55ff Upgrade Makefile test_performance target for Xcode 9.2 and Swift 4.0.3 2017-12-16 13:44:19 +01:00
Gwendal Roué 08d6c843d6 Upgrade performance comparison tests for Xcode 9.2 and Swift 4.0.3 2017-12-16 13:42:53 +01:00
Gwendal Roué 0da3726a89 Realm 3.0.2 2017-12-16 13:36:13 +01:00
Gwendal Roué 36676bcad3 SQLite.swift 0.11.4 2017-12-16 13:33:36 +01:00
Gwendal Roué 1509e1e9a8 Clean up projects & workspace 2017-12-16 13:29:05 +01:00
Gwendal Roué 4c71dd9ebe Remove compiler warning 2017-12-16 13:14:07 +01:00
Gwendal Roué ef8d0d6334 TODO.md 2017-12-15 18:49:36 +01:00
Gwendal Roué 7477b7a173 CHANGELOG.md 2017-12-13 08:24:14 +01:00
Gwendal Roué 246f36821b Merge pull request #284 from groue/Issue283
Don't call sqlite3_config() unless explicitly required to do so
2017-12-13 08:10:57 +01:00
Gwendal Roué d567ee60bf Remove compiler warning 2017-12-08 10:51:31 +01:00
Gwendal Roué 3a157d2808 Test for global SQLite error log requires global variables 2017-12-08 10:51:20 +01:00
Gwendal Roué 7d0c2f9ef8 Fix tests for Database.logError 2017-12-08 10:03:27 +01:00
Gwendal Roué f356f8734a Update Database.logError documentation, and make it clear that it has to be called very very early. 2017-12-07 13:35:19 +01:00
Gwendal Roué 5b7f4a7ff5 Call sqlite3_config(SQLITE_CONFIG_LOG, ...) if and only if Database.logError is set. 2017-12-07 13:14:49 +01:00
Gwendal Roué e10efca17a Fix typo 2017-12-03 16:27:59 +01:00
Gwendal Roué 578b9a5275 v2.4.0 2017-12-03 16:04:07 +01:00
Gwendal Roué 63304b3d12 Merge pull request #281 from groue/DropSynchronizationTriggers
Drop full-text synchronization triggers
2017-12-03 15:57:08 +01:00
Gwendal Roué 39f6ca0035 Merge branch 'master' into DropSynchronizationTriggers 2017-12-03 15:56:23 +01:00
Gwendal Roué 5e3c62c963 Merge pull request #282 from groue/preventXcodeWarningsForMissingFiles
Prevent Xcode warnings for missing files
2017-12-03 15:55:14 +01:00
Gwendal Roué 6966600223 Fix scheme references to projects 2017-12-03 14:41:16 +01:00
Gwendal Roué e028cbb6d5 Declare new GRDBCipher.xcodeproj and GRDBCustom.xcodeproj in CHANGELOG.md 2017-12-03 14:37:21 +01:00
Gwendal Roué 8b3c3f48a8 Update documention for embedding GRDBCipher & GRDBCustom 2017-12-03 14:23:49 +01:00
Gwendal Roué 2d84e72097 Restore GRDBOSXPerformanceComparisonTests 2017-12-03 14:20:08 +01:00
Gwendal Roué d91fe7b633 Extract GRDBCipher.xcodeproj and GRDBCustom.xcodeproj from GRDB.xcodeproj 2017-12-03 14:07:05 +01:00
Gwendal Roué 090df10831 Revert attempt at preventing Xcode warnings with Run Script phases 2017-12-03 12:52:37 +01:00
Gwendal Roué f21037bb69 Run make preventXcodeWarningsForMissingFiles as a Run Script Phase in all targets except custom SQLite 2017-12-01 13:47:06 +01:00
Gwendal Roué f3041bcc9a Run make preventXcodeWarningsForMissingFiles as a Run Script Phase in the GRDBiOS target 2017-12-01 13:41:47 +01:00
Gwendal Roué 67b1225dfa make preventXcodeWarningsForMissingFiles 2017-12-01 13:37:02 +01:00
Gwendal Roué 23f2e0371e Fix documentation typo 2017-12-01 13:24:04 +01:00
Gwendal Roué a3d8df222f Fix documentation typo 2017-12-01 13:20:17 +01:00
Gwendal Roué 632ef3707c CHANGELOG.md 2017-12-01 13:17:58 +01:00
Gwendal Roué 79dc099e6d Documentation for Database.dropFTS4SynchronizationTriggers & Database.dropFTS5SynchronizationTriggers 2017-12-01 13:17:54 +01:00
Gwendal Roué 75035fb40c Documentation for Database.dropFTS4SynchronizationTriggers & Database.dropFTS5SynchronizationTriggers 2017-12-01 13:14:30 +01:00
Gwendal Roué b4887b661c Tests for Database.dropFTS4SynchronizationTriggers & Database.dropFTS5SynchronizationTriggers 2017-12-01 13:14:24 +01:00
Gwendal Roué e8835af363 Database.dropFTS4SynchronizationTriggers & Database.dropFTS5SynchronizationTriggers 2017-12-01 13:14:13 +01:00
Gwendal Roué 1fabe08332 Trust SQLite: don't assert anything about the remaining characters after a statement 2017-11-30 08:53:10 +01:00
Gwendal Roué c2e3638e8d More failing tests for Database.execute() 2017-11-30 08:50:42 +01:00
Gwendal Roué 71abced420 CHANGELOG.md 2017-11-30 08:09:15 +01:00
Gwendal Roué ac00046b07 CHANGELOG.md 2017-11-29 20:29:33 +01:00
Gwendal Roué 38b5204713 Merge pull request #280 from groue/AddUntypedColumn
Table alteration: add untyped column
2017-11-29 20:21:13 +01:00
Gwendal Roué 4b173dece5 Test for t.add(column:) without any explicit column type 2017-11-29 20:17:26 +01:00
Gwendal Roué 8ce2c09b52 TableAlteration.add(column:type:) accepts nil type 2017-11-29 20:11:28 +01:00
Gwendal Roué 8125574f8f Fix typo in ISSUE_TEMPLATE.md 2017-11-22 08:56:48 +01:00
Gwendal Roué 8974360cac ISSUE_TEMPLATE.md 2017-11-22 08:24:21 +01:00
Gwendal Roué 6e48cc1524 Reminder: enable sanitizers when running tests 2017-11-11 06:43:59 +01:00
Gwendal Roué a1ea75ca34 TODO.md 2017-11-10 12:58:04 +01:00
Gwendal Roué 81d2f21093 Cleanup 2017-11-10 08:45:05 +01:00
Gwendal Roué fd73a31abc Fix failing tests and faulty assert 2017-11-09 14:29:59 +01:00
Gwendal Roué 1583ac0c08 Add failing test for Database.execute() 2017-11-09 14:29:35 +01:00
Gwendal Roué cafbecd8af v2.3.1 2017-11-08 07:50:58 +01:00
Gwendal Roué 78c36612b7 Enhance documentation of Codable Records 2017-11-07 19:29:51 +01:00
Gwendal Roué a95385c740 Simplify TransactionObserverTests with Codable 2017-11-07 19:22:54 +01:00
Gwendal Roué a58ebf7c48 CHANGELOG.md 2017-11-07 17:47:24 +01:00
Gwendal Roué 13623575ff Fix encryption tests broken by 681460a415 2017-11-07 17:21:32 +01:00
Gwendal Roué 87c5f913b8 CHANGELOG.md 2017-11-07 14:56:51 +01:00
Gwendal Roué 41172d7967 Documentation: no more exception for empty deferred transactions 2017-11-07 14:42:58 +01:00
Gwendal Roué 820bc87cfe No more exception for empty deferred transactions 2017-11-07 14:42:02 +01:00
Gwendal Roué 2901acfb41 Refactor tests of observation of transaction completion. Make them fail for empty deferred transactions. 2017-11-07 13:55:17 +01:00
Gwendal Roué 681460a415 Tests: generate a unique database by default 2017-11-07 13:54:19 +01:00
Gwendal Roué 19b067405f v2.3.0 2017-11-05 13:56:10 +01:00
Gwendal Roué 3b494b5737 Update SQLite to 3.21.0 2017-11-05 11:21:46 +01:00
Gwendal Roué 5f11a19296 Travis: use Xcode 9.1 2017-11-01 13:19:12 +01:00
Gwendal Roué 3ff7675eb7 Makefile: add support for Xcode 9.1 and Xcode 9.2 beta 1 2017-11-01 13:13:05 +01:00
Gwendal Roué 3d06841eba Remove Xcode9.1 warnings about deprecated string.characters 2017-11-01 07:33:03 +01:00
120 changed files with 12323 additions and 6428 deletions

No files matched your search

+106 -45
View File
@@ -1,3 +1,6 @@
# The OS X Build Environment
# https://docs.travis-ci.com/user/reference/osx/#Xcode-version
language: objective-c
xcode_project: GRDB.xcodeproj
@@ -12,140 +15,198 @@ jobs:
###########################################
## Test GRDB
# Test GRDBOSX (Xcode 9)
# Test GRDBOSX (Xcode 9.2)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.2
env:
- TID=GRDBOSX (Xcode 9, macOS 10.12)
- TID=GRDBOSX (Xcode 9.2, macOS)
script: make test_framework_GRDBOSX
# Test GRDBWatchOS (Xcode 9)
# Test GRDBWatchOS (Xcode 9.2)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.2
env:
- TID=GRDBWatchOS (Xcode 9, watchOS)
- TID=GRDBWatchOS (Xcode 9.2, watchOS)
script: make test_framework_GRDBWatchOS
# Test GRDBiOS (Xcode 9, iOS <MAXIMUM VERSION>)
# Test GRDBiOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.2
env:
- TID=GRDBiOS (Xcode 9, iOS <MAX>)
- TID=GRDBiOS (Xcode 9.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget
# Test GRDBiOS (Xcode 9, iOS <MINIMUM VERSION>))
# Test GRDBiOS (Xcode 9.2, iOS <MINIMUM VERSION>))
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.2
env:
- TID=GRDBiOS (Xcode 9, iOS <MIN>)
- TID=GRDBiOS (Xcode 9.2, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
# Test GRDB [SPM] (Xcode 9, macOS 10.12)
# Test GRDB [SPM] (Xcode 9.2, macOS)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.2
env:
- 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=GRDB [SPM] (Xcode 9, macOS 10.12)
script: make test_SPM
- 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)
# Test GRDBCustomSQLiteOSX (Xcode 9.2)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.2
env:
- TID=GRDBCustomSQLiteOSX (Xcode 9, macOS 10.12)
- TID=GRDBCustomSQLiteOSX (Xcode 9.2, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
# Test GRDBCustomSQLiteiOS (Xcode 9, iOS <MAXIMUM VERSION>)
# Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.2
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9, iOS <MAX>)
- TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
# Test GRDBCustomSQLiteiOS (Xcode 9, iOS <MINIMUM VERSION>))
# Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MINIMUM VERSION>))
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.2
env:
- 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=GRDBCustomSQLiteiOS (Xcode 9, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
- 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)
# Test GRDBCipherOSX (Xcode 9.2)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.2
env:
- TID=GRDBCipherOSX (Xcode 9, macOS 10.12)
- TID=GRDBCipherOSX (Xcode 9.2, macOS)
script: make test_framework_GRDBCipherOSX
# Test GRDBCipheriOS (Xcode 9, iOS <MAXIMUM VERSION>)
# Test GRDBCipheriOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.2
env:
- TID=GRDBCipheriOS (Xcode 9, iOS <MAX>)
- TID=GRDBCipheriOS (Xcode 9.2, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
# Test GRDBCipheriOS (Xcode 9, iOS <MINIMUM VERSION>))
# Test GRDBCipheriOS (Xcode 9.2, iOS <MINIMUM VERSION>))
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.2
env:
- 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=GRDBCipheriOS (Xcode 9, iOS <MIN>)
script: make test_framework_GRDBCipheriOS_minTarget
- 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
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
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.2
install:
- gem install cocoapods # Since Travis is not always on latest version
env:
- TID=Cocoapods (Xcode 9.2)
script: make test_CocoaPodsLint
# Cocoapods Lint (Xcode 9.0)
- stage: Test Installation
osx_image: xcode9
install:
- gem install cocoapods # Since Travis is not always on latest version
env:
- TID=Cocoapods
- TID=Cocoapods (Xcode 9.0)
script: make test_CocoaPodsLint
# SPM Install
# SPM Install (Xcode 9.2)
- stage: Test Installation
osx_image: xcode9
osx_image: xcode9.2
env:
- TID=SPM
- 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
# osx_image: xcode9.2
# before_install:
# - brew update
# - brew outdated carthage || brew upgrade carthage
+241 -2
View File
@@ -1,6 +1,245 @@
Release Notes
=============
## 2.7.0
Released January 21, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.6.1...v2.7.0)
**New**
- The new RecordBox class brings changes tracking to any record type ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#recordbox-class)):
```swift
// A regular record struct
struct Player: RowConvertible, MutablePersistable { ... }
try dbQueue.inDatabase { db in
// Fetch a boxed player
if let boxedPlayer = try RecordBox<Player>.fetchOne(db, key: 1) {
// boxedPlayer.value is Player
boxedPlayer.value.score = 300
if boxedPlayer.hasPersistentChangedValues {
print("player has been modified")
}
// Does nothing if player has not been modified:
try boxedPlayer.updateChanges(db)
}
}
```
## 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)
**Fixed**
- When using a database pool, the schema introspection methods could return wrong values whenever the database schema was concurrently read and modified. This has been fixed.
- `DatabasePool.readFromCurrentState` no longer accepts to spawn a reader when a transaction is currently opened on the writer connection.
## 2.4.1
Released December 16, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.4.0...v2.4.1)
**Fixed**
- [#284](https://github.com/groue/GRDB.swift/pull/284): fixes a misuse of the sqlite3_config() function when configuring the global SQLite [Error Log](https://github.com/groue/GRDB.swift/blob/master/README.md#error-log)
## 2.4.0
Released December 3, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.3.1...v2.4.0)
**New**
- [#280](https://github.com/groue/GRDB.swift/pull/280): It is now possible to add an untyped column to an existing table.
```swift
try db.alter(table: "players") { t in
t.add(column: "score")
}
```
- [#281](https://github.com/groue/GRDB.swift/pull/280): The `Database.dropFTS4SynchronizationTriggers` & `Database.dropFTS5SynchronizationTriggers` method help cleaning up synchronized full-text table ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#deleting-synchronized-full-text-tables))
**Breaking Change**
- [#282](https://github.com/groue/GRDB.swift/issues/282): This version comes with a breaking change that affects users who manually embed the GRDBCipher and GRDBCustom frameworks in their projects. This change does not affect users of the GRDB framework, or users of GRDBCipher through CocoaPods. Now, instead of embedding the GRDB.xcodeproj project, you have to embed the GRDBCipher.xcodeproj or GRDBCustom.xcodeproj. Please have a look at the updated [Encryption](https://github.com/groue/GRDB.swift/blob/master/README.md#encryption) and [Custom SQLite Builds](https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md) documentation chapters.
## 2.3.1
Released November 8, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.3.0...v2.3.1)
**Fixed**
- GRDB 2.2.0 has introduced a fix in the way [transaction observers](https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol) are notified of empty deferred transactions (`BEGIN; COMMIT;`). That fix was incomplete, and inconsistent.
Now all transactions are notified, without any exception, including:
```swift
try db.execute("BEGIN; COMMIT;")
try db.execute("SAVEPOINT foo; RELEASE SAVEPOINT foo;")
```
[Rationale](https://github.com/groue/GRDB.swift/commit/820bc87cfeee701743da852f3634e2c695e911ee#diff-3e791e9db648cd302590c9b86c70757fR376)
## 2.3.0
Released November 5, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.2.0...v2.3.0)
**New**
- Upgrade custom SQLite builds to [v3.21.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
## 2.2.0
Released October 31, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.1.0...v2.2.0)
@@ -58,14 +297,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?
}
}
```
+4 -4
View File
@@ -3,7 +3,7 @@ Custom SQLite Builds
By default, GRDB uses the version of SQLite that ships with the target operating system.
**You can build GRDB with a custom build of [SQLite 3.20.1](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.21.0](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks).
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```sh
cd [GRDB directory]
git checkout v2.2.0
git checkout v2.7.0
git submodule update --init SQLiteCustom/src
````
@@ -60,7 +60,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
# !! MODIFY THESE TO MATCH YOUR PROJECT HIERARCHY !!
#######################################################
# The path to the folder containing GRDB.xcodeproj:
# The path to the folder containing GRDBCustom.xcodeproj:
GRDB_SOURCE_PATH="${PROJECT_DIR}/GRDB"
# The path to your custom "SQLiteLib-USER.xcconfig":
@@ -107,7 +107,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
Modify the top of `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
5. Embed the `GRDB.xcodeproj` project in your own project.
5. Embed the `GRDBCustom.xcodeproj` project in your own project.
6. Add the `GRDBCustomSQLiteOSX` or `GRDBCustomSQLiteiOS` target in the **Target Dependencies** section of the **Build Phases** tab of your **application target**.
-591
View File
@@ -1,591 +0,0 @@
GRDB Extension Guide
====================
**Some parts of GRDB are extensible, so that you can make it better fit your needs.**
This guide is a step-by-step tour of GRDB extensibility, around a few topics:
- **[Add a value type](#add-a-value-type)**
You'll learn how to turn UIColor into a value type that you can store, fetch, and use in your records:
```swift
let rows = try Row.fetchCursor(db, "SELECT name, color FROM clothes")
while let row = try rows.next() {
let name: String = row["name"]
let color: UIColor = row["color"] // <-- New! UIColor as value
}
```
- **[Add an SQLite function or operator](#add-an-sqlite-function-or-operator)**
You'll learn how to add support for the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) function, and the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator:
```swift
Books.select(strftime("%Y", Column("publishedDate"))) // <-- New! strftime function
Books.filter(Column("body").glob("*Moby-Dick*")) // <-- New! glob method
```
- **[Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression)**
You'll learn how to add support for [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr):
```swift
let jsonString = Column("jsonString")
let request = Books.select(cast(jsonString, as: .blob)) // <-- New! cast function
let rows = try Row.fetchCursor(db, request)
while let row = try rows.next() {
let data = row.dataNoCopy(atIndex: 0)
}
```
- **Extend the query interface requests**
You may need to extend the [query interface requests](../../../#requests) so that their SELECT queries could embed recursive clauses, table joins, etc.
Pull requests are welcome. Open issues if you have questions.
Meanwhile, you can build your own [custom requests](../../../#custom-requests).
- **[Add a custom FTS5 full-text tokenizer](FTS5Tokenizers.md)**
Custom tokenizers can leverage extra full-text features such as synonyms or stop words.
- **Support a new kind of SQL query**
For example, you may need to generate SQL triggers, or create specific kinds of virtual tables.
Pull requests are welcome. Open issues if you have questions.
## Add a Value Type
**All value types adopt the [DatabaseValueConvertible protocol](../../../#custom-value-types).**
```swift
protocol DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue { get }
/// Returns a value initialized from databaseValue, if possible.
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self?
}
```
The `databaseValue` property returns [DatabaseValue](../../../#databasevalue), a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and Data. Since DatabaseValue has no public initializer, use `DatabaseValue.null`, or another type that already adopts the protocol: `1.databaseValue`, `"foo".databaseValue`, etc. Conversion to DatabaseValue *must not* fail.
The `fromDatabaseValue()` factory method returns an instance of your custom type if the databaseValue contains a suitable value. If the databaseValue does not contain a suitable value, such as "foo" for Date, `fromDatabaseValue` *must* return nil (GRDB will interpret this nil result as a conversion error, and react accordingly).
**What does the DatabaseValueConvertible protocol bring to a type like UIColor?**
Well, you will be able to use UIColor like all other [value types](../../../#values) (Bool, Int, String, Date, Swift enums, etc.):
- Use UIColor as [statement arguments](../../../#executing-updates):
```swift
try db.execute(
"INSERT INTO clothes (name, color) VALUES (?, ?)",
arguments: ["Shirt", UIColor.red])
```
- UIColor can be [extracted from rows](../../../#column-values):
```swift
let rows = try Row.fetchCursor(db, "SELECT * FROM clothes")
while let row = try rows.next() {
let name: String = row["name"]
let color: UIColor = row["color"]
}
```
- UIColor can be [directly fetched](../../../#value-queries):
```swift
let colors = try UIColor.fetchAll(db, "SELECT DISTINCT color FROM clothes") // [UIColor]
```
- Use UIColor in [Records](../../../#records):
```swift
class ClothingItem : Record {
var name: String
var color: UIColor
required init(row: Row) {
name = row["name"]
color = row["color"]
super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
container["name"] = name
container["color"] = color
}
}
```
- Use UIColor in the [query interface](../../../#the-query-interface):
```swift
let redClothes = try ClothingItem.filter(colorColumn == UIColor.red).fetchAll(db)
```
**Let's have UIColor adopt DatabaseValueConvertible**
In order to preserve as most information as possible, we'll archive UIColor as a data blob using the NSCoding protocol. But YMMV.
```swift
extension UIColor : DatabaseValueConvertible {
/// Encode UIColor as a data blob
var databaseValue: DatabaseValue {
// Use NSKeyedArchiver to build Data
let data = NSKeyedArchiver.archivedData(withRootObject: self)
// Data is already DatabaseValueConvertible
return data.databaseValue
}
/// Returns a UIColor if databaseValue contains suitable data, and
/// nil otherwise.
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
// Only Data blobs can contain a UIColor
guard let data = Data.fromDatabaseValue(databaseValue) else {
return nil
}
// We're looking for an archived object
guard let color = NSKeyedUnarchiver.unarchiveObject(with: data) else {
return nil
}
// The cast function will return nil if the unarchived object doesn't
// have the correct type
return cast(color) // Converts Any to Self?
}
}
```
Use the `cast` utility function when you want *non-final classes* to implement DatabaseValueConvertible. It avoids compiler errors that are not easy to deal with. Note that final classes and value types won't need it.
```swift
// Workaround Swift inconvenience around factories methods of non-final classes
func cast<T, U>(_ value: T) -> U? {
return value as? U
}
```
## Add an SQLite Function or Operator
**When an SQLite [function](https://www.sqlite.org/lang_corefunc.html) or [operator](https://www.sqlite.org/lang_expr.html) is missing from GRDB**, this usually means that there hasn't been a [feature request](http://github.com/groue/GRDB.swift/issues) yet.
But you don't have to wait: you can extend GRDB and the query interface to add support for the missing syntax element (and eventually submit a pull request later).
Let's remind our goal: we'll add the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) function, and the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator.
Their SQL usage is the following:
```sql
-- Publication years of books
SELECT STRFTIME('%Y', publishedOn) FROM books;
-- Books that talk about Moby Dick
SELECT * FROM books WHERE body GLOB '*Moby-Dick*';
```
Translated in the query interface, this gives:
```swift
Books.select(strftime("%Y", Column("publishedDate")))
Books.filter(Column("body").glob("*Moby-Dick*"))
```
`strftime` is a top-level Swift function because this is how GRDB usually imports SQLite functions which do not have matching standard Swift counterpart, like AVG, LEGNTH, SUM. It helps the Swift code looking like SQL when it is relevant.
In the same fashion, we expose the GLOB SQL operator as the `glob` Swift method, just because `value.glob(pattern)` reads like `value GLOB pattern`.
Whenever you import a SQL feature to Swift, you'll have to decide: should you preserve the SQL look and feel, or adopt a well-established swiftism? It's really up to you.
### STRFTIME
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
The [STRFTIME](https://www.sqlite.org/lang_datefunc.html) SQL function accepts many arguments. We'll simplify it to `strftime(format, date)`, so that we can write:
```sql
// Publication years of books
// SELECT STRFTIME('%Y', publishedOn) FROM books
Books.select(strftime("%Y", Column("publishedDate")))
```
The signature of the Swift `strftime` function is:
```swift
func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression
```
SQLSpecificExpressible and SQLExpression are types of the [query interface](../../../#the-query-interface) that you do not usually see. We have moved down one floor, closer to the SQL guts of GRDB. We'll see more new types and protocols below.
The return value is SQLExpression. All GRDB functions and operators that build [query interface expressions](../../../#expressions) return values of this type. It represents actual [SQLite expressions](https://www.sqlite.org/lang_expr.html).
SQLExpression is a protocol, so that you can build your own [custom expressions](#add-a-new-kind-of-sqlite-expression). But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, and here we'll use SQLExpressionFunction that is dedicated to function calls:
```swift
struct SQLExpressionFunction : SQLExpression {
/// Creates an SQL function call
///
/// // ABS(-1)
/// SQLExpressionFunction(.abs, arguments: -1)
init(_ functionName: SQLFunctionName, arguments: SQLExpressible...)
}
```
So here is the code that defines our `strftime` function:
```swift
// Add a SQLFunctionName just like we add NSNotification.Name since
// the release of Swift 3.
extension SQLFunctionName {
/// The `STRFTIME` SQL function
static let strftime = SQLFunctionName("STRFTIME")
}
/// Returns an expression that evaluates the `STRFTIME` SQL function.
///
/// // STRFTIME('%Y', date)
/// strftime("%Y", Column("date"))
func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionFunction(.strftime, arguments: format, date)
}
```
The `strftime` function is now complete, ready to be used. We haven't yet described the SQLSpecificExpressible type of the `date` argument:
SQLSpecificExpressible is the protocol for all types that can be turned into a SQL expression, but types like Int, Date, or UIColor that exist outside of GRDB and the query interface. Having `strftime` accept a SQLSpecificExpressible date prevents it from polluting the global space. It is *specific* to GRDB:
```swift
strftime("%Y", Date()) // Compiler error
strftime("%Y", Column("date")) // SQLExpression: STRFTIME('%Y', date)
```
You may want to compare it to another protocol, SQLExpressible, which will be described [below](#add-a-new-kind-of-sqlite-expression), when we add support for CAST SQL expressions.
> :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 `strftime` function, it is the SQLSpecificExpressible protocol.
### GLOB
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
For the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator, we want to define the glob Swift method:
```swift
// Books that talk about Moby Dick
// SELECT * FROM books WHERE body GLOB '*Moby-Dick*'
Books.filter(Column("body").glob("*Moby-Dick*"))
```
This time we can't use the SQLExpressionFunction type, because it can't generate the SQL for a binary operator. Instead, we'll use another [built-in expression](#built-in-expressions), SQLExpressionBinary:
```swift
struct SQLExpressionBinary : SQLExpression {
/// Creates an expression made of two expressions joined with a binary operator.
///
/// // length * width
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible)
}
```
Now we have to find the signature of our Swift method. The GLOB operator accepts any value on both sides. However, what kind of Swift code should we accept?
```swift
// 1) body GLOB '*Moby-Dick*' -- Yes, of course
Column("body").glob("*Moby-Dick*")
// 2) body GLOB pattern -- Sure, why not?
Column("body").glob(Column("pattern"))
// 3) 'Some Swift String' GLOB pattern - Not sure, but OK
"Some Swift String".glob(Column("pattern"))
// 4) 'Some Swift String' GLOB 'Another Swift String' -- NO
"Some Swift String".glob("Another Swift String")
```
We don't want the form 4, because this is an unacceptable pollution of the Swift global namespace. A good GRDB extension limits its scope to database-related code.
We thus have two overloaded definitions of the `glob` method:
```swift
extension SQLSpecificExpressible {
func glob(_ pattern: SQLExpressible) -> SQLExpression
}
extension SQLExpressible {
func glob(_ pattern: SQLSpecificExpressible) -> SQLExpression
}
```
SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all expressions, and all [value types](../../../#values) (including String).
SQLSpecificExpressible is a sub protocol of SQLExpressible protocol, restricted to all types that can be turned into a SQL expression, but types like Int, Date, or String that exist outside of GRDB and the query interface.
By extending both, we can define the GLOB operators for any pair that contains at least one type that is specific to GRDB - and leave the global Swift space clean.
The final implementation follows:
```swift
// Add a SQLBinaryOperator just like we add NSNotification.Name since
// the release of Swift 3.
extension SQLBinaryOperator {
/// The `GLOB` binary operator
static let glob = SQLBinaryOperator("GLOB")
}
extension SQLSpecificExpressible {
/// Returns an SQL `GLOB` expression.
///
/// // body GLOB '*Moby-Dick*'
/// Column("body").glob("*Moby-Dick*")
func glob(_ pattern: SQLExpressible) -> SQLExpression {
return SQLExpressionBinary(.glob, self, pattern)
}
}
extension SQLExpressible {
/// Returns an SQL `GLOB` expression.
///
/// // 'Some Swift String' GLOB pattern
/// "Some Swift String".glob(Column("pattern"))
func glob(_ pattern: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.glob, self, pattern)
}
}
```
### Built-in Expressions
When you extend GRDB with a new function, method, or operator that generates an [SQL expression](https://www.sqlite.org/lang_expr.html), you have to return a value the adopts the SQLExpression protocol.
We have already seen in our [previous](#strftime) [examples](#glob) two concrete types that generate SQL function calls and binary operators: SQLExpressionFunction and SQLExpressionBinary.
This section of the documentation lists all built-in expressions. Adding a custom SQLExpression type will be documented [below](#add-a-new-kind-of-sqlite-expression).
#### Column and DatabaseValue
The [Column](../../../#the-query-interface) type from the query interface, and [DatabaseValue](../../../#databasevalue), the type that wraps the five values supported by SQLite (NULL, Int64, Double, String and Data) are expressions. They are rather trivial, and it is unlikely that you use them in your GRDB extensions.
#### SQLExpressionLiteral
Use SQLExpressionLiteral when you need to go fast:
```swift
struct SQLExpressionLiteral : SQLExpression {
/// Creates an SQL literal expression.
///
/// SQLExpressionLiteral("1 + 2")
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
init(_ sql: String, arguments: StatementArguments? = nil)
}
```
For an example of use, see the [Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression) chapter.
#### SQLExpressionUnary
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
SQLExpressionUnary builds an expression by prefixing another expression with an unary operator:
```swift
struct SQLExpressionUnary : SQLExpression {
/// Creates an expression made of an unary operator and
/// an operand expression.
///
/// // NOT favorite
/// SQLExpressionUnary(.not, Column("favorite"))
init(_ op: SQLUnaryOperator, _ value: SQLExpressible)
}
```
You add missing SQLite unary operators by extending SQLUnaryOperator:
```swift
extension SQLUnaryOperator {
/// The `+` unary operator
static let plus = SQLUnaryOperator("+", needsRightSpace: false)
}
```
#### SQLExpressionBinary
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
SQLExpressionBinary builds an expression by joining two expressions with a binary operator:
```swift
struct SQLExpressionBinary : SQLExpression {
/// Creates an expression made of two expressions joined with a binary operator.
///
/// // length * width
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible)
}
```
You add missing SQLite binary operators by extending SQLBinaryOperator:
```swift
extension SQLBinaryOperator {
/// The `GLOB` binary operator
static let glob = SQLBinaryOperator("GLOB")
}
```
#### SQLExpressionFunction
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
SQLExpressionFunction builds an SQL function call:
```swift
struct SQLExpressionFunction : SQLExpression {
/// Creates an SQL function call
///
/// // ABS(-1)
/// SQLExpressionFunction(.abs, arguments: -1)
init(_ functionName: SQLFunctionName, arguments: SQLExpressible...)
}
```
You add missing SQLite function names by extending SQLFunctionName:
```swift
extension SQLFunctionName {
/// The `STRFTIME` SQL function
static let strftime = SQLFunctionName("STRFTIME")
}
```
#### The IN Operator
Build a `value IN (...)` expression from any sequence of [values](../../../#values):
```swift
// SQLExpression: id IN (1, 2, 3)
[1,2,3].contains(Column("id"))
// SQLExpression: id NOT IN (1, 2, 3)
![1,2,3].contains(Column("id"))
```
#### The BETWEEN Operator
Build a `value BETWEEN min AND max` expression from Swift ranges:
```swift
// SQLExpression: id BETWEEN 1 AND 10
1...10.contains(Column("id")
```
#### The COUNT Function
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.2/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.2/Functions.html) functions:
```swift
// SQLExpression: COUNT(email)
count(Column("email"))
// SQLExpression: COUNT(DISTINCT email)
count(distinct: Column("email"))
```
#### The COLLATE Operator
Build a `expression COLLATE collation` expression with the `collating` method:
```swift
// SQLExpression: name = 'Arthur' COLLATE NOCASE
Column("name").collating(.nocase) == "Arthur"
```
## Add a New Kind of SQLite Expression
GRDB does not have built-in support for the full range of the SQLite [expression grammar](https://www.sqlite.org/lang_expr.html).
For example, [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr) are not ready-made. They can be useful, though: a CAST expression can efficiently convert json strings to UTF-8 data blobs for you:
```sql
SELECT CAST(jsonString AS BLOB) FROM books
```
We'll add below a Swift `cast` function:
```swift
let request = Books.select(cast(Column("jsonString"), as: .blob))
let jsonDatas = try Data.fetchAll(db, request) // [Data]
```
`cast` is a top-level Swift function because this is how GRDB usually imports SQLite features which do not have matching standard Swift counterpart. It helps the Swift code looking like SQL when it is relevant. But YMMV.
The signature of the `cast` function is:
```swift
func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression
```
Database.ColumnType is a String-based enumeration of all database column types (.integer, .text, .blob, etc.) You have already used if you have [created tables](../../../#create-tables) using the query interface.
The return type SQLExpression is the type returned by all GRDB functions and operators that build [query interface expressions](../../../#expressions).
SQLExpression is a protocol. But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, so that you generally don't have to write your custom expression type. Here we need something new. So we'll use the most versatile of all, SQLExpressionLiteral:
```swift
struct SQLExpressionLiteral : SQLExpression {
/// Creates an SQL literal expression.
///
/// SQLExpressionLiteral("1 + 2")
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
init(_ sql: String, arguments: StatementArguments? = nil)
}
```
Here is the code that defines our `cast` function:
```swift
func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression {
// Turn the value into a literal expression
let literal: SQLExpressionLiteral = value.sqlExpression.literal
// Build our "CAST(value AS type)" sql snippet
let sql = "CAST(\(literal.sql) AS \(type.rawValue))"
// And return a new literal expression, preserving input arguments
return SQLExpressionLiteral(sql, arguments: literal.arguments)
}
```
We haven't yet described the SQLExpressible type of the `value` argument:
SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all [value types](../../../#values) (Bool, Int, String, Date, Swift enums, etc.):
```swift
cast("foo", as: .blob) // SQLExpression: CAST('foo' AS BLOB)
cast(Column("name"), as: .blob) // SQLExpression: CAST(name AS BLOB)
```
You may want to compare it to another protocol, SQLSpecificExpressible, which has been described [above](#strftime), when we were adding support for the STRFTIME SQL function.
> :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.2/Protocols/SQLExpression.html) protocol.
+3 -1
View File
@@ -16,7 +16,6 @@ To release a new GRDB version:
- Makefile
- CHANGELOG.md
- Documentation/CustomSQLiteBuilds.md
- Documentation/ExtendingGRDB.md
- GRDB.swift.podspec
- GRDBCipher.podspec
- README.md
@@ -30,3 +29,6 @@ To release a new GRDB version:
- `make doc`, and update index.html in the `gh-pages` branch
- Update http://github.com/groue/GRDBDemo
- Update http://github.com/groue/WWDCCompanion
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
`make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb`
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '2.2.0'
s.version = '2.7.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
File diff suppressed because it is too large. Load diff
+21
View File
@@ -23,9 +23,30 @@
location = "group:MyPlayground.playground">
</FileRef>
</Group>
<FileRef
location = "group:CHANGELOG.md">
</FileRef>
<FileRef
location = "group:README.md">
</FileRef>
<FileRef
location = "group:TODO.md">
</FileRef>
<FileRef
location = "group:Documentation/ReleaseProcess.md">
</FileRef>
<FileRef
location = "group:Makefile">
</FileRef>
<FileRef
location = "group:GRDB.xcodeproj">
</FileRef>
<FileRef
location = "group:GRDBCustom.xcodeproj">
</FileRef>
<FileRef
location = "group:GRDBCipher.xcodeproj">
</FileRef>
<FileRef
location = "group:Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj">
</FileRef>
+6
View File
@@ -87,6 +87,7 @@ public class AnyCursor<Element> : Cursor {
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> Element? {
return try element()
}
@@ -231,6 +232,7 @@ public final class EnumeratedCursor<Base: Cursor> : Cursor {
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> (Int, Base.Element)? {
guard let element = try base.next() else { return nil }
defer { index += 1 }
@@ -251,6 +253,7 @@ public final class FilterCursor<Base: Cursor> : Cursor {
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> Base.Element? {
while let element = try base.next() {
if try isIncluded(element) {
@@ -275,6 +278,7 @@ public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Curs
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> Base.Element.Element? {
while true {
if let element = try inner?.next() {
@@ -303,6 +307,7 @@ public final class MapCursor<Base: Cursor, Element> : Cursor {
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> Element? {
guard let element = try base.next() else { return nil }
return try transform(element)
@@ -327,6 +332,7 @@ public final class IteratorCursor<Base: IteratorProtocol> : Cursor {
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() -> Base.Element? {
return base.next()
}
+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 {
+6 -41
View File
@@ -14,7 +14,7 @@ extension Database {
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeSelectStatement(_ sql: String) throws -> SelectStatement {
return try makeStatement(sql, prepFlags: 0)
return try makeSelectStatement(sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
@@ -29,7 +29,7 @@ extension Database {
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeSelectStatement(_ sql: String, prepFlags: Int32) throws -> SelectStatement {
return try makeStatement(sql, prepFlags: prepFlags)
return try SelectStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
}
/// Returns a prepared statement that can be reused.
@@ -63,7 +63,7 @@ extension Database {
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement {
return try makeStatement(sql, prepFlags: 0)
return try makeUpdateStatement(sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
@@ -78,7 +78,7 @@ extension Database {
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeUpdateStatement(_ sql: String, prepFlags: Int32) throws -> UpdateStatement {
return try makeStatement(sql, prepFlags: prepFlags)
return try UpdateStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
}
/// Returns a prepared statement that can be reused.
@@ -185,41 +185,6 @@ extension Database {
// arguments that do not match the statement.
try! validateRemainingArguments() // throws if there are remaining arguments.
}
private func makeStatement<Statement: AuthorizedStatement>(_ sql: String, prepFlags: Int32) throws -> Statement {
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
authorizer = statementCompilationAuthorizer
defer { authorizer = nil }
var statement: Statement? = nil
let sqlCodeUnits = sql.utf8CString
var remainingSQL = ""
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let statementStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
var statementEnd: UnsafePointer<Int8>? = nil
do {
statement = try Statement(
database: self,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: prepFlags,
authorizer: statementCompilationAuthorizer)
} catch is EmptyStatementError {
throw DatabaseError(resultCode: .SQLITE_ERROR, message: "empty statement", sql: sql, arguments: nil)
}
let remainingData = Data(
bytesNoCopy: UnsafeMutableRawPointer(mutating: statementEnd!),
count: statementStart + sqlCodeUnits.count - statementEnd! - 1,
deallocator: .none)
remainingSQL = String(data: remainingData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines)
}
guard remainingSQL.isEmpty else {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
}
return statement!
}
}
extension Database {
@@ -228,12 +193,12 @@ extension Database {
observationBroker.updateStatementWillExecute(statement)
}
func updateStatementDidExecute(_ statement: UpdateStatement) {
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
if statement.invalidatesDatabaseSchemaCache {
clearSchemaCache()
}
observationBroker.updateStatementDidExecute(statement)
try observationBroker.updateStatementDidExecute(statement)
}
func updateStatementDidFail(_ statement: UpdateStatement) throws {
+21 -25
View File
@@ -46,7 +46,20 @@ public final class Database {
/// > advantage of the error logging facility of SQLite in their products,
/// > as it is very low CPU and memory cost but can be a huge aid
/// > for debugging.
public static var logError: LogErrorFunction? = nil
public static var logError: LogErrorFunction? = nil {
didSet {
if logError != nil {
registerErrorLogCallback { (_, code, message) in
guard let logError = Database.logError else { return }
guard let message = message.map({ String(cString: $0) }) else { return }
let resultCode = ResultCode(rawValue: code)
logError(resultCode, message)
}
} else {
registerErrorLogCallback(nil)
}
}
}
/// The database configuration
public let configuration: Configuration
@@ -145,9 +158,6 @@ public final class Database {
// MARK: - Initializer
init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCache) throws {
// Setup the global SQLite error log before connecting to the database.
Database.setupGlobalErrorLog()
let sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
do {
try Database.activateExtendedCodes(sqliteConnection)
@@ -179,26 +189,6 @@ extension Database {
// MARK: - Database Opening
/// Registers the public Database.logError function as the global SQLite
/// error log, with sqlite3_config(SQLITE_CONFIG_LOG).
///
/// See https://sqlite.org/c3ref/c_config_covering_index_scan.html#sqliteconfiglog
private static func setupGlobalErrorLog() {
// We use a Swift static variable as a way to ensure that the error log
// is registered once and only once.
struct Impl {
static let setupErrorLog: () = {
registerErrorLogCallback { (_, code, message) in
guard let log = Database.logError else { return }
guard let message = message.map({ String(cString: $0) }) else { return }
let resultCode = ResultCode(rawValue: code)
log(resultCode, message)
}
}()
}
Impl.setupErrorLog
}
private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection {
// See https://www.sqlite.org/c3ref/open.html
var sqliteConnection: SQLiteConnection? = nil
@@ -280,7 +270,7 @@ extension Database {
setupBusyMode()
setupDefaultFunctions()
setupDefaultCollations()
observationBroker.setup()
observationBroker.installCommitAndRollbackHooks()
}
private func setupTrace() {
@@ -827,8 +817,10 @@ extension Database {
///
/// See https://www.sqlite.org/datatype3.html#collation
public struct CollationName : RawRepresentable, Hashable {
/// :nodoc:
public let rawValue: String
/// :nodoc:
public init(rawValue: String) {
self.rawValue = rawValue
}
@@ -838,6 +830,7 @@ extension Database {
}
/// The hash value
/// :nodoc:
public var hashValue: Int {
return rawValue.hashValue
}
@@ -861,8 +854,10 @@ extension Database {
///
/// See https://www.sqlite.org/datatype3.html
public struct ColumnType : RawRepresentable, Hashable {
/// :nodoc:
public let rawValue: String
/// :nodoc:
public init(rawValue: String) {
self.rawValue = rawValue
}
@@ -872,6 +867,7 @@ extension Database {
}
/// The hash value
/// :nodoc:
public var hashValue: Int {
return rawValue.hashValue
}
+2
View File
@@ -33,6 +33,7 @@ public final class DatabaseCollation {
}
extension DatabaseCollation : Hashable {
/// :nodoc:
public var hashValue: Int {
// Collation equality is based on the sqlite3_strnicmp SQLite function.
// (see https://www.sqlite.org/c3ref/create_collation.html). Computing
@@ -44,6 +45,7 @@ extension DatabaseCollation : Hashable {
}
/// Two collations are equal if they share the same name (case insensitive)
/// :nodoc:
public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
// See https://www.sqlite.org/c3ref/create_collation.html
return sqlite3_stricmp(lhs.name, lhs.name) == 0
+16 -6
View File
@@ -5,7 +5,7 @@ import Foundation
import SQLite3
#endif
public struct ResultCode : RawRepresentable {
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
public let rawValue: Int32
public init(rawValue: Int32) {
@@ -139,13 +139,17 @@ public struct ResultCode : RawRepresentable {
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
}
extension ResultCode : Equatable {
// Equatable
extension ResultCode {
/// :nodoc:
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension ResultCode : CustomStringConvertible {
// CustomStringConvertible
extension ResultCode {
/// :nodoc:
public var description: String {
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
@@ -162,7 +166,7 @@ extension ResultCode : CustomStringConvertible {
}
/// DatabaseError wraps an SQLite error.
public struct DatabaseError : Error {
public struct DatabaseError : Error, CustomStringConvertible, CustomNSError {
/// The SQLite error code (see
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
@@ -223,7 +227,9 @@ public struct DatabaseError : Error {
let arguments: StatementArguments?
}
extension DatabaseError: CustomStringConvertible {
// CustomStringConvertible
extension DatabaseError {
/// :nodoc:
public var description: String {
var description = "SQLite error \(resultCode.rawValue)"
if let sql = sql {
@@ -239,19 +245,23 @@ extension DatabaseError: CustomStringConvertible {
}
}
extension DatabaseError : CustomNSError {
// CustomNSError
extension DatabaseError {
/// NSError bridging: the domain of the error.
/// :nodoc:
public static var errorDomain: String {
return "GRDB.DatabaseError"
}
/// NSError bridging: the error code within the given domain.
/// :nodoc:
public var errorCode: Int {
return Int(extendedResultCode.rawValue)
}
/// NSError bridging: the user-info dictionary.
/// :nodoc:
public var errorUserInfo: [String : Any] {
return [NSLocalizedDescriptionKey: description]
}
+2
View File
@@ -311,11 +311,13 @@ public final class DatabaseFunction {
extension DatabaseFunction : Hashable {
/// The hash value
/// :nodoc:
public var hashValue: Int {
return name.hashValue ^ nArg.hashValue
}
/// Two functions are equal if they share the same name and arity.
/// :nodoc:
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
return lhs.name == rhs.name && lhs.nArg == rhs.nArg
}
+25 -10
View File
@@ -44,14 +44,11 @@ public final class DatabasePool {
public init(path: String, configuration: Configuration = Configuration()) throws {
GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1")
// Writer and readers share the same database schema cache
let sharedSchemaCache = SharedDatabaseSchemaCache()
// Writer
writer = try SerializedDatabase(
path: path,
configuration: configuration,
schemaCache: sharedSchemaCache)
schemaCache: SimpleDatabaseSchemaCache())
// Activate WAL Mode unless readonly
if !configuration.readonly {
@@ -84,7 +81,7 @@ public final class DatabasePool {
let reader = try SerializedDatabase(
path: path,
configuration: self.readerConfig,
schemaCache: sharedSchemaCache)
schemaCache: SimpleDatabaseSchemaCache())
reader.sync { db in
for function in self.functions {
@@ -250,6 +247,8 @@ extension DatabasePool : DatabaseReader {
// The block isolation comes from the DEFERRED transaction.
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
try db.inTransaction(.deferred) {
// Reset the schema cache before running user code in snapshot isolation
db.schemaCache = SimpleDatabaseSchemaCache()
result = try block(db)
return .commit
}
@@ -287,7 +286,11 @@ extension DatabasePool : DatabaseReader {
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
return try readerPool.get { reader in
try reader.sync(block)
try reader.sync { db in
// No schema cache when snapshot isolation is not established
db.schemaCache = EmptyDatabaseSchemaCache()
return try block(db)
}
}
}
@@ -323,7 +326,11 @@ extension DatabasePool : DatabaseReader {
return try reader.reentrantSync(block)
} else {
return try readerPool.get { reader in
try reader.sync(block)
try reader.sync { db in
// No schema cache when snapshot isolation is not established
db.schemaCache = EmptyDatabaseSchemaCache()
return try block(db)
}
}
}
}
@@ -504,7 +511,8 @@ extension DatabasePool : DatabaseWriter {
/// Asynchronously executes a read-only block in a protected dispatch queue,
/// wrapped in a deferred transaction.
///
/// This method must be called from the writing dispatch queue.
/// This method must be called from the writing dispatch queue, outside of a
/// transaction. You'll get a fatal error otherwise.
///
/// The *block* argument is guaranteed to see the database in the last
/// committed state at the moment this method is called. Eventual concurrent
@@ -570,8 +578,11 @@ extension DatabasePool : DatabaseWriter {
// UPDATE ...
// Here the change is not visible by GRDB user
// This method must be called from the writing dispatch queue:
writer.preconditionValidQueue()
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.")
}
// The semaphore that blocks the writing dispatch queue until snapshot
// isolation has been established:
@@ -590,7 +601,11 @@ extension DatabasePool : DatabaseWriter {
return
}
semaphore.signal() // We can release the writer queue now that we are isolated for good
// Reset the schema cache before running user code in snapshot isolation
db.schemaCache = SimpleDatabaseSchemaCache()
block(db)
_ = try? db.commit() // Ignore commit error
}
}
+32 -16
View File
@@ -188,8 +188,8 @@ extension DatabaseQueue {
extension DatabaseQueue : DatabaseReader {
// MARK: - DatabaseReader Protocol Adoption
// MARK: - Reading from Database
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result.
///
@@ -220,6 +220,8 @@ extension DatabaseQueue : DatabaseReader {
}
/// Alias for `inDatabase`. See `DatabaseReader.unsafeRead`.
///
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
return try inDatabase(block)
}
@@ -233,6 +235,8 @@ extension DatabaseQueue : DatabaseReader {
///
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
///
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try serializedDatabase.reentrantSync(block)
}
@@ -282,10 +286,10 @@ extension DatabaseQueue : DatabaseReader {
}
extension DatabaseQueue : DatabaseWriter {
// MARK: - DatabaseWriter Protocol Adoption
/// Alias for `inDatabase`. See `DatabaseWriter.write`.
///
/// :nodoc:
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
return try inDatabase(block)
}
@@ -296,22 +300,34 @@ extension DatabaseQueue : DatabaseWriter {
/// SQLCipher, attempts to write in the database throw a DatabaseError whose
/// resultCode is `SQLITE_READONLY`.
///
/// This method must be called from the protected database dispatch queue.
/// This method must be called from the protected database dispatch queue,
/// outside of a transaction. You'll get a fatal error otherwise.
///
/// See `DatabaseWriter.readFromCurrentState`.
///
/// :nodoc:
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
serializedDatabase.execute { readOnly($0, block) }
#else
if #available(iOS 8.2, OSX 10.10, *) {
serializedDatabase.execute { readOnly($0, block) }
} else {
serializedDatabase.execute(block)
}
#endif
// Check that we're on the correct queue...
serializedDatabase.execute { db in
// ... and that no transaction is opened.
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.")
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
readOnly(db, block)
#else
if #available(iOS 8.2, OSX 10.10, *) {
readOnly(db, block)
} else {
block(db)
}
#endif
}
}
// MARK: - Unsafe Database Access
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
+7
View File
@@ -223,34 +223,41 @@ public final class AnyDatabaseReader : DatabaseReader {
// MARK: - Reading from Database
/// :nodoc:
public func read<T>(_ block: (Database) throws -> T) throws -> T {
return try base.read(block)
}
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeRead(block)
}
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeReentrantRead(block)
}
// MARK: - Functions
/// :nodoc:
public func add(function: DatabaseFunction) {
base.add(function: function)
}
/// :nodoc:
public func remove(function: DatabaseFunction) {
base.remove(function: function)
}
// MARK: - Collations
/// :nodoc:
public func add(collation: DatabaseCollation) {
base.add(collation: collation)
}
/// :nodoc:
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
+303
View File
@@ -0,0 +1,303 @@
/// 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: CustomStringConvertible, Equatable {
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)
}
}
}
// Equatable
extension DatabaseRegion {
/// :nodoc:
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
}
}
}
// CustomStringConvertible
extension DatabaseRegion {
/// :nodoc:
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)
}
}
+33 -46
View File
@@ -1,12 +1,10 @@
/// The protocol for schema cache.
///
/// This protocol must not contain values that are valid for a single connection
/// only, because several connections can share the same schema cache.
///
/// Statements can't be cached here, for example.
/// The protocol for database schema cache.
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)
@@ -21,24 +19,34 @@ protocol DatabaseSchemaCache {
}
/// A thread-unsafe database schema cache
final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
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]] = [:]
func clear() {
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]
}
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
primaryKeys[table] = primaryKey
}
@@ -46,7 +54,7 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
return columns[table]
}
func set(columns: [ColumnInfo], forTable table: String) {
mutating func set(columns: [ColumnInfo], forTable table: String) {
self.columns[table] = columns
}
@@ -54,7 +62,7 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
return indexes[table]
}
func set(indexes: [IndexInfo], forTable table: String) {
mutating func set(indexes: [IndexInfo], forTable table: String) {
self.indexes[table] = indexes
}
@@ -62,48 +70,27 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
return foreignKeys[table]
}
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
self.foreignKeys[table] = foreignKeys
}
}
/// A thread-safe database schema cache
final class SharedDatabaseSchemaCache: DatabaseSchemaCache {
private let cache = ReadWriteBox(SimpleDatabaseSchemaCache())
/// An always empty database schema cache
struct EmptyDatabaseSchemaCache: DatabaseSchemaCache {
func clear() { }
func clear() {
cache.write { $0.clear() }
}
func canonicalName(table: String) -> String? { return nil }
func set(canonicalName: String, forTable table: String) { }
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
return cache.read { $0.primaryKey(table) }
}
func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil }
func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
cache.write { $0.set(primaryKey: primaryKey, forTable: table) }
}
func columns(in table: String) -> [ColumnInfo]? { return nil }
func set(columns: [ColumnInfo], forTable table: String) { }
func columns(in table: String) -> [ColumnInfo]? {
return cache.read { $0.columns(in: table) }
}
func indexes(on table: String) -> [IndexInfo]? { return nil }
func set(indexes: [IndexInfo], forTable table: String) { }
func set(columns: [ColumnInfo], forTable table: String) {
cache.write { $0.set(columns: columns, forTable: table) }
}
func indexes(on table: String) -> [IndexInfo]? {
return cache.read { $0.indexes(on: table) }
}
func set(indexes: [IndexInfo], forTable table: String) {
cache.write { $0.set(indexes: indexes, forTable: table) }
}
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
return cache.read { $0.foreignKeys(on: table) }
}
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
cache.write { $0.set(foreignKeys: foreignKeys, forTable: table) }
}
func foreignKeys(on table: String) -> [ForeignKeyInfo]? { return nil }
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { }
}
+16 -6
View File
@@ -10,7 +10,7 @@ import Foundation
/// DatabaseValue is the intermediate type between SQLite and your values.
///
/// See https://www.sqlite.org/datatype3.html
public struct DatabaseValue {
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpressible, SQLExpression {
/// The SQLite storage
public let storage: Storage
@@ -146,9 +146,11 @@ public struct DatabaseValue {
// MARK: - Hashable & Equatable
extension DatabaseValue : Hashable {
// Hashable
extension DatabaseValue {
/// The hash value
/// :nodoc:
public var hashValue: Int {
switch storage {
case .null:
@@ -280,7 +282,8 @@ extension DatabaseValue {
}
}
extension DatabaseValue : DatabaseValueConvertible {
// DatabaseValueConvertible
extension DatabaseValue {
/// Returns self
public var databaseValue: DatabaseValue {
return self
@@ -292,15 +295,19 @@ extension DatabaseValue : DatabaseValueConvertible {
}
}
extension DatabaseValue : SQLExpressible {
// SQLExpressible
extension DatabaseValue {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var sqlExpression: SQLExpression {
return self
}
}
extension DatabaseValue : SQLExpression {
// SQLExpression
extension DatabaseValue {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
// fast path for NULL
if isNull {
@@ -318,6 +325,7 @@ extension DatabaseValue : SQLExpression {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var negated: SQLExpression {
switch storage {
case .null:
@@ -343,7 +351,9 @@ extension DatabaseValue : SQLExpression {
}
}
extension DatabaseValue : CustomStringConvertible {
// CustomStringConvertible
extension DatabaseValue {
/// :nodoc:
public var description: String {
switch storage {
case .null:
+3
View File
@@ -32,6 +32,7 @@ public protocol DatabaseValueConvertible : SQLExpressible {
extension DatabaseValueConvertible {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var sqlExpression: SQLExpression {
return databaseValue
}
@@ -60,6 +61,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Value? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
@@ -99,6 +101,7 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Value?? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
+22 -54
View File
@@ -41,65 +41,23 @@ public protocol DatabaseWriter : DatabaseReader {
/// Synchronously or asynchronously executes a read-only block that takes a
/// database connection.
///
/// This method must be called from a writing dispatch queue.
/// This method must be called from a writing dispatch queue, outside of any
/// transaction. You'll get a fatal error otherwise.
///
/// The *block* argument is guaranteed to see the database in the state it
/// has at the moment this method is called (see below). Eventual concurrent
/// The *block* argument is guaranteed to see the database in the last
/// committed state at the moment this method is called. Eventual concurrent
/// database updates are *not visible* inside the block.
///
/// What is the "current state" of the database?
/// For example:
///
/// - When this method is called outside of any transaction, the current
/// state is the last committed state.
///
/// try writer.write { db in
/// try db.execute("DELETE FROM players")
/// try writer.readFromCurrentState { db in
/// // Guaranteed to be zero
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
/// }
/// try db.execute("INSERT INTO players ...")
/// try writer.write { db in
/// try db.execute("DELETE FROM players")
/// try writer.readFromCurrentState { db in
/// // Guaranteed to be zero
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
/// }
///
/// - When this method is called inside an uncommitted transation, the
/// current state depends on the caller:
///
/// DatabasePool.readFromCurrentState runs *block* asynchronously in a
/// concurrent reader dispatch queue, and release the writing dispatch
/// queue early, before the block has finished. In the example below,
/// the insertion runs concurrently with the select, and the select sees
/// the database in its last committed state.
///
/// try dbPool.write { db in
/// try db.execute("DELETE FROM players")
/// db.inTransaction {
/// try db.execute("INSERT INTO players ...")
/// try dbPool.readFromCurrentState { db in
/// // Zero
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
/// }
/// return .commit
/// }
/// }
///
/// DatabaseQueue.readFromCurrentState simply runs *block* synchronously,
/// and returns when the block has completed. In the example below, the
/// select sees the uncommitted state of the database, and the insertion
/// is run after the select.
///
/// try dbQueue.write { db in
/// try db.execute("DELETE FROM players")
/// db.inTransaction {
/// try db.execute("INSERT INTO players ...")
/// try dbQueue.readFromCurrentState { db in
/// // One
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
/// }
/// return .commit
/// }
/// }
///
/// This method is *not* reentrant.
/// try db.execute("INSERT INTO players ...")
/// }
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
}
@@ -138,48 +96,58 @@ public final class AnyDatabaseWriter : DatabaseWriter {
// MARK: - Reading from Database
/// :nodoc:
public func read<T>(_ block: (Database) throws -> T) throws -> T {
return try base.read(block)
}
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeRead(block)
}
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeReentrantRead(block)
}
/// :nodoc:
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
try base.readFromCurrentState(block)
}
// MARK: - Writing in Database
/// :nodoc:
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
return try base.write(block)
}
/// :nodoc:
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
return try base.unsafeReentrantWrite(block)
}
// MARK: - Functions
/// :nodoc:
public func add(function: DatabaseFunction) {
base.add(function: function)
}
/// :nodoc:
public func remove(function: DatabaseFunction) {
base.remove(function: function)
}
// MARK: - Collations
/// :nodoc:
public func add(collation: DatabaseCollation) {
base.add(collation: collation)
}
/// :nodoc:
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
+80 -39
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,7 @@ 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.
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let (statement, baseAdapter) = try base.prepare(db)
if let baseAdapter = baseAdapter {
@@ -98,15 +113,15 @@ public struct AdaptedRequest<Base: Request> : Request {
}
}
/// The number of rows fetched by the request.
///
/// - parameter db: A database connection.
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try base.fetchCount(db)
}
private let base: Base
private let adapter: (Database) throws -> RowAdapter
/// :nodoc:
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try base.fetchedRegion(db)
}
}
/// A type-erased Request.
@@ -114,26 +129,39 @@ 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.
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try _prepare(db)
return try base.prepare(db)
}
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try base.fetchCount(db)
}
/// :nodoc:
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try base.fetchedRegion(db)
}
}
/// A Request built from raw SQL.
@@ -183,7 +211,9 @@ public struct SQLRequest : Request {
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
///
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let statement: SelectStatement
switch cache {
case .none:
@@ -239,32 +269,31 @@ 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.
/// :nodoc:
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.
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try adaptedRequest.fetchCount(db)
return try base.fetchCount(db)
}
private let adaptedRequest: AdaptedRequest<Base>
/// :nodoc:
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try base.fetchedRegion(db)
}
}
/// A type-erased TypedRequest.
@@ -274,27 +303,39 @@ 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.
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try _prepare(db)
return try base.prepare(db)
}
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try base.fetchCount(db)
}
/// :nodoc:
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try base.fetchedRegion(db)
}
}
extension TypedRequest where RowDecoder: RowConvertible {
+39 -30
View File
@@ -6,7 +6,7 @@ import Foundation
#endif
/// A database row.
public final class Row {
public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible {
let impl: RowImpl
/// Unless we are producing a row array, we use a single row when iterating
@@ -506,6 +506,7 @@ public final class RowCursor : Cursor {
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Row? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
@@ -725,7 +726,8 @@ extension Row {
}
}
extension Row : ExpressibleByDictionaryLiteral {
// ExpressibleByDictionaryLiteral
extension Row {
/// Creates a row initialized with elements. Column order is preserved, and
/// duplicated columns names are allowed.
@@ -738,17 +740,20 @@ extension Row : ExpressibleByDictionaryLiteral {
}
}
extension Row : Collection {
// RandomAccessCollection
extension Row {
// MARK: - Row as a Collection of (ColumnName, DatabaseValue) Pairs
/// The index of the first (ColumnName, DatabaseValue) pair.
/// :nodoc:
public var startIndex: RowIndex {
return Index(0)
}
/// The "past-the-end" index, successor of the index of the last
/// (ColumnName, DatabaseValue) pair.
/// :nodoc:
public var endIndex: RowIndex {
return Index(count)
}
@@ -761,25 +766,14 @@ 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.
extension Row : Equatable {
// Equatable
extension Row {
/// Returns true if and only if both rows have the same columns and values,
/// in the same order. Columns are compared in a case-sensitive way.
/// :nodoc:
public static func == (lhs: Row, rhs: Row) -> Bool {
if lhs === rhs {
return true
@@ -789,10 +783,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
}
@@ -819,17 +810,19 @@ extension Row : Equatable {
}
}
/// Row adopts Hashable.
extension Row : Hashable {
// Hashable
extension Row {
/// The hash value
/// :nodoc:
public var hashValue: Int {
return columnNames.reduce(0) { (acc, column) in acc ^ column.hashValue } ^
databaseValues.reduce(0) { (acc, dbValue) in acc ^ dbValue.hashValue }
}
}
/// Row adopts CustomStringConvertible.
extension Row: CustomStringConvertible {
// CustomStringConvertible
extension Row {
/// :nodoc:
public var description: String {
return "<Row"
+ map { (column, dbValue) in
@@ -842,22 +835,38 @@ extension Row: CustomStringConvertible {
// MARK: - RowIndex
/// Indexes to (columnName, dbValue) pairs in a database row.
public struct RowIndex : Comparable {
/// Indexes to (ColumnName, DatabaseValue) pairs in a database row.
public struct RowIndex : Comparable, Strideable {
let index: Int
init(_ index: Int) { self.index = index }
/// Equality operator
}
// Comparable
extension RowIndex {
/// :nodoc:
public static func == (lhs: RowIndex, rhs: RowIndex) -> Bool {
return lhs.index == rhs.index
}
// Comparison operator
/// :nodoc:
public static func < (lhs: RowIndex, rhs: RowIndex) -> Bool {
return lhs.index < rhs.index
}
}
// Strideable: support for Row: RandomAccessCollection
extension RowIndex {
/// :nodoc:
public func distance(to other: RowIndex) -> Int {
return other.index - index
}
/// :nodoc:
public func advanced(by n: Int) -> RowIndex {
return RowIndex(index + n)
}
}
// MARK: - RowImpl
+21
View File
@@ -3,6 +3,8 @@ import Foundation
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// LayoutedColumnMapping is a type that supports the RowAdapter protocol.
///
/// :nodoc:
public struct LayoutedColumnMapping {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -56,6 +58,8 @@ public struct LayoutedColumnMapping {
}
/// LayoutedColumnMapping adopts LayoutedRowAdapter
///
/// :nodoc:
extension LayoutedColumnMapping : LayoutedRowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -72,6 +76,7 @@ extension LayoutedColumnMapping : LayoutedRowAdapter {
}
}
/// :nodoc:
extension LayoutedColumnMapping : RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -91,6 +96,8 @@ extension LayoutedColumnMapping : RowLayout {
///
/// GRBD ships with a ready-made type that adopts this protocol:
/// LayoutedColumnMapping.
///
/// :nodoc:
public protocol LayoutedRowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -108,6 +115,8 @@ public protocol LayoutedRowAdapter {
///
/// RowLayout is a protocol that supports the RowAdapter protocol. It describes
/// a layout of a base row.
///
/// :nodoc:
public protocol RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -124,11 +133,15 @@ public protocol RowLayout {
extension SelectStatement : RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public var layoutColumns: [(Int, String)] {
return Array(columnNames.enumerated())
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func layoutIndex(ofColumn name: String) -> Int? {
return index(ofColumn: name)
}
@@ -214,6 +227,8 @@ public struct ColumnMapping : RowAdapter {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
let layoutColumns = try mapping
.map { (mappedColumn, baseColumn) -> (Int, String) in
@@ -250,6 +265,8 @@ public struct SuffixRowAdapter : RowAdapter {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index))
}
@@ -279,6 +296,8 @@ public struct RangeRowAdapter : RowAdapter {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range])
}
@@ -329,6 +348,8 @@ public struct ScopeAdapter : RowAdapter {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
let layoutedAdapter = try mainAdapter.layoutedAdapter(from: layout)
var layoutedScopes = layoutedAdapter.scopes
+10 -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]
var databaseObservationBroker: DatabaseObservationBroker?
private init(allowedDatabase database: Database) {
allowedDatabases = [database]
@@ -36,27 +37,22 @@ 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)
}
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.
+104 -101
View File
@@ -8,20 +8,13 @@ import Foundation
/// A raw SQLite statement, suitable for the SQLite C API.
public typealias SQLiteStatement = OpaquePointer
/// Statements are separated by semicolons and white spaces
let statementSeparatorCharacterSet = CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines)
/// An error emitted when one tries to compile an empty statement.
struct EmptyStatementError : Error {
}
/// A common protocol for UpdateStatement and SelectStatement
protocol AuthorizedStatement {
init(
database: Database,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
}
/// A statement represents an SQL query.
///
/// It is the base class of UpdateStatement that executes *update statements*,
@@ -35,10 +28,9 @@ public class Statement {
public var sql: String {
// trim white space and semicolumn for homogeneous output
return String(cString: sqlite3_sql(sqliteStatement))
.trimmingCharacters(in: CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines))
.trimmingCharacters(in: statementSeparatorCharacterSet)
}
/// The database
unowned let database: Database
/// Creates a prepared statement.
@@ -73,9 +65,6 @@ public class Statement {
}
guard let statement = sqliteStatement else {
// Sanity check: verify that the string contains only whitespace
assert(String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: statementStart), count: statementEnd.pointee! - statementStart, deallocator: .none), encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
// I wish we could simply return nil, and make this initializer failable.
//
// Unfortunately, there is a Swift bug with failable+throwing initializers:
@@ -223,6 +212,73 @@ public class Statement {
}
}
// MARK: - AuthorizedStatement
/// A common protocol for UpdateStatement and SelectStatement
protocol AuthorizedStatement {
// This initializer should be a required initializer of Statement.
//
// But Swift requires this required initializer to be public:
// https://bugs.swift.org/browse/SR-2347
//
// We work around SR-2347 with this internal protocol.
init(
database: Database,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
}
extension AuthorizedStatement {
// Static function instead of an initializer because initializer doesn't
// compile due to the "capturing of an uninitialized self" in
// `sqlCodeUnits.withUnsafeBufferPointer`.
static func prepare(sql: String, prepFlags: Int32, in database: Database) throws -> Self {
let authorizer = StatementCompilationAuthorizer()
database.authorizer = authorizer
defer { database.authorizer = nil }
let sqlCodeUnits = sql.utf8CString
return try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let statementStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
var statementEnd: UnsafePointer<Int8>? = nil
let statement: Self
do {
statement = try self.init(
database: database,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: prepFlags,
authorizer: authorizer)
} catch is EmptyStatementError {
throw DatabaseError(
resultCode: .SQLITE_ERROR,
message: "empty statement",
sql: sql,
arguments: nil)
}
let remainingData = Data(
bytesNoCopy: UnsafeMutableRawPointer(mutating: statementEnd!),
count: statementStart + sqlCodeUnits.count - statementEnd! - 1,
deallocator: .none)
let remainingSQL = String(data: remainingData, encoding: .utf8)!
.trimmingCharacters(in: statementSeparatorCharacterSet)
guard remainingSQL.isEmpty else {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.",
sql: sql,
arguments: nil)
}
return statement
}
}
}
// MARK: - SelectStatement
@@ -235,9 +291,17 @@ public class Statement {
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// 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
public final class SelectStatement : Statement {
/// :nodoc:
@available(*, deprecated, renamed:"DatabaseRegion")
public typealias SelectionInfo = DatabaseRegion
/// :nodoc:
@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.
///
@@ -258,7 +322,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,
@@ -268,7 +332,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.
@@ -308,70 +372,11 @@ 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: ",")
}
}
}
// Hide AuthorizedStatement from Jazzy
extension SelectStatement: AuthorizedStatement { }
/// A cursor that iterates a database statement without producing any value.
/// For example:
///
@@ -391,6 +396,7 @@ public final class StatementCursor: Cursor {
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Void? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
@@ -419,7 +425,7 @@ public final class StatementCursor: Cursor {
/// try statement.execute(arguments: ["Barbara"])
/// return .commit
/// }
public final class UpdateStatement : Statement, AuthorizedStatement {
public final class UpdateStatement : Statement {
enum TransactionEffect {
case beginTransaction
case commitTransaction
@@ -433,10 +439,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]
@@ -460,7 +462,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
authorizer: StatementCompilationAuthorizer) throws
{
self.invalidatesDatabaseSchemaCache = false
self.needsTruncateOptimizationPreventionDuringExecution = false
self.databaseEventKinds = []
try super.init(
database: database,
@@ -468,7 +469,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
}
@@ -483,10 +483,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:
@@ -509,12 +505,10 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
continue
case SQLITE_DONE:
database.authorizer = nil
database.updateStatementDidExecute(self)
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.
}
@@ -522,6 +516,9 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
}
}
// Hide AuthorizedStatement from Jazzy
extension UpdateStatement: AuthorizedStatement { }
// MARK: - StatementArguments
@@ -596,7 +593,7 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
/// let row = try Row.fetchOne(db, sql, arguments: [1, 2, "bar"] + ["foo": "foo"])!
/// print(row)
/// // Prints <Row two:2 foo:"foo" one:1 foo2:"foo" bar:"bar">
public struct StatementArguments {
public struct StatementArguments: CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {
var values: [DatabaseValue] = []
var namedValues: [String: DatabaseValue] = [:]
@@ -882,7 +879,8 @@ public struct StatementArguments {
}
}
extension StatementArguments : ExpressibleByArrayLiteral {
// ExpressibleByArrayLiteral
extension StatementArguments {
/// Returns a StatementArguments from an array literal:
///
/// db.selectRows("SELECT ...", arguments: ["Arthur", 41])
@@ -891,7 +889,8 @@ extension StatementArguments : ExpressibleByArrayLiteral {
}
}
extension StatementArguments : ExpressibleByDictionaryLiteral {
// ExpressibleByDictionaryLiteral
extension StatementArguments {
/// Returns a StatementArguments from a dictionary literal:
///
/// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "score": 41])
@@ -900,7 +899,9 @@ extension StatementArguments : ExpressibleByDictionaryLiteral {
}
}
extension StatementArguments : CustomStringConvertible {
// CustomStringConvertible
extension StatementArguments {
/// :nodoc:
public var description: String {
let valuesDescriptions = values.map { $0.description }
let namedValuesDescriptions = namedValues.map { (key, value) -> String in
@@ -910,7 +911,9 @@ extension StatementArguments : CustomStringConvertible {
}
}
extension StatementArguments : Equatable {
// Equatable
extension StatementArguments {
/// :nodoc:
public static func == (lhs: StatementArguments, rhs: StatementArguments) -> Bool {
if lhs.values != rhs.values { return false }
if lhs.namedValues != rhs.namedValues { return false }
+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,
@@ -73,6 +73,7 @@ public final class ColumnCursor<Value: DatabaseValueConvertible & StatementColum
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Value? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
@@ -118,6 +119,7 @@ public final class NullableColumnCursor<Value: DatabaseValueConvertible & Statem
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Value?? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
+446 -173
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,74 +161,138 @@ 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)
// As statement executes, it may trigger database changes that will
// be notified to transaction observers. As a consequence, observers
// may disable themselves with stopObservingDatabaseChangesUntilNextTransaction()
//
// This method takes no argument, and requires access to the "current
// broker", which is a per-thread global stored in
// SchedulingWatchdog.current:
SchedulingWatchdog.current!.databaseObservationBroker = 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 = []
database.authorizer = nil
SchedulingWatchdog.current!.databaseObservationBroker = nil
// Reset transactionState before databaseDidRollback eventually
// executes other statements.
let transactionState = self.transactionState
@@ -250,45 +312,26 @@ class DatabaseObservationBroker {
}
}
func updateStatementDidExecute(_ statement: UpdateStatement) {
// Wait for next statement
activeTransactionObservations = []
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
// Undo updateStatementWillExecute
statementObservations = []
database.authorizer = nil
SchedulingWatchdog.current!.databaseObservationBroker = nil
// Has statement any effect on transaction/savepoints?
if let transactionEffect = statement.transactionEffect {
// Statement has modified transaction/savepoint state
switch transactionEffect {
case .beginTransaction:
break
case .commitTransaction:
if case .none = self.transactionState {
// A COMMIT statement has ended an empty deferred
// transaction. For SQLite, no transaction has ever begun:
case .commitTransaction: // 1. A COMMIT statement has been executed
if case .none = self.transactionState { // 2. sqlite3_commit_hook was not triggered
// 1+2 mean that an empty deferred transaction has been completed:
//
// BEGIN DEFERRED TRANSACTION
// COMMIT
// BEGIN DEFERRED TRANSACTION; COMMIT
//
// We don't need to tell transaction observers about it.
//
// But we have to take care of the .nextTransaction
// observation extent. In the sample code below, the
// observer must not be notified of the second transaction,
// because this is the intent of the programmer:
//
// // Register an observer for next transaction only
// let observer = Observer()
// dbQueue.add(transactionObserver:observer, extent: .nextTransaction)
//
// try dbQueue.inTransaction(.deferred) { db in
// return .commit
// }
//
// // Must not notify observer
// try dbQueue.inTransaction(.deferred) { db in
// try db.execute("...")
// return .commit
// }
emptyDeferredTransactionDidCommit()
// This special case has a dedicated handling:
return try databaseDidCommitEmptyDeferredTransaction()
}
case .rollbackTransaction:
@@ -297,17 +340,22 @@ class DatabaseObservationBroker {
case .beginSavepoint(let name):
savepointStack.savepointDidBegin(name)
case .releaseSavepoint(let name):
case .releaseSavepoint(let name): // 1. A RELEASE SAVEPOINT statement has been executed
savepointStack.savepointDidRelease(name)
if case .none = self.transactionState, // 2. sqlite3_commit_hook was not triggered
!database.isInsideTransaction // 3. database is no longer inside a transaction
{
// 1+2+3 mean that an empty deferred transaction has been completed:
//
// SAVEPOINT foo; RELEASE SAVEPOINT foo
//
// This special case has a dedicated handling:
return try databaseDidCommitEmptyDeferredTransaction()
}
if savepointStack.isEmpty {
// Notify buffered events
let eventsBuffer = savepointStack.eventsBuffer
savepointStack.clear()
for (event, observations) in eventsBuffer {
for observation in observations {
event.send(to: observation)
}
}
notifyBufferedEvents()
}
case .rollbackSavepoint(let name):
@@ -335,42 +383,43 @@ 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
// transaction observers. In this method, observers may disable
// themselves with stopObservingDatabaseChangesUntilNextTransaction()
//
// This method takes no argument, and requires access to the "current
// broker", which is a per-thread global stored in
// SchedulingWatchdog.current:
assert(SchedulingWatchdog.current?.databaseObservationBroker != 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
// MARK: - End of transaction
// Called from sqlite3_commit_hook and databaseDidCommitEmptyDeferredTransaction()
private func databaseWillCommit() throws {
// Time to send all buffered events
let eventsBuffer = savepointStack.eventsBuffer
savepointStack.clear()
for (event, observations) in eventsBuffer {
for observation in observations {
event.send(to: observation)
}
}
notifyBufferedEvents()
for observation in transactionObservations {
try observation.databaseWillCommit()
}
@@ -383,15 +432,50 @@ class DatabaseObservationBroker {
for observation in transactionObservations {
observation.databaseDidCommit(database)
}
cleanupTransactionObservations()
databaseDidEndTransaction()
}
// Called from updateStatementDidExecute
private func emptyDeferredTransactionDidCommit() {
for observation in transactionObservations {
observation.emptyDeferredTransactionDidCommit(database)
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:
//
// try db.execute("BEGIN DEFERRED TRANSACTION")
// try db.execute("COMMIT") // <- no sqlite3_commit_hook callback invocation
//
// Should we tell transaction observers of this transaction, or not?
// The code says that a transaction was open, but SQLite says the
// opposite. How do we lift this ambiguity? Should we notify of
// *transactions expressed in the code*, or *SQLite transactions* only?
//
// If we would notify of SQLite transactions only, then we'd notify of
// all transactions expressed in the code, but empty deferred
// transaction. This means that we'd make an exception. And exceptions
// are the recipe for both surprise and confusion.
//
// For example, is the code below expected to print "did commit"?
//
// db.afterNextTransactionCommit { _ in print("did commit") }
// try db.inTransaction {
// performSomeTask(db)
// return .commit
// }
//
// Yes it is. And the only way to make it reliably print "did commit" is
// to behave consistently, regardless of the implementation of the
// `performSomeTask` function. Even if the `performSomeTask` is empty,
// even if we actually execute an empty deferred transaction.
//
// For better or for worse, let's simulate a transaction:
do {
try databaseWillCommit()
databaseDidCommit()
} catch {
databaseDidRollback(notifyTransactionObservers: true)
throw error
}
cleanupTransactionObservations()
}
// Called from updateStatementDidExecute or updateStatementDidFails
@@ -403,11 +487,115 @@ 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() {
// We're about to call the databaseDidChange(with:) method of
// transaction observers. In this method, observers may disable
// themselves with stopObservingDatabaseChangesUntilNextTransaction()
//
// This method takes no argument, and requires access to the "current
// broker", which is a per-thread global stored in
// SchedulingWatchdog.current.
//
// Normally, notifyBufferedEvents() is called as part of statement
// execution, and the current broker has been set in
// updateStatementWillExecute(). An assertion should be enough:
//
// assert(SchedulingWatchdog.current?.databaseObservationBroker != nil)
//
// But we have to deal with a particular case:
//
// let journalMode = String.fetchOne(db, "PRAGMA journal_mode = wal")
//
// It runs a SelectStatement, not an UpdateStatement. But this not why
// this case is particular. What is unexpected is that it triggers
// the commit hook when the "PRAGMA journal_mode = wal" statement is
// finalized, long after it has executed:
//
// 1. Statement.deinit()
// 2. sqlite3_finalize()
// 3. commit hook
// 4. DatabaseObservationBroker.databaseWillCommit()
// 5. DatabaseObservationBroker.notifyBufferedEvents()
//
// I don't know if this behavior is something that can be relied
// upon. One would naively expect, for example, that changing the
// journal mode would trigger the commit hook in sqlite3_step(),
// not in sqlite3_finalize().
//
// Anyway: in this scenario, updateStatementWillExecute() has not been
// called, and the current broker is nil.
//
// Let's not try to outsmart SQLite, and build a complex state machine.
// Instead, let's just make sure that the current broker is set to self
// when this method is called.
let watchDog = SchedulingWatchdog.current!
watchDog.databaseObservationBroker = self
defer {
watchDog.databaseObservationBroker = nil
}
// Now we can safely notify:
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(
@@ -438,16 +626,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
@@ -456,6 +635,8 @@ class DatabaseObservationBroker {
}
}
// MARK: - TransactionObserver
/// A transaction observer is notified of all changes and transactions committed
/// or rollbacked on a database.
///
@@ -468,13 +649,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)
@@ -511,34 +697,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.current?.databaseObservationBroker 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 }
@@ -565,10 +797,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)
}
@@ -582,7 +823,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
@@ -591,23 +832,13 @@ final class TransactionObservation {
}
}
func emptyDeferredTransactionDidCommit(_ db: Database) {
switch extent {
case .observerLifetime, .databaseLifetime:
break
case .nextTransaction:
// Observer most not get any further notification.
strongObserver = nil
}
}
func databaseDidRollback(_ db: Database) {
switch extent {
case .observerLifetime, .databaseLifetime:
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
@@ -615,16 +846,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)
@@ -635,19 +864,22 @@ 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)
}
}
/// :nodoc:
@available(*, deprecated, message: "Use DatabaseRegion.isModified(byEventsOfKind:) instead")
public func impacts(_ region: DatabaseRegion) -> Bool {
return region.isModified(byEventsOfKind: self)
}
}
extension DatabaseEventKind {
@@ -663,6 +895,7 @@ extension DatabaseEventKind {
protocol DatabaseEventProtocol {
func send(to observer: TransactionObservation)
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool
}
/// A database event, notified to TransactionObserver.
@@ -680,6 +913,8 @@ public struct DatabaseEvent {
case update = 23
}
private let impl: DatabaseEventImpl
/// The event kind
public let kind: Kind
@@ -713,14 +948,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
@@ -874,6 +1117,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
@@ -999,6 +1252,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
///
@@ -1009,8 +1281,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.
@@ -1063,3 +1335,4 @@ class SavepointStack {
}
}
}
+17 -4
View File
@@ -111,16 +111,16 @@ public struct FTS4 : VirtualTableModule {
let oldRowID = "old.\(rowIDColumn.quotedDatabaseIdentifier)"
try db.execute("""
CREATE TRIGGER \("__\(contentTable)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN
CREATE TRIGGER \("__\(tableName)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
END;
CREATE TRIGGER \("__\(contentTable)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN
CREATE TRIGGER \("__\(tableName)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
END;
CREATE TRIGGER \("__\(contentTable)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
END;
CREATE TRIGGER \("__\(contentTable)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
END;
""")
@@ -269,6 +269,7 @@ public final class FTS4ColumnDefinition {
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
///
/// - returns: Self so that you can further refine the column definition.
/// :nodoc:
@discardableResult
public func notIndexed() -> Self {
// notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
@@ -313,3 +314,15 @@ public final class FTS4ColumnDefinition {
return self
}
}
extension Database {
/// Deletes the synchronization triggers for a synchronized FTS4 table
public func dropFTS4SynchronizationTriggers(forTable tableName: String) throws {
try execute("""
DROP TRIGGER IF EXISTS \("__\(tableName)_bu".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_bd".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_ai".quotedDatabaseIdentifier);
""")
}
}
+14 -3
View File
@@ -111,13 +111,13 @@
.joined(separator: ", ")
try db.execute("""
CREATE TRIGGER \("__\(contentTable)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
END;
CREATE TRIGGER \("__\(contentTable)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
END;
CREATE TRIGGER \("__\(contentTable)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
END;
@@ -319,4 +319,15 @@
/// The FTS5 rank column
public static let rank = Column("rank")
}
extension Database {
/// Deletes the synchronization triggers for a synchronized FTS5 table
public func dropFTS5SynchronizationTriggers(forTable tableName: String) throws {
try execute("""
DROP TRIGGER IF EXISTS \("__\(tableName)_ai".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_ad".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier);
""")
}
}
#endif
+2
View File
@@ -85,6 +85,8 @@ public struct DatabaseMigrator {
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
///
/// :nodoc:
public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
+2
View File
@@ -17,6 +17,8 @@ public struct Column {
extension Column : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
return name.quotedDatabaseIdentifier
}
+191 -7
View File
@@ -16,6 +16,8 @@ extension QueryInterfaceRequest : TypedRequest {
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
///
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try query.prepare(db)
}
@@ -23,9 +25,18 @@ extension QueryInterfaceRequest : TypedRequest {
/// The number of rows fetched by the request.
///
/// - parameter db: A database connection.
///
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try query.fetchCount(db)
}
/// The database region that the request looks into.
///
/// :nodoc:
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try query.fetchedRegion(db)
}
}
extension QueryInterfaceRequest {
@@ -104,13 +115,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 +246,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 +438,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.
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) + ")"
}
}
}
@@ -51,11 +51,15 @@ public struct SQLCollatedExpression {
extension SQLCollatedExpression : SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public var reversed: SQLOrderingTerm {
return desc
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
return sqlExpression.orderingTermSQL(&arguments)
}
+2
View File
@@ -3,6 +3,8 @@
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLCollection is the protocol for types that can be checked for inclusion.
///
/// :nodoc:
public protocol SQLCollection {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
+14
View File
@@ -8,6 +8,8 @@
/// like Column.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// :nodoc:
public protocol SQLExpressible {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -27,6 +29,8 @@ public protocol SQLExpressible {
/// and it adopts SQLSpecificExpressible.
///
/// On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible).
///
/// :nodoc:
public protocol SQLSpecificExpressible : SQLExpressible {
// SQLExpressible can be adopted by Swift standard types, and user
// types, through the DatabaseValueConvertible protocol which inherits
@@ -53,11 +57,15 @@ public protocol SQLSpecificExpressible : SQLExpressible {
extension SQLExpressible where Self: SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public var reversed: SQLOrderingTerm {
return SQLOrdering.desc(sqlExpression)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
return sqlExpression.expressionSQL(&arguments)
}
@@ -68,16 +76,22 @@ extension SQLExpressible where Self: SQLOrderingTerm {
extension SQLExpressible where Self: SQLSelectable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
return sqlExpression.expressionSQL(&arguments)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func countedSQL(_ arguments: inout StatementArguments?) -> String {
return sqlExpression.expressionSQL(&arguments)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func count(distinct: Bool) -> SQLCount? {
return sqlExpression.count(distinct: distinct)
}
@@ -5,6 +5,8 @@ extension SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Converts an expression to an SQLExpressionLiteral
///
/// :nodoc:
public var literal: SQLExpressionLiteral {
var arguments: StatementArguments? = []
let sql = expressionSQL(&arguments)
@@ -57,6 +59,8 @@ public struct SQLExpressionLiteral : SQLExpression {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
if let literalArguments = self.arguments {
guard arguments != nil else {
@@ -75,6 +79,8 @@ public struct SQLExpressionLiteral : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLUnaryOperator is a SQLite unary operator.
///
/// :nodoc:
public struct SQLUnaryOperator : Hashable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -97,11 +103,15 @@ public struct SQLUnaryOperator : Hashable {
}
/// The hash value
///
/// :nodoc:
public var hashValue: Int {
return sql.hashValue
}
/// Equality operator
///
/// :nodoc:
public static func == (lhs: SQLUnaryOperator, rhs: SQLUnaryOperator) -> Bool {
return lhs.sql == rhs.sql
}
@@ -113,6 +123,8 @@ public struct SQLUnaryOperator : Hashable {
/// an operand expression.
///
/// SQLExpressionUnary(.not, Column("favorite"))
///
/// :nodoc:
public struct SQLExpressionUnary : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -147,6 +159,8 @@ public struct SQLExpressionUnary : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLBinaryOperator is a SQLite binary operator.
///
/// :nodoc:
public struct SQLBinaryOperator : Hashable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -223,6 +237,8 @@ public struct SQLBinaryOperator : Hashable {
/// binary operator.
///
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
///
/// :nodoc:
public struct SQLExpressionBinary : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -265,6 +281,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 +362,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
@@ -342,6 +436,8 @@ public struct SQLFunctionName : Hashable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The SQL function name
///
/// :nodoc:
public let sql: String
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -349,16 +445,22 @@ public struct SQLFunctionName : Hashable {
/// Creates a function name
///
/// SQLFunctionName("ABS")
///
/// :nodoc:
public init(_ sql: String) {
self.sql = sql
}
/// The hash value
///
/// :nodoc:
public var hashValue: Int {
return sql.hashValue
}
/// Equality operator
///
/// :nodoc:
public static func == (lhs: SQLFunctionName, rhs: SQLFunctionName) -> Bool {
return lhs.sql == rhs.sql
}
@@ -370,6 +472,8 @@ public struct SQLFunctionName : Hashable {
///
/// // ABS(-1)
/// SQLExpressionFunction(.abs, [-1.databaseValue])
///
/// :nodoc:
public struct SQLExpressionFunction : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
+21
View File
@@ -16,6 +16,8 @@
/// - SQLExpressionExists
/// - SQLExpressionFunction
/// - SQLExpressionCollate
///
/// :nodoc:
public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -53,6 +55,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 {
@@ -64,9 +71,19 @@ extension SQLExpression {
/// let column = Column("favorite")
/// column.negated // NOT favorite
///
/// :nodoc:
public var negated: SQLExpression {
return SQLExpressionNot(self)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The default implementation returns nil
///
/// :nodoc:
public func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
return nil
}
}
// SQLExpression: SQLExpressible
@@ -74,6 +91,8 @@ extension SQLExpression {
extension SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public var sqlExpression: SQLExpression {
return self
}
@@ -84,6 +103,8 @@ extension SQLExpression {
extension SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func count(distinct: Bool) -> SQLCount? {
if distinct {
// SELECT DISTINCT expr FROM tableName ...
+2
View File
@@ -4,6 +4,8 @@
///
/// The protocol for all types that can be used as an SQL ordering term, as
/// described at https://www.sqlite.org/syntax/ordering-term.html
///
/// :nodoc:
public protocol SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -21,16 +21,22 @@ public struct AllColumns {
extension AllColumns : SQLSelectable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
return "*"
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func countedSQL(_ arguments: inout StatementArguments?) -> String {
return "*"
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func count(distinct: Bool) -> SQLCount? {
// SELECT DISTINCT * FROM tableName ...
guard !distinct else {
+4
View File
@@ -4,6 +4,8 @@
///
/// SQLSelectable is the protocol for types that can be selected, as
/// described at https://www.sqlite.org/syntax/result-column.html
///
/// :nodoc:
public protocol SQLSelectable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func resultColumnSQL(_ arguments: inout StatementArguments?) -> String
@@ -18,6 +20,8 @@ public protocol SQLSelectable {
// MARK: - Counting
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public enum SQLCount {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -587,7 +587,7 @@ extension SQLBinaryOperator {
extension SQLUnaryOperator {
/// The `-` unary operator
public static let minus = SQLUnaryOperator("-", needsRightSpace: false)
static let minus = SQLUnaryOperator("-", needsRightSpace: false)
}
/// An SQL arithmetic multiplication.
+1 -1
View File
@@ -495,7 +495,7 @@ public final class TableAlteration {
/// - returns: An ColumnDefinition that allows you to refine the
/// column definition.
@discardableResult
public func add(column name: String, _ type: Database.ColumnType) -> ColumnDefinition {
public func add(column name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition {
let column = ColumnDefinition(name: name, type: type)
addedColumns.append(column)
return column
+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
+8 -4
View File
@@ -13,14 +13,16 @@ extension Database.ConflictResolution {
// MARK: - PersistenceError
/// An error thrown by a type that adopts Persistable.
public enum PersistenceError: Error {
public enum PersistenceError: Error, CustomStringConvertible {
/// Thrown by MutablePersistable.update() when no matching row could be
/// found in the database.
case recordNotFound(MutablePersistable)
}
extension PersistenceError : CustomStringConvertible {
// CustomStringConvertible
extension PersistenceError {
/// :nodoc:
public var description: String {
switch self {
case .recordNotFound(let persistable):
@@ -96,6 +98,8 @@ public struct PersistenceContainer {
/// Accesses the value associated with the given column, in a
/// case-insensitive fashion.
///
/// :nodoc:
subscript(caseInsensitive column: String) -> DatabaseValueConvertible? {
get {
if let value = storage[column] {
@@ -572,7 +576,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 +627,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
+100
View File
@@ -0,0 +1,100 @@
/// RecordBox is a subclass of Record that aims at giving any record type the
/// changes tracking provided by the Record class.
///
/// // A Regular record struct
/// struct Player: RowConvertible, MutablePersistable, Codable {
/// static let databaseTableName = "players"
/// var id: Int64?
/// var name: String
/// var score: Int
/// mutating func didInsert(with rowID: Int64, for column: String?) {
/// id = rowID
/// }
/// }
///
/// try dbQueue.inDatabase { db in
/// // Fetch a player record
/// let playerRecord = try RecordBox<Player>.fetchOne(db, key: 1)!
///
/// // Profit from changes tracking
/// playerRecord.value.score = 300
/// playerRecord.hasPersistentChangedValues // true
/// playerRecord.persistentChangedValues["score"] // 100 (the old value)
/// }
public final class RecordBox<T: RowConvertible & MutablePersistable>: Record {
/// The boxed record
public var value: T
/// Creates a RecordBox that wraps the given record
public init(value: T) {
self.value = value
super.init()
}
// MARK: - RowConvertible
/// Initializes a record from `row`.
public required init(row: Row) {
self.value = T(row: row)
super.init(row: row)
}
// MARK: - TableMapping
/// :nodoc:
override public class var databaseTableName: String {
return T.databaseTableName
}
/// :nodoc:
override public class var databaseSelection: [SQLSelectable] {
return T.databaseSelection
}
// MARK: - MutablePersistable
/// :nodoc:
override public class var persistenceConflictPolicy: PersistenceConflictPolicy {
return T.persistenceConflictPolicy
}
/// :nodoc:
override public func encode(to container: inout PersistenceContainer) {
value.encode(to: &container)
}
/// :nodoc:
override public func didInsert(with rowID: Int64, for column: String?) {
value.didInsert(with: rowID, for: column)
}
/// :nodoc:
override public func insert(_ db: Database) throws {
try value.insert(db)
hasPersistentChangedValues = false
}
/// :nodoc:
override public func update(_ db: Database, columns: Set<String>) throws {
try value.update(db, columns: columns)
hasPersistentChangedValues = false
}
/// :nodoc:
@discardableResult
override public func delete(_ db: Database) throws -> Bool {
defer {
// Future calls to update() will throw NotFound. Make the user
// a favor and make sure this error is thrown even if she checks the
// hasPersistentChangedValues flag:
hasPersistentChangedValues = true
}
return try value.delete(db)
}
/// :nodoc:
public func exists(_ db: Database) throws -> Bool {
return try value.exists(db)
}
}
+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)
}
}
+1
View File
@@ -51,6 +51,7 @@ public final class RecordCursor<Record: RowConvertible> : Cursor {
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Record? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
-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)
}
}
+8
View File
@@ -23,16 +23,24 @@ public func databaseQuestionMarks(count: Int) -> String {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// This protocol is an implementation detail of GRDB. Don't use it.
///
/// :nodoc:
public protocol _OptionalProtocol {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
associatedtype _Wrapped
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// This conformance is an implementation detail of GRDB. Don't rely on it.
///
/// :nodoc:
extension Optional : _OptionalProtocol {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public typealias _Wrapped = Wrapped
}
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDBCipher'
s.version = '2.2.0'
s.version = '2.7.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
+3113
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:GRDBCipher.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded</key>
<false/>
</dict>
</plist>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
LastUpgradeVersion = "0910"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -17,7 +17,35 @@
BlueprintIdentifier = "560FC5191CB003810014AA8E"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipherOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "560FC55D1CB00B880014AA8E"
BuildableName = "GRDBCipherOSXTests.xctest"
BlueprintName = "GRDBCipherOSXTests"
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "567156191CB16729007DC145"
BuildableName = "GRDBCipherOSXEncryptedTests.xctest"
BlueprintName = "GRDBCipherOSXEncryptedTests"
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
@@ -26,6 +54,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
@@ -35,7 +64,7 @@
BlueprintIdentifier = "560FC55D1CB00B880014AA8E"
BuildableName = "GRDBCipherOSXTests.xctest"
BlueprintName = "GRDBCipherOSXTests"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</TestableReference>
<TestableReference
@@ -45,7 +74,7 @@
BlueprintIdentifier = "567156191CB16729007DC145"
BuildableName = "GRDBCipherOSXEncryptedTests.xctest"
BlueprintName = "GRDBCipherOSXEncryptedTests"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
@@ -55,7 +84,7 @@
BlueprintIdentifier = "560FC5191CB003810014AA8E"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipherOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
@@ -65,6 +94,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
@@ -77,7 +107,7 @@
BlueprintIdentifier = "560FC5191CB003810014AA8E"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipherOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
@@ -95,7 +125,7 @@
BlueprintIdentifier = "560FC5191CB003810014AA8E"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipherOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
LastUpgradeVersion = "0910"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -17,7 +17,35 @@
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipheriOS"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56AFCA841CB1ABC800F48B96"
BuildableName = "GRDBCipheriOSEncryptedTests.xctest"
BlueprintName = "GRDBCipheriOSEncryptedTests"
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56AFCA2B1CB1AA9900F48B96"
BuildableName = "GRDBCipheriOSTests.xctest"
BlueprintName = "GRDBCipheriOSTests"
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
@@ -26,6 +54,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
@@ -35,7 +64,7 @@
BlueprintIdentifier = "56AFCA2B1CB1AA9900F48B96"
BuildableName = "GRDBCipheriOSTests.xctest"
BlueprintName = "GRDBCipheriOSTests"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</TestableReference>
<TestableReference
@@ -45,7 +74,7 @@
BlueprintIdentifier = "56AFCA841CB1ABC800F48B96"
BuildableName = "GRDBCipheriOSEncryptedTests.xctest"
BlueprintName = "GRDBCipheriOSEncryptedTests"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
@@ -55,7 +84,7 @@
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipheriOS"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
@@ -65,6 +94,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
@@ -77,7 +107,7 @@
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipheriOS"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCipher.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
@@ -89,15 +119,6 @@
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipheriOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
+2464
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:GRDBCustom.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded</key>
<false/>
</dict>
</plist>
@@ -17,7 +17,21 @@
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCustom.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F3BA809A1CFB2F6F003DC1BA"
BuildableName = "GRDBCustomSQLiteOSXTests.xctest"
BlueprintName = "GRDBCustomSQLiteOSXTests"
ReferencedContainer = "container:GRDBCustom.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
@@ -26,6 +40,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
@@ -35,7 +50,7 @@
BlueprintIdentifier = "F3BA809A1CFB2F6F003DC1BA"
BuildableName = "GRDBCustomSQLiteOSXTests.xctest"
BlueprintName = "GRDBCustomSQLiteOSXTests"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCustom.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
@@ -45,7 +60,7 @@
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCustom.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
@@ -55,21 +70,13 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
@@ -79,15 +86,6 @@
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
@@ -17,7 +17,21 @@
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteiOS"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCustom.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F3BA80401CFB2AD7003DC1BA"
BuildableName = "GRDBCustomSQLiteiOSTests.xctest"
BlueprintName = "GRDBCustomSQLiteiOSTests"
ReferencedContainer = "container:GRDBCustom.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
@@ -27,7 +41,8 @@
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<Testables>
<TestableReference
skipped = "NO">
@@ -36,7 +51,7 @@
BlueprintIdentifier = "F3BA80401CFB2AD7003DC1BA"
BuildableName = "GRDBCustomSQLiteiOSTests.xctest"
BlueprintName = "GRDBCustomSQLiteiOSTests"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCustom.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
@@ -46,7 +61,7 @@
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteiOS"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCustom.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
@@ -69,7 +84,7 @@
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteiOS"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCustom.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
@@ -87,7 +102,7 @@
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteiOS"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCustom.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
+29
View File
@@ -0,0 +1,29 @@
> ℹ We use Github issues for bug reports, feature requests, general support, and questions about the library.
>
> Please fill out this template when filing an issue, and remove this header before submitting.
## What did you do?
> Please replace this with what you did.
## What did you expect to happen?
> Please replace this with what you expected to happen.
## What happened instead?
> Please replace this with of what happened instead.
## Environment
**GRDB flavor(s):** (GRDB, GRDBCipher, GRDBCustom?)
**GRDB version:**
**Installation method:** (CocoaPods, SPM, manual?)
**Xcode version:**
**Swift version:**
**Platform(s) running GRDB:** (iOS, macOS, watchOS?)
**macOS version running Xcode:**
## Demo Project
> Please link to or upload a project we can download that reproduces the issue.
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (C) 2017 Gwendal Roué
Copyright (C) 2018 Gwendal Roué
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+26 -15
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)
@@ -46,9 +47,18 @@ TEST_ACTIONS = clean build build-for-testing test-without-building
# xcodebuild destination to run tests on iOS 8.1 (requires a pre-installed simulator)
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=8.1"
ifeq ($(XCODEVERSION),9.0)
# xcodebuild destination to run tests on latest iOS (Xcode 9.0)
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0"
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"
else ifeq ($(XCODEVERSION),9.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
@@ -127,7 +137,7 @@ test_framework_GRDBiOS_minTarget:
test_framework_GRDBCustomSQLiteOSX: SQLiteCustom
$(XCODEBUILD) \
-project GRDB.xcodeproj \
-project GRDBCustom.xcodeproj \
-scheme GRDBCustomSQLiteOSX \
$(TEST_ACTIONS) \
$(XCPRETTY)
@@ -136,7 +146,7 @@ test_framework_GRDBCustomSQLiteiOS: test_framework_GRDBCustomSQLiteiOS_maxTarget
test_framework_GRDBCustomSQLiteiOS_maxTarget: SQLiteCustom
$(XCODEBUILD) \
-project GRDB.xcodeproj \
-project GRDBCustom.xcodeproj \
-scheme GRDBCustomSQLiteiOS \
-destination $(MAX_IOS_DESTINATION) \
$(TEST_ACTIONS) \
@@ -144,7 +154,7 @@ test_framework_GRDBCustomSQLiteiOS_maxTarget: SQLiteCustom
test_framework_GRDBCustomSQLiteiOS_minTarget: SQLiteCustom
$(XCODEBUILD) \
-project GRDB.xcodeproj \
-project GRDBCustom.xcodeproj \
-scheme GRDBCustomSQLiteiOS \
-destination $(MIN_IOS_DESTINATION) \
$(TEST_ACTIONS) \
@@ -152,7 +162,7 @@ test_framework_GRDBCustomSQLiteiOS_minTarget: SQLiteCustom
test_framework_GRDBCipherOSX: SQLCipher
$(XCODEBUILD) \
-project GRDB.xcodeproj \
-project GRDBCipher.xcodeproj \
-scheme GRDBCipherOSX \
$(TEST_ACTIONS) \
$(XCPRETTY)
@@ -161,7 +171,7 @@ test_framework_GRDBCipheriOS: test_framework_GRDBCipheriOS_maxTarget test_framew
test_framework_GRDBCipheriOS_maxTarget: SQLCipher
$(XCODEBUILD) \
-project GRDB.xcodeproj \
-project GRDBCipher.xcodeproj \
-scheme GRDBCipheriOS \
-destination $(MAX_IOS_DESTINATION) \
$(TEST_ACTIONS) \
@@ -169,13 +179,14 @@ test_framework_GRDBCipheriOS_maxTarget: SQLCipher
test_framework_GRDBCipheriOS_minTarget: SQLCipher
$(XCODEBUILD) \
-project GRDB.xcodeproj \
-project GRDBCipher.xcodeproj \
-scheme GRDBCipheriOS \
-destination $(MIN_IOS_DESTINATION) \
$(TEST_ACTIONS) \
$(XCPRETTY)
test_SPM:
# Add sanitizers when available: https://twitter.com/simjp/status/929140877540278272
$(SWIFT) package clean
$(SWIFT) build
$(SWIFT) build -c release
@@ -240,10 +251,10 @@ test_performance: Realm FMDB SQLite.swift
-scheme GRDBOSXPerformanceComparisonTests \
build-for-testing test-without-building
Realm: Tests/Performance/Realm/build/osx/swift-4.0/RealmSwift.framework
Realm: Tests/Performance/Realm/build/osx/swift-4.0.3/RealmSwift.framework
# Makes sure the Tests/Performance/Realm submodule has been downloaded, and Realm framework has been built.
Tests/Performance/Realm/build/osx/swift-4.0/RealmSwift.framework:
Tests/Performance/Realm/build/osx/swift-4.0.3/RealmSwift.framework:
$(GIT) submodule update --init --recursive Tests/Performance/Realm
cd Tests/Performance/Realm && sh build.sh osx-swift
@@ -292,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.2.0 \
--module-version 2.2 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v2.7.0 \
--module-version 2.7 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/2.2/ \
--root-url http://groue.github.io/GRDB.swift/docs/2.7/ \
--output Documentation/Reference \
--podspec GRDB.swift.podspec
else
+395 -252
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**: October 31, 2017 • version 2.2.0 • [CHANGELOG](CHANGELOG.md)
**Latest release**: January 21, 2018 • version 2.7.0 • [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.2.0** |
| **Swift 4** | **v2.7.0** |
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.2/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/2.7/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
**Getting Started**
@@ -245,7 +245,7 @@ Installation
See [Encryption](#encryption) for the installation procedure of GRDB with SQLCipher.
See [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) for the installation procedure of GRDB with a customized build of SQLite 3.20.1.
See [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) for the installation procedure of GRDB with a customized build of SQLite 3.21.0.
## CocoaPods
@@ -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.2.0")
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.7.0")
]
)
```
@@ -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.2.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.2.0` command.
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.7.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.7.0` 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.2/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.7/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.2/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.7/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.2/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.7/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.2/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.7/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.2/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.7/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.2/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/2.7/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.2/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.7/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.2/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.7/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.2/Structs/Configuration.html)
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/2.2/Classes/Database.html)
- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.7/Structs/Configuration.html)
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/2.7/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.2/Classes/Statement.html)
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/2.2/Structs/Configuration.html)
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/2.2/Classes/DatabasePool.html)
- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/2.7/Classes/Statement.html)
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/2.7/Structs/Configuration.html)
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/2.7/Classes/DatabasePool.html)
Records
@@ -1839,13 +1839,13 @@ Your custom structs and classes can adopt each protocol individually, and opt in
- [Persistable Protocol](#persistable-protocol)
- [Persistence Methods](#persistence-methods)
- [Customizing the Persistence Methods](#customizing-the-persistence-methods)
- [Conflict Resolution](#conflict-resolution)
- [Codable Records](#codable-records)
- [Record Class](#record-class)
- [Changes Tracking](#changes-tracking)
- [RecordBox Class](#recordbox-class)
- [Changes Tracking](#changes-tracking)
- [Conflict Resolution](#conflict-resolution)
- [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key)
- [List of Record Methods](#list-of-record-methods)
- [The Query Interface](#the-query-interface)
### Inserting Records
@@ -1950,9 +1950,11 @@ Details follow:
- [Persistable Protocol](#persistable-protocol)
- [Codable Records](#codable-records)
- [Record Class](#record-class)
- [RecordBox Class](#recordbox-class)
- [Changes Tracking](#changes-tracking)
- [Conflict Resolution](#conflict-resolution)
- [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key)
- [List of Record Methods](#list-of-record-methods)
- [The Query Interface](#the-query-interface)
## Record Protocols Overview
@@ -2114,8 +2116,8 @@ extension Place : RowConvertible {
See [column values](#column-values) for more information about the `row[]` subscript.
> :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
**The `init(row:)` initializer can be automatically generated** when your type adopts the standard `Decodable` protocol. See [Codable Records](#codable-records) for more information.
>
> :bulb: **Tip**: the `init(row:)` initializer can be automatically generated when your type adopts the standard `Decodable` protocol. See [Codable Records](#codable-records) for more information.
RowConvertible allows adopting types to be fetched from SQL queries:
@@ -2125,7 +2127,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.2/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.7/Structs/StatementArguments.html) for more information about the query arguments.
## TableMapping Protocol
@@ -2216,7 +2218,7 @@ Yes, two protocols instead of one. Both grant exactly the same advantages. Here
The `encode(to:)` method defines which [values](#values) (Bool, Int, String, Date, Swift enums, etc.) are assigned to database columns.
**`encode(to:)` can be automatically generated** when your type adopts the standard `Encodable` protocol. See [Codable Records](#codable-records) for more information.
> :bulb: **Tip**: `encode(to:)` can be automatically generated when your type adopts the standard `Encodable` protocol. See [Codable Records](#codable-records) for more information.
The optional `didInsert` method lets the adopting type store its rowID after successful insertion. If your table has an INTEGER PRIMARY KEY column, you are likely to define this method. Otherwise, you can safely ignore it. It is called from a protected dispatch queue, and serialized with all database updates.
@@ -2279,7 +2281,7 @@ try place.save(db) // Inserts or updates
try place.insert(db) // INSERT
try place.update(db) // UPDATE
try place.update(db, columns: ...) // UPDATE
try place.updateChanges(db) // Available for the Record class only
try place.updateChanges(db) // Available on Record and RecordBox only
try place.delete(db) // DELETE
place.exists(db)
@@ -2356,7 +2358,239 @@ struct Link : Persistable {
> :point_up: **Note**: it is recommended that you do not implement your own version of the `save` method. Its default implementation forwards the job to `update` or `insert`: these are the methods that may need customization, not `save`.
### Conflict Resolution
## Codable Records
[Swift Archival & Serialization](https://github.com/apple/swift-evolution/blob/master/proposals/0166-swift-archival-serialization.md) was introduced with Swift 4.
GRDB provides default implementations for [`RowConvertible.init(row:)`](#rowconvertible-protocol) and [`Persistable.encode(to:)`](#persistable-protocol) for record types that also adopt an archival protocol (`Codable`, `Encodable` or `Decodable`). When all their properties are themselves codable, Swift generates the archiving methods, and you don't need to write them down:
```swift
// Declare a plain Codable struct or class...
struct Player: Codable {
let name: String
let score: Int
}
// Adopt Record protocols...
extension Player: RowConvertible, Persistable {
static let databaseTableName = "players"
}
// ...and you can save and fetch players:
try dbQueue.inDatabase { db in
try Player(name: "Arthur", score: 100).insert(db)
let players = try Player.fetchAll(db)
}
```
GRDB support for Codable only works for "flat" records, whose stored properties are all simple [values](#values) (Bool, Int, String, Date, Swift enums, etc.) For example, the following record is not flat:
```swift
// Can't take profit from Codable code generation:
struct Place: RowConvertible, Persistable, Codable {
static let databaseTableName = "places"
var title: String
var coordinate: CLLocationCoordinate2D // <- Not a simple value!
}
```
Make it flat, as below, and you'll be granted with all Codable and GRDB advantages:
```swift
struct Place: Codable {
// Stored properties are plain values:
var title: String
var latitude: CLLocationDegrees
var longitude: CLLocationDegrees
// Complex property is computed:
var coordinate: CLLocationCoordinate2D {
get {
return CLLocationCoordinate2D(
latitude: latitude,
longitude: longitude)
}
set {
latitude = newValue.latitude
longitude = newValue.longitude
}
}
}
// Free database support!
extension Place: RowConvertible, Persistable {
static let databaseTableName = "places"
}
```
As documented with the [Persistable](#persistable-protocol) protocol, have your struct records use MutablePersistable instead of Persistable when they store their automatically incremented row id:
```swift
struct Place: Codable {
var id: Int64? // <- the row id
var title: String
var latitude: CLLocationDegrees
var longitude: CLLocationDegrees
var coordinate: CLLocationCoordinate2D { ... }
}
extension Place: RowConvertible, MutablePersistable {
static let databaseTableName = "places"
mutating func didInsert(with rowID: Int64, for column: String?) {
// Update id after insertion
id = rowID
}
}
var place = Place(id: nil, ...)
try place.insert(db)
place.id // A unique id
```
> :point_up: **Note**: Some values have a different way to encode and decode themselves in a standard archive vs. the database. For example, [Date](#date-and-datecomponents) saves itself as a numerical timestamp (archive) or a string (database). When such an ambiguity happens, GRDB always favors customized database encoding and decoding.
## Record Class
**Record** is a class that is designed to be subclassed. It inherits its features from the [RowConvertible, TableMapping, and Persistable](#record-protocols-overview) protocols. On top of that, it adds [changes tracking](#changes-tracking).
Record subclasses define their custom database relationship by overriding database methods:
```swift
class Place : Record {
var id: Int64?
var title: String
var coordinate: CLLocationCoordinate2D
/// The table name
override class var databaseTableName: String {
return "places"
}
/// Initialize from a database row
required init(row: Row) {
id = row["id"]
title = row["title"]
coordinate = CLLocationCoordinate2D(
latitude: row["latitude"],
longitude: row["longitude"])
super.init(row: row)
}
/// The values persisted in the database
override func encode(to container: inout PersistenceContainer) {
container["id"] = id
container["title"] = title
container["latitude"] = coordinate.latitude
container["longitude"] = coordinate.longitude
}
/// When relevant, update record ID after a successful insertion
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
```
## RecordBox Class
**RecordBox** is a generic [Record](#record-class) subclass that wraps any other record type that adopts the [RowConvertible, TableMapping, and Persistable](#record-protocols-overview) protocols. It brings [changes tracking](#changes-tracking) to any record type.
```swift
final class RecordBox<T: RowConvertible & MutablePersistable>: Record {
var value: T
init(value: T)
required init(row: Row)
}
```
As an example, let's start from a regular `Player` record struct:
```swift
// A regular record struct
struct Player: RowConvertible, MutablePersistable, Codable {
static let databaseTableName = "players"
var id: Int64?
var name: String
var score: Int
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
```
To track changes, don't fetch raw `Player` records, but fetch `RecordBox<Player>` instead. You can then modify player attributes, and easily check if they have been changed:
```swift
try dbQueue.inDatabase { db in
// Fetch a boxed player
if let boxedPlayer = try RecordBox<Player>.fetchOne(db, key: 1) {
// boxedPlayer.value is Player
boxedPlayer.value.score = 300
if boxedPlayer.hasPersistentChangedValues {
print("player has been modified")
}
// Does nothing if player has not been modified:
try boxedPlayer.updateChanges(db)
}
}
```
See [Changes Tracking](#changes-tracking) for more information.
## Changes Tracking
**Changes tracking is the ability, for a record, to know if it has been modified since it was last fetched or persisted.**
> :point_up: **Note**: changes tracking is available on the [Record](#record-class) class, its subclasses, and the [RecordBox](#recordbox-class) class that can wrap any other record type.
The `update()` [method](#persistence-methods) always executes an UPDATE statement. When the record has not been edited, this costly database access is generally useless.
Avoid it with the `hasPersistentChangedValues` property, which returns whether the record has changes that have not been saved:
```swift
// Insert or update the player if it has unsaved changes
if player.hasPersistentChangedValues {
try player.save(db)
}
```
You can also use the `updateChanges` method, which performs an update of the changed columns (and does nothing if record has no change):
```swift
// Update the unsaved player changes
try player.updateChanges(db)
```
The `hasPersistentChangedValues` flag is false after a record has been fetched or saved into the database. Subsequent modifications may set it, or not: `hasPersistentChangedValues` is based on value comparison. **Setting a property to the same value does not set the changed flag**:
```swift
let player = Player(name: "Barbara", score: 750)
player.hasPersistentChangedValues // true
try player.insert(db)
player.hasPersistentChangedValues // false
player.name = "Barbara"
player.hasPersistentChangedValues // false
player.score = 1000
player.hasPersistentChangedValues // true
player.persistentChangedValues // ["score": 750]
```
For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check [JSONSynchronization.playground](Playgrounds/JSONSynchronization.playground/Contents.swift).
## Conflict Resolution
**Insertions and updates can create conflicts**: for example, a query may attempt to insert a duplicate row that violates a unique index.
@@ -2432,178 +2666,6 @@ try player.insert(db)
> :warning: **Warning**: [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) may delete rows so that inserts and updates can succeed. Those deletions are not reported to [transaction observers](#transactionobserver-protocol) (this might change in a future release of SQLite).
## Codable Records
[Swift Archival & Serialization](https://github.com/apple/swift-evolution/blob/master/proposals/0166-swift-archival-serialization.md) was introduced with Swift 4.
GRDB provides default implementations for [`RowConvertible.init(row:)`](#rowconvertible-protocol) and [`Persistable.encode(to:)`](#persistable-protocol) for record types that also adopt an archival protocol (`Codable`, `Encodable` or `Decodable`). When all their properties are themselves codable, Swift generates the archiving methods, and you don't need to write them down:
```swift
// This is just enough...
struct Player: RowConvertible, Persistable, Codable {
static let databaseTableName = "players"
let name: String
let score: Int
}
// ... so that you can save and fetch players:
try dbQueue.inDatabase { db in
try Player(name: "Arthur", score: 100).insert(db)
let players = try Player.fetchAll(db)
}
```
GRDB support for Codable only works for "flat" records, whose stored properties are all simple [values](#values) (Bool, Int, String, Date, Swift enums, etc.) For example, the following record is not flat:
```swift
// Can't take profit from Codable code generation:
struct Place: RowConvertible, Persistable, Codable {
static let databaseTableName = "places"
var title: String
var coordinate: CLLocationCoordinate2D // <- Not a simple value
}
```
Make it flat, as below, and you'll be granted with all Codable and GRDB advantages:
```swift
struct Place: RowConvertible, Persistable, Codable {
static let databaseTableName = "places"
// Stored properties are all plain values:
var title: String
var latitude: CLLocationDegrees
var longitude: CLLocationDegrees
// Complex properties are computed properties:
var coordinate: CLLocationCoordinate2D {
get {
return CLLocationCoordinate2D(
latitude: latitude,
longitude: longitude)
}
set {
latitude = newValue.latitude
longitude = newValue.longitude
}
}
}
```
As documented with the [Persistable](#persistable-protocol) protocol, have you struct records use MutablePersistable instead of Persistable when they store their automatically incremented row id:
```swift
struct Place: RowConvertible, MutablePersistable, Codable {
static let databaseTableName = "places"
var id: Int64? // <- the row id
var title: String
var latitude: CLLocationDegrees
var longitude: CLLocationDegrees
var coordinate: CLLocationCoordinate2D { ... }
mutating func didInsert(with rowID: Int64, for column: String?) {
// Update id after insertion
id = rowID
}
}
var place = Place(id: nil, ...)
try place.insert(db)
place.id // A unique id
```
> :point_up: **Note**: Some values have a different way to encode and decode themselves in a standard archive vs. the database. For example, [Date](#date-and-datecomponents) saves itself as a numerical timestamp (archive) or a string (database). When such an ambiguity happens, GRDB always favors customized database encoding and decoding.
## Record Class
**Record** is a class that is designed to be subclassed. It inherits its features from the [RowConvertible, TableMapping, and Persistable](#record-protocols-overview) protocols. On top of that, it adds [changes tracking](#changes-tracking).
Record subclasses define their custom database relationship by overriding database methods:
```swift
class Place : Record {
var id: Int64?
var title: String
var coordinate: CLLocationCoordinate2D
/// The table name
override class var databaseTableName: String {
return "places"
}
/// Initialize from a database row
required init(row: Row) {
id = row["id"]
title = row["title"]
coordinate = CLLocationCoordinate2D(
latitude: row["latitude"],
longitude: row["longitude"])
super.init(row: row)
}
/// The values persisted in the database
override func encode(to container: inout PersistenceContainer) {
container["id"] = id
container["title"] = title
container["latitude"] = coordinate.latitude
container["longitude"] = coordinate.longitude
}
/// When relevant, update record ID after a successful insertion
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
```
### Changes Tracking
**Record instances know if they have been modified since they were last fetched.**
The `update()` [method](#persistence-methods) always executes an UPDATE statement. When the record has not been edited, this costly database access is generally useless.
Avoid it with the `hasPersistentChangedValues` property, which returns whether the record has changes that have not been saved:
```swift
// Insert or update the player if it has unsaved changes
if player.hasPersistentChangedValues {
try player.save(db)
}
```
You can also use the `updateChanges` method, which performs an update of the changed columns (and does nothing if record has no change):
```swift
// Update the unsaved player changes
try player.updateChanges(db)
```
The `hasPersistentChangedValues` flag is false after a record has been fetched or saved into the database. Subsequent modifications may set it, or not: `hasPersistentChangedValues` is based on value comparison. **Setting a property to the same value does not set the changed flag**:
```swift
let player = Player(name: "Barbara", score: 750)
player.hasPersistentChangedValues // true
try player.insert(db)
player.hasPersistentChangedValues // false
player.name = "Barbara"
player.hasPersistentChangedValues // false
player.score = 1000
player.hasPersistentChangedValues // true
player.persistentChangedValues // ["score": 750]
```
For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check [JSONSynchronization.playground](Playgrounds/JSONSynchronization.playground/Contents.swift).
## The Implicit RowID Primary Key
**All SQLite tables have a primary key.** Even when the primary key is not explicit:
@@ -2731,7 +2793,7 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu
## List of Record Methods
This is the list of record methods, along with their required protocols. The [Record Class](#record-class) adopts all these protocols.
This is the list of record methods, along with their required protocols. The [Record](#record-class) and [RecordBox](#recordbox-class) classes adopt all these protocols, and support [changes tracking](#changes-tracking).
| Method | Protocols | Notes |
| ------ | --------- | :---: |
@@ -2740,7 +2802,7 @@ This is the list of record methods, along with their required protocols. The [Re
| `record.save(db)` | [Persistable](#persistable-protocol) | |
| `record.update(db)` | [Persistable](#persistable-protocol) | |
| `record.update(db, columns: ...)` | [Persistable](#persistable-protocol) | |
| `record.updateChanges(db)` | [Record](#record-class) | |
| `record.updateChanges(db)` | [Record](#record-class), [RecordBox](#recordbox-class) | |
| **Delete Records** | | |
| `record.delete(db)` | [Persistable](#persistable-protocol) | |
| `Type.deleteOne(db, key: ...)` | [Persistable](#persistable-protocol) | <a href="#list-of-record-methods-1">¹</a> |
@@ -2772,9 +2834,10 @@ This is the list of record methods, along with their required protocols. The [Re
| `Type.fetchOne(db, sql)` | [RowConvertible](#rowconvertible-protocol) | <a href="#list-of-record-methods-3">³</a> |
| `Type.fetchOne(statement)` | [RowConvertible](#rowconvertible-protocol) | <a href="#list-of-record-methods-4">⁴</a> |
| `Type.filter(...).fetchOne(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | <a href="#list-of-record-methods-2">²</a> |
| **[Track Changes](#changes-tracking)** | | |
| `record.hasPersistentChangedValues` | [Record](#record-class) | |
| `record.persistentChangedValues` | [Record](#record-class) | |
| **[Changes Tracking](#changes-tracking)** | | |
| `record.hasPersistentChangedValues` | [Record](#record-class), [RecordBox](#recordbox-class) | |
| `record.persistentChangedValues` | [Record](#record-class), [RecordBox](#recordbox-class) | |
| `record.updateChanges(db)` | [Record](#record-class), [RecordBox](#recordbox-class) | |
<a name="list-of-record-methods-1">¹</a> All unique keys are supported: primary keys (single-column, composite, [implicit RowID](#the-implicit-rowid-primary-key)) and unique indexes:
@@ -3091,6 +3154,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
@@ -3181,7 +3260,7 @@ Player // SELECT * FROM players
```
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.2/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.7/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM players WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -3485,6 +3564,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
@@ -3650,9 +3767,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.2/Structs/SQLRequest.html): a Request built from raw SQL
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/2.2/Structs/AnyRequest.html): a type-erased Request
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/2.2/Structs/AnyTypedRequest.html): a type-erased TypedRequest
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.7/Structs/SQLRequest.html): a Request built from raw SQL
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/2.7/Structs/AnyRequest.html): a type-erased Request
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/2.7/Structs/AnyTypedRequest.html): a type-erased TypedRequest
Use the `asRequest(of:)` method to define the type fetched by the request:
@@ -4082,7 +4199,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.2/Structs/StatementArguments.html):
FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.7/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -4295,7 +4412,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.2/Structs/StatementArguments.html):
FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.7/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -4355,13 +4472,49 @@ try db.create(virtualTable: "books_ft", using: FTS4()) { t in // or FTS5()
}
```
The eventual content already present in the regular table is indexed, and every insert, update or delete that happens in the regular table is automatically applied to the full-text index by the mean of SQL triggers.
The eventual content already present in the regular table is indexed, and every insert, update or delete that happens in the regular table is automatically applied to the full-text index.
For more information, see the SQLite documentation about external content tables: [FTS4](https://www.sqlite.org/fts3.html#_external_content_fts4_tables_), [FTS5](https://sqlite.org/fts5.html#external_content_tables).
See also [WWDC Companion](https://github.com/groue/WWDCCompanion), a sample app that uses external content tables to store, display, and let the user search the WWDC sessions.
#### Deleting Synchronized Full-Text Tables
Synchronization of full-text tables with their content table happens by the mean of SQL triggers.
SQLite automatically deletes those triggers when the content (not full-text) table is dropped.
However, those triggers remain after the full-text table has been dropped. Unless they are dropped too, they will prevent future insertion, updates, and deletions in the content table, and the creation of a new full-text table.
To drop those triggers, use the `dropFTS4SynchronizationTriggers` or `dropFTS5SynchronizationTriggers` methods:
```swift
// Create tables
try db.create(table: "books") { t in
...
}
try db.create(virtualTable: "books_ft", using: FTS4()) { t in
t.synchronize(withTable: "books")
...
}
// Drop full-text table
try db.drop(table: "books_ft")
try db.dropFTS4SynchronizationTriggers(forTable: "books_ft")
```
> :warning: **Warning**: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers **twice**: once with the name of the deleted full-text table, and once with the name of the content table:
>
> ```swift
> // Drop full-text table
> try db.drop(table: "books_ft")
> try db.dropFTS4SynchronizationTriggers(forTable: "books_ft")
> try db.dropFTS4SynchronizationTriggers(forTable: "books") // Support for GRDB <= 2.3.1
> ```
#### Querying External Content Full-Text Tables
When you need to perform a full-text search, and the external content table contains all the data you need, you can simply query the full-text table.
@@ -4496,19 +4649,6 @@ try dbQueue.inTransaction { db in
}
```
> :point_up: **Note**: for SQLite, empty [deferred](#transaction-kinds) transactions are no transaction at all. In this case, the transaction callback is never executed:
>
> ```swift
> // Empty deferred transaction
> dbQueue.inTransaction { db in
> db.afterNextTransactionCommit { db in
> // Never executed
> print("success")
> }
> return .commit
> }
> ```
### TransactionObserver Protocol
@@ -4627,15 +4767,6 @@ do {
> :point_up: **Note**: all callbacks are called in a protected dispatch queue, and serialized with all database updates.
>
> :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument.
>
> :point_up: **Note**: for SQLite, empty [deferred](#transaction-kinds) transactions are no transaction at all. In this case, transaction observers are not notified:
>
> ```swift
> // Empty deferred transaction does not notify transaction observers
> dbQueue.inTransaction { db in
> return .commit
> }
> ```
[FetchedRecordsController](#fetchedrecordscontroller) and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) are based on the TransactionObserver protocol.
@@ -4737,16 +4868,27 @@ dbQueue.inDatabase { db in
- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed.
> :point_up: **Note**: for SQLite, empty [deferred](#transaction-kinds) transactions are no transaction at all. In this case, an observer added with the `.nextTransaction` extent is never notified of any transaction:
>
> ```swift
> // Empty deferred transaction
> dbQueue.inTransaction { db in
> // Observer is never notified of any transaction
> db.add(transactionObserver: observer, extent: .nextTransaction)
> return .commit
> }
> ```
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
@@ -5118,11 +5260,11 @@ Alternatively, perform a manual installation of GRDB and SQLCipher:
```sh
cd [GRDB directory]
git checkout v2.2.0
git checkout v2.7.0
git submodule update --init SQLCipher/src
```
2. Embed the `GRDB.xcodeproj` project in your own project.
2. Embed the `GRDBCipher.xcodeproj` project in your own project.
3. Add the `GRDBCipherOSX` or `GRDBCipheriOS` target in the **Target Dependencies** section of the **Build Phases** tab of your application target.
@@ -5225,7 +5367,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.2/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.7/Structs/StatementArguments.html) to your SQL queries:
```swift
// Good
@@ -5454,7 +5596,7 @@ See [prepared statements](#prepared-statements) and [DatabaseValue](#databaseval
**SQLite can be configured to invoke a callback function containing an error code and a terse error message whenever anomalies occur.**
It is recommended that you setup, early in the lifetime of your application, the error logging callback:
This global error callback must be configured early in the lifetime of your application:
```swift
Database.logError = { (resultCode, message) in
@@ -5462,6 +5604,8 @@ Database.logError = { (resultCode, message) in
}
```
> :warning: **Warning**: Database.logError must be set before any database connection is opened. This includes the connections that your application opens with GRDB, but also connections opened by other tools, such as third-party libraries. Setting it after a connection has been opened is an SQLite misuse, and has no effect.
See [The Error And Warning Log](https://sqlite.org/errlog.html) for more information.
@@ -5804,7 +5948,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.2/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.2/Protocols/DatabaseWriter.html) protocols.
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.7/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.7/Protocols/DatabaseWriter.html) protocols.
These protocols provide a unified API that lets you write safe concurrent code that targets both classes.
@@ -5812,7 +5956,6 @@ However, database queues are not database pools, and DatabaseReader and Database
- Pools are less forgiving than queues when one overlooks a transaction (see [concurrency rule 3](#guarantees-and-rules)).
- DatabaseWriter.readFromCurrentState is synchronous, or asynchronous, depending on whether it is run by a queue or a pool (see [advanced DatabasePool](#advanced-databasepool)). It thus requires higher libDispatch skills, and more complex synchronization code.
- The definition of "current state" in DatabaseWriter.readFromCurrentState is [delicate](http://groue.github.io/GRDB.swift/docs/2.2/Protocols/DatabaseWriter.html#/s:FP4GRDB14DatabaseWriter20readFromCurrentStateFzFCS_8DatabaseT_T_).
DatabaseReader and DatabaseWriter are not a tool for applications that hesitate between DatabaseQueue and DatabasePool, and look for a common API. As seen above, the protocols actually make applications harder to write correctly. Instead, they target generic code that has *both* queues and pools in mind. The built-in AnyDatabaseReader and AnyDatabaseWriter type erasers serve the same purpose.
@@ -5899,7 +6042,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.2/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.7/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.2.0</string>
<string>2.7.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+10 -14
View File
@@ -1,7 +1,5 @@
- [ ] We share the database cache between database pool writers and readers. But what if a writer modifies the database schema within a transaction, and a concurrent reader reads the cache? Bad things, isn't it? Write failing tests first, and fix the bug.
- [ ] Attach databases. Interesting question: what happens when one attaches a non-WAL db to a databasePool?
- [ ] SQLCipher: sqlite3_rekey is discouraged (https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320)
- [ ] What is the behavior inTransaction and inSavepoint behaviors in case of commit error? Code looks like we do not rollback, leaving the app in a weird state (out of Swift transaction block with a SQLite transaction that may still be opened).
- [ ] Query builder
- [ ] SELECT readers.*, books.* FROM ... JOIN ...
- [ ] date functions
@@ -12,16 +10,21 @@
- [ ] REGEXP https://www.sqlite.org/lang_expr.html
- [ ] CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END https://www.sqlite.org/lang_expr.html
- [ ] Write regression tests for #156 and #157
- [ ] Truncate optimization: tests for drop temp table, drop view, drop temp view
- [ ] "Documents" and "Application Support" directories: see https://github.com/ccgus/fmdb/commit/7ebbfd055c48d75dfb0119abbd9b5fc2f9001b9f#diff-2f831b88cf9e6758355acd8f88f7d996R16
GRDB 3.0
- [ ] Rename Request to DatabaseRequest, SQLiteRequest, SQLRequest, because Request is a bad name: https://github.com/swift-server/http/pull/7#issuecomment-308448528
- [ ] Make DatabasePool.write safe. See https://github.com/groue/GRDB.swift/commit/5e3c7d9c430df606a1cccfd4983be6b50e778a5c#commitcomment-26988970
- [ ] Do one of those two:
1. Make save() impossible to customize: remove it from Persistable protocol, and remove performSave() from tne public API.
2. Open Record.save(), and have RecordBox.save() forward this method to its underlying type.
- [ ] Make the MutablePersistable.update(_:columns:) method mutating (as support for an updatedDate column)
- [ ] 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.
Not sure
- [ ] Support for resource values (see https://developer.apple.com/library/ios/qa/qa1719/_index.html)
- [ ] Think about supporting Cursor's underestimatedCount, which could speed up Array(cursor) and fetchAll()
- [ ] Support for OR ROLLBACK, and mismatch between the Swift depth and the SQLite depth of nested transactions/savepoint:
@@ -63,14 +66,6 @@ Not sure
}
```
- [ ] Support for NSColor/UIColor. Beware UIColor components can go beyond [0, 1.0] in iOS10.
- [ ] Store dates as timestamp (https://twitter.com/gloparco/status/780948021613912064, https://github.com/groue/GRDB.swift/issues/97)
Require changes in the Swift language:
- [ ] Specific and optimized Optional<StatementColumnConvertible>.fetch... methods when http://openradar.appspot.com/22852669 is fixed.
Requires recompilation of SQLite:
@@ -98,3 +93,4 @@ Reading list:
- React oddity: http://stackoverflow.com/questions/41721769/realm-update-object-without-updating-lists
- File protection: https://github.com/ccgus/fmdb/issues/262
- File protection: https://lists.apple.com/archives/cocoa-dev/2012/Aug/msg00527.html
- [iOS apps are terminated every time they enter the background if they share an encrypted database with an app extension](https://github.com/sqlcipher/sqlcipher/issues/255)
@@ -7,147 +7,70 @@
objects = {
/* Begin PBXBuildFile section */
56288F841FD4256C0091310B /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56288F7D1FD424A40091310B /* GRDBCipher.framework */; };
56288F851FD4256C0091310B /* GRDBCipher.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56288F7D1FD424A40091310B /* GRDBCipher.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
56B0372B1E8E31D0003B6DA4 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0372A1E8E31D0003B6DA4 /* AppDelegate.swift */; };
56B0372D1E8E31D0003B6DA4 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0372C1E8E31D0003B6DA4 /* ViewController.swift */; };
56B037301E8E31D0003B6DA4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0372E1E8E31D0003B6DA4 /* Main.storyboard */; };
56B037321E8E31D0003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B037311E8E31D0003B6DA4 /* Assets.xcassets */; };
56B037351E8E31D0003B6DA4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B037331E8E31D0003B6DA4 /* LaunchScreen.storyboard */; };
56B0373D1E8E3219003B6DA4 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0373C1E8E3219003B6DA4 /* Database.swift */; };
56B037791E8E328C003B6DA4 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0376C1E8E3250003B6DA4 /* GRDBCipher.framework */; };
56B0377A1E8E328C003B6DA4 /* GRDBCipher.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0376C1E8E3250003B6DA4 /* GRDBCipher.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
56B0377F1E8E32B9003B6DA4 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0377E1E8E32B9003B6DA4 /* Person.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
56B037551E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
56288F761FD424A40091310B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = DC3773F319C8CBB3004FCF85;
remoteInfo = GRDBOSX;
};
56B037571E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
remoteInfo = GRDBOSXTests;
};
56B037591E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 560C981A1C0E22D300BF8471;
remoteInfo = GRDBOSXPerformanceTests;
};
56B0375B1E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56553C181C3E906C00522B5C;
remoteInfo = GRDBOSXCrashTests;
};
56B0375D1E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 560FC54D1CB003810014AA8E;
remoteInfo = GRDBCipherOSX;
};
56B0375F1E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
56288F781FD424A40091310B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 560FC5B01CB00B880014AA8E;
remoteInfo = GRDBCipherOSXTests;
};
56B037611E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
56288F7A1FD424A40091310B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 5671566C1CB16729007DC145;
remoteInfo = GRDBCipherOSXEncryptedTests;
};
56B037631E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
56288F7C1FD424A40091310B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = F3BA805A1CFB2BB2003DC1BA;
remoteInfo = GRDBCustomSQLiteOSX;
};
56B037651E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = F3BA809B1CFB2F6F003DC1BA;
remoteInfo = GRDBCustomSQLiteOSXTests;
};
56B037671E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7CA1B4D3FED00430942;
remoteInfo = GRDBiOS;
};
56B037691E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
remoteInfo = GRDBiOSTests;
};
56B0376B1E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56AFCA231CB1A8BB00F48B96;
remoteInfo = GRDBCipheriOS;
};
56B0376D1E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
56288F7E1FD424A40091310B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56AFCA7F1CB1AA9900F48B96;
remoteInfo = GRDBCipheriOSTests;
};
56B0376F1E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
56288F801FD424A40091310B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56AFCAD71CB1ABC800F48B96;
remoteInfo = GRDBCipheriOSEncryptedTests;
};
56B037711E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
56288F821FD424AD0091310B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = F3BA7FFE1CFB25E4003DC1BA;
remoteInfo = GRDBCustomSQLiteiOS;
};
56B037731E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = F3BA80411CFB2AD7003DC1BA;
remoteInfo = GRDBCustomSQLiteiOSTests;
};
56B037751E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 565490A01D5A4798005622CB;
remoteInfo = GRDBWatchOS;
};
56B037771E8E3263003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 56AFC9EE1CB1A8BB00F48B96;
remoteInfo = GRDBCipheriOS;
};
56B0377B1E8E328C003B6DA4 /* PBXContainerItemProxy */ = {
56288F861FD4256C0091310B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 56AFC9EE1CB1A8BB00F48B96;
remoteInfo = GRDBCipheriOS;
@@ -161,7 +84,7 @@
dstPath = "";
dstSubfolderSpec = 10;
files = (
56B0377A1E8E328C003B6DA4 /* GRDBCipher.framework in Embed Frameworks */,
56288F851FD4256C0091310B /* GRDBCipher.framework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
@@ -177,7 +100,7 @@
56B037341E8E31D0003B6DA4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
56B037361E8E31D0003B6DA4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
56B0373C1E8E3219003B6DA4 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDBCipher.xcodeproj; path = ../../../GRDBCipher.xcodeproj; sourceTree = "<group>"; };
56B0377E1E8E32B9003B6DA4 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
@@ -186,17 +109,30 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
56B037791E8E328C003B6DA4 /* GRDBCipher.framework in Frameworks */,
56288F841FD4256C0091310B /* GRDBCipher.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
56288F6E1FD424A40091310B /* Products */ = {
isa = PBXGroup;
children = (
56288F771FD424A40091310B /* GRDBCipher.framework */,
56288F791FD424A40091310B /* GRDBCipherOSXTests.xctest */,
56288F7B1FD424A40091310B /* GRDBCipherOSXEncryptedTests.xctest */,
56288F7D1FD424A40091310B /* GRDBCipher.framework */,
56288F7F1FD424A40091310B /* GRDBCipheriOSTests.xctest */,
56288F811FD424A40091310B /* GRDBCipheriOSEncryptedTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
56B0371E1E8E31D0003B6DA4 = {
isa = PBXGroup;
children = (
56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */,
56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */,
56B037291E8E31D0003B6DA4 /* GRDBiOS */,
56B037281E8E31D0003B6DA4 /* Products */,
);
@@ -225,30 +161,6 @@
path = GRDBiOS;
sourceTree = "<group>";
};
56B0373F1E8E3250003B6DA4 /* Products */ = {
isa = PBXGroup;
children = (
56B037561E8E3250003B6DA4 /* GRDB.framework */,
56B037581E8E3250003B6DA4 /* GRDBOSXTests.xctest */,
56B0375A1E8E3250003B6DA4 /* GRDBOSXPerformanceTests.xctest */,
56B0375C1E8E3250003B6DA4 /* GRDBOSXCrashTests.xctest */,
56B0375E1E8E3250003B6DA4 /* GRDBCipher.framework */,
56B037601E8E3250003B6DA4 /* GRDBCipherOSXTests.xctest */,
56B037621E8E3250003B6DA4 /* GRDBCipherOSXEncryptedTests.xctest */,
56B037641E8E3250003B6DA4 /* GRDBCustomSQLite.framework */,
56B037661E8E3250003B6DA4 /* GRDBCustomSQLiteOSXTests.xctest */,
56B037681E8E3250003B6DA4 /* GRDB.framework */,
56B0376A1E8E3250003B6DA4 /* GRDBiOSTests.xctest */,
56B0376C1E8E3250003B6DA4 /* GRDBCipher.framework */,
56B0376E1E8E3250003B6DA4 /* GRDBCipheriOSTests.xctest */,
56B037701E8E3250003B6DA4 /* GRDBCipheriOSEncryptedTests.xctest */,
56B037721E8E3250003B6DA4 /* GRDBCustomSQLite.framework */,
56B037741E8E3250003B6DA4 /* GRDBCustomSQLiteiOSTests.xctest */,
56B037761E8E3250003B6DA4 /* GRDB.framework */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@@ -264,8 +176,8 @@
buildRules = (
);
dependencies = (
56B037781E8E3263003B6DA4 /* PBXTargetDependency */,
56B0377C1E8E328C003B6DA4 /* PBXTargetDependency */,
56288F831FD424AD0091310B /* PBXTargetDependency */,
56288F871FD4256C0091310B /* PBXTargetDependency */,
);
name = GRDBiOS;
productName = GRDBiOS;
@@ -279,7 +191,7 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0830;
LastUpgradeCheck = 0830;
LastUpgradeCheck = 0910;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
56B037261E8E31D0003B6DA4 = {
@@ -302,8 +214,8 @@
projectDirPath = "";
projectReferences = (
{
ProductGroup = 56B0373F1E8E3250003B6DA4 /* Products */;
ProjectRef = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
ProductGroup = 56288F6E1FD424A40091310B /* Products */;
ProjectRef = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
},
);
projectRoot = "";
@@ -314,123 +226,46 @@
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
56B037561E8E3250003B6DA4 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 56B037551E8E3250003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B037581E8E3250003B6DA4 /* GRDBOSXTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXTests.xctest;
remoteRef = 56B037571E8E3250003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0375A1E8E3250003B6DA4 /* GRDBOSXPerformanceTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXPerformanceTests.xctest;
remoteRef = 56B037591E8E3250003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0375C1E8E3250003B6DA4 /* GRDBOSXCrashTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXCrashTests.xctest;
remoteRef = 56B0375B1E8E3250003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0375E1E8E3250003B6DA4 /* GRDBCipher.framework */ = {
56288F771FD424A40091310B /* GRDBCipher.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDBCipher.framework;
remoteRef = 56B0375D1E8E3250003B6DA4 /* PBXContainerItemProxy */;
remoteRef = 56288F761FD424A40091310B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B037601E8E3250003B6DA4 /* GRDBCipherOSXTests.xctest */ = {
56288F791FD424A40091310B /* GRDBCipherOSXTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBCipherOSXTests.xctest;
remoteRef = 56B0375F1E8E3250003B6DA4 /* PBXContainerItemProxy */;
remoteRef = 56288F781FD424A40091310B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B037621E8E3250003B6DA4 /* GRDBCipherOSXEncryptedTests.xctest */ = {
56288F7B1FD424A40091310B /* GRDBCipherOSXEncryptedTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBCipherOSXEncryptedTests.xctest;
remoteRef = 56B037611E8E3250003B6DA4 /* PBXContainerItemProxy */;
remoteRef = 56288F7A1FD424A40091310B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B037641E8E3250003B6DA4 /* GRDBCustomSQLite.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDBCustomSQLite.framework;
remoteRef = 56B037631E8E3250003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B037661E8E3250003B6DA4 /* GRDBCustomSQLiteOSXTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBCustomSQLiteOSXTests.xctest;
remoteRef = 56B037651E8E3250003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B037681E8E3250003B6DA4 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 56B037671E8E3250003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0376A1E8E3250003B6DA4 /* GRDBiOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBiOSTests.xctest;
remoteRef = 56B037691E8E3250003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0376C1E8E3250003B6DA4 /* GRDBCipher.framework */ = {
56288F7D1FD424A40091310B /* GRDBCipher.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDBCipher.framework;
remoteRef = 56B0376B1E8E3250003B6DA4 /* PBXContainerItemProxy */;
remoteRef = 56288F7C1FD424A40091310B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0376E1E8E3250003B6DA4 /* GRDBCipheriOSTests.xctest */ = {
56288F7F1FD424A40091310B /* GRDBCipheriOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBCipheriOSTests.xctest;
remoteRef = 56B0376D1E8E3250003B6DA4 /* PBXContainerItemProxy */;
remoteRef = 56288F7E1FD424A40091310B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B037701E8E3250003B6DA4 /* GRDBCipheriOSEncryptedTests.xctest */ = {
56288F811FD424A40091310B /* GRDBCipheriOSEncryptedTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBCipheriOSEncryptedTests.xctest;
remoteRef = 56B0376F1E8E3250003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B037721E8E3250003B6DA4 /* GRDBCustomSQLite.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDBCustomSQLite.framework;
remoteRef = 56B037711E8E3250003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B037741E8E3250003B6DA4 /* GRDBCustomSQLiteiOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBCustomSQLiteiOSTests.xctest;
remoteRef = 56B037731E8E3250003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B037761E8E3250003B6DA4 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 56B037751E8E3250003B6DA4 /* PBXContainerItemProxy */;
remoteRef = 56288F801FD424A40091310B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
@@ -463,15 +298,15 @@
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
56B037781E8E3263003B6DA4 /* PBXTargetDependency */ = {
56288F831FD424AD0091310B /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBCipheriOS;
targetProxy = 56B037771E8E3263003B6DA4 /* PBXContainerItemProxy */;
targetProxy = 56288F821FD424AD0091310B /* PBXContainerItemProxy */;
};
56B0377C1E8E328C003B6DA4 /* PBXTargetDependency */ = {
56288F871FD4256C0091310B /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBCipheriOS;
targetProxy = 56B0377B1E8E328C003B6DA4 /* PBXContainerItemProxy */;
targetProxy = 56288F861FD4256C0091310B /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
@@ -505,7 +340,9 @@
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
@@ -513,7 +350,11 @@
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
@@ -536,7 +377,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 10.3;
IPHONEOS_DEPLOYMENT_TARGET = 11.1;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
@@ -555,7 +396,9 @@
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
@@ -563,7 +406,11 @@
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
@@ -580,7 +427,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 10.3;
IPHONEOS_DEPLOYMENT_TARGET = 11.1;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
@@ -598,7 +445,7 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 3.0;
SWIFT_VERSION = 4.0;
};
name = Debug;
};
@@ -612,7 +459,7 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 3.0;
SWIFT_VERSION = 4.0;
};
name = Release;
};
@@ -635,6 +482,7 @@
56B0373B1E8E31D0003B6DA4 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0830"
LastUpgradeVersion = "0910"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -26,6 +26,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
@@ -45,6 +46,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
@@ -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
@@ -9,7 +9,41 @@ import XCTest
class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
func testDatabaseAfterNextTransactionCommit() throws {
func testTransactionCompletions() throws {
// implicit transaction
try assertTransaction(start: "", end: "CREATE TABLE t(a)", isNotifiedAs: .commit)
// explicit commit
try assertTransaction(start: "BEGIN DEFERRED TRANSACTION", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "BEGIN DEFERRED TRANSACTION; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test; ROLLBACK TRANSACTION TO SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a); ROLLBACK TRANSACTION TO SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
// explicit rollback
try assertTransaction(start: "BEGIN DEFERRED TRANSACTION", end: "ROLLBACK", isNotifiedAs: .rollback)
try assertTransaction(start: "BEGIN DEFERRED TRANSACTION; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback)
try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION", end: "ROLLBACK", isNotifiedAs: .rollback)
try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback)
try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION", end: "ROLLBACK", isNotifiedAs: .rollback)
try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback)
try assertTransaction(start: "SAVEPOINT test", end: "ROLLBACK", isNotifiedAs: .rollback)
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback)
}
func assertTransaction(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws {
try assertTransaction_registerBefore(start: startSQL, end: endSQL, isNotifiedAs: expectedCompletion)
try assertTransaction_registerBetween(start: startSQL, end: endSQL, isNotifiedAs: expectedCompletion)
}
func assertTransaction_registerBefore(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws {
class Witness { }
let dbQueue = try makeDatabaseQueue()
@@ -26,29 +60,39 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
}
}
XCTAssertNotNil(deallocationWitness)
XCTAssertEqual(transactionCount, 0)
try db.inTransaction {
try db.execute("CREATE TABLE t(a)")
return .commit
try db.execute(startSQL)
try db.execute(endSQL)
switch expectedCompletion {
case .commit:
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
case .rollback:
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
}
XCTAssertEqual(transactionCount, 1)
XCTAssertNil(deallocationWitness)
try db.inTransaction {
try db.execute("DROP TABLE t")
try db.execute("DROP TABLE IF EXISTS t; CREATE TABLE t(a); ")
return .commit
}
XCTAssertEqual(transactionCount, 1)
switch expectedCompletion {
case .commit:
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
case .rollback:
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
}
}
}
func testDatabaseAfterNextTransactionWithEmptyDeferredTransaction() throws {
func assertTransaction_registerBetween(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws {
class Witness { }
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var transactionCount = 0
try db.execute(startSQL)
weak var deallocationWitness: Witness? = nil
do {
let witness = Witness()
@@ -60,51 +104,27 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
}
}
XCTAssertNotNil(deallocationWitness)
XCTAssertEqual(transactionCount, 0)
try db.inTransaction(.deferred) { .commit }
XCTAssertEqual(transactionCount, 0)
try db.execute(endSQL)
switch expectedCompletion {
case .commit:
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
case .rollback:
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
}
XCTAssertNil(deallocationWitness)
try db.inTransaction {
try db.execute("CREATE TABLE t(a)")
try db.execute("DROP TABLE IF EXISTS t; CREATE TABLE t(a); ")
return .commit
}
XCTAssertEqual(transactionCount, 0)
}
}
func testDatabaseAfterNextTransactionCommitWithRollback() throws {
class Witness { }
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var transactionCount = 0
weak var deallocationWitness: Witness? = nil
do {
let witness = Witness()
deallocationWitness = witness
db.afterNextTransactionCommit { _ in
// use witness
withExtendedLifetime(witness, { })
transactionCount += 1
}
switch expectedCompletion {
case .commit:
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
case .rollback:
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
}
XCTAssertEqual(transactionCount, 0)
try db.inTransaction {
try db.execute("CREATE TABLE t(a)")
return .rollback
}
XCTAssertEqual(transactionCount, 0)
XCTAssertNil(deallocationWitness)
try db.inTransaction {
try db.execute("CREATE TABLE t(a)")
return .commit
}
XCTAssertEqual(transactionCount, 0)
}
}
}
@@ -10,23 +10,11 @@ import XCTest
class DatabaseLogErrorTests: GRDBTestCase {
func testErrorLog() throws {
// Remember current log function
let currentLogError = Database.logError
var lastResultCode: ResultCode? = nil
var lastMessage: String? = nil
Database.logError = { (resultCode, message) in
lastResultCode = resultCode
lastMessage = message
}
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
_ = try? db.execute("That's not SQL.")
}
XCTAssertEqual(lastResultCode!, ResultCode.SQLITE_ERROR)
XCTAssertEqual(lastMessage!, "near \"That\": syntax error")
// Restore current log function
Database.logError = currentLogError
}
}
@@ -33,28 +33,9 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
try dbPool.read { db in
// Warm cache in a reader
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.rowIDColumn, "id")
let columns = try db.columns(in: "items")
XCTAssertEqual(columns.count, 4)
XCTAssertEqual(columns[0].name, "id")
XCTAssertEqual(columns[1].name, "email")
XCTAssertEqual(columns[2].name, "foo")
XCTAssertEqual(columns[3].name, "bar")
let indexes = try db.indexes(on: "items")
XCTAssertEqual(indexes.count, 2)
for index in indexes {
switch index.name {
case "foobar":
XCTAssertEqual(index.columns, ["foo", "bar"])
XCTAssertFalse(index.isUnique)
default:
XCTAssertEqual(index.columns, ["email"])
XCTAssertTrue(index.isUnique)
}
}
_ = try db.primaryKey("items")
_ = try db.columns(in: "items")
_ = try db.indexes(on: "items")
// Assert that reader cache is warmed
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
@@ -62,7 +43,12 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil)
}
dbPool.write { db in
try dbPool.write { db in
// Warm cache in the writer
_ = try db.primaryKey("items")
_ = try db.columns(in: "items")
_ = try db.indexes(on: "items")
// Assert that writer cache is warmed
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
XCTAssertTrue(db.schemaCache.columns(in: "items") != nil)
@@ -137,4 +123,95 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
blocks[index]()
}
}
func testCacheSnapshotIsolation() throws {
// This test checks that the schema cache follows snapshot isolation.
// and that writer and readers do not naively share the same cache.
dbConfiguration.trace = { print($0) }
let dbPool = try makeDatabasePool()
// writer reader
// CREATE TABLE foo
// table exists: true
// >
let s1 = DispatchSemaphore(value: 0)
// table exists: true
// <
let s2 = DispatchSemaphore(value: 0)
// DROP TABLE foo
// table exists: false
// >
let s3 = DispatchSemaphore(value: 0)
// table exists: true
// <
let s4 = DispatchSemaphore(value: 0)
// table exists: false
let block1 = { () in
try! dbPool.write { db in
try db.execute("CREATE TABLE foo(id INTEGER PRIMARY KEY)")
// warm cache
_ = try db.primaryKey("foo")
// cache contains the primary key
XCTAssertNotNil(db.schemaCache.primaryKey("foo"))
s1.signal()
_ = s2.wait(timeout: .distantFuture)
try db.execute("DROP TABLE foo")
// cache does not contain the primary key
XCTAssertNil(db.schemaCache.primaryKey("foo"))
s3.signal()
_ = s4.wait(timeout: .distantFuture)
// cache does not contain the primary key
XCTAssertNil(db.schemaCache.primaryKey("foo"))
}
}
let block2 = { () in
_ = s1.wait(timeout: .distantFuture)
try! dbPool.read { db in
// activate snapshot isolation so that foo table is visible during the whole read. Any read is enough.
try db.makeSelectStatement("SELECT * FROM sqlite_master").cursor().next()
// warm cache
_ = try db.primaryKey("foo")
// cache contains the primary key
XCTAssertNotNil(db.schemaCache.primaryKey("foo"))
s2.signal()
_ = s3.wait(timeout: .distantFuture)
// cache contains the primary key
XCTAssertNotNil(db.schemaCache.primaryKey("foo"))
// warm cache if needed
_ = try db.primaryKey("foo")
s4.signal()
}
}
let blocks = [block1, block2]
DispatchQueue.concurrentPerform(iterations: blocks.count) { index in
blocks[index]()
}
}
func testUnsafeReaderHasNoDatabaseCache() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, email TEXT UNIQUE, foo INT, bar DOUBLE)")
try db.execute("CREATE INDEX foobar ON items(foo, bar)")
}
try dbPool.unsafeRead { db in
// Assert that a cache is empty
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache.columns(in: "items") == nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil)
// Warm cache in a reader
_ = try db.primaryKey("items")
_ = try db.columns(in: "items")
_ = try db.indexes(on: "items")
// Assert that a reader cache is still empty
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache.columns(in: "items") == nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil)
}
}
}
@@ -39,7 +39,7 @@ class ConcurrencyTests: GRDBTestCase {
}
func testDeferredTransactionConcurrency() throws {
let dbQueue1 = try makeDatabaseQueue()
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
#if GRDBCIPHER_USE_ENCRYPTION
// Work around SQLCipher bug when two connections are open to the
// same empty database: make sure the database is not empty before
@@ -48,7 +48,7 @@ class ConcurrencyTests: GRDBTestCase {
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
let dbQueue2 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
// Queue 1 Queue 2
// BEGIN DEFERRED TRANSACTION
@@ -118,8 +118,8 @@ class ConcurrencyTests: GRDBTestCase {
}
func testExclusiveTransactionConcurrency() throws {
let dbQueue1 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue()
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
// Queue 1 Queue 2
// BEGIN EXCLUSIVE TRANSACTION
@@ -174,8 +174,8 @@ class ConcurrencyTests: GRDBTestCase {
}
func testImmediateTransactionConcurrency() throws {
let dbQueue1 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue()
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
// Queue 1 Queue 2
// BEGIN IMMEDIATE TRANSACTION
@@ -230,7 +230,7 @@ class ConcurrencyTests: GRDBTestCase {
}
func testBusyCallback() throws {
let dbQueue1 = try makeDatabaseQueue()
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
#if GRDBCIPHER_USE_ENCRYPTION
// Work around SQLCipher bug when two connections are open to the
// same empty database: make sure the database is not empty before
@@ -239,7 +239,7 @@ class ConcurrencyTests: GRDBTestCase {
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
let dbQueue2 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
// Queue 1 Queue 2
// BEGIN EXCLUSIVE TRANSACTION
@@ -293,7 +293,7 @@ class ConcurrencyTests: GRDBTestCase {
}
func testReaderDuringDefaultTransaction() throws {
let dbQueue1 = try makeDatabaseQueue()
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
#if GRDBCIPHER_USE_ENCRYPTION
// Work around SQLCipher bug when two connections are open to the
// same empty database: make sure the database is not empty before
@@ -302,7 +302,7 @@ class ConcurrencyTests: GRDBTestCase {
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
let dbQueue2 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
// Here we test that a reader can read while a writer is writing.
@@ -359,7 +359,7 @@ class ConcurrencyTests: GRDBTestCase {
}
func testReaderInDeferredTransactionDuringDefaultTransaction() throws {
let dbQueue1 = try makeDatabaseQueue()
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
#if GRDBCIPHER_USE_ENCRYPTION
// Work around SQLCipher bug when two connections are open to the
// same empty database: make sure the database is not empty before
@@ -368,7 +368,7 @@ class ConcurrencyTests: GRDBTestCase {
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
let dbQueue2 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
// The `SELECT * FROM stuffs` statement of Queue 2 prevents Queue 1
// from committing with SQLITE_BUSY.
@@ -12,12 +12,12 @@ class DatabaseQueueReadOnlyTests : GRDBTestCase {
func testReadOnlyDatabaseCanNotBeModified() throws {
// Create database
do {
_ = try makeDatabaseQueue()
_ = try makeDatabaseQueue(filename: "test.sqlite")
}
// Open it again, readonly
dbConfiguration.readonly = true
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
let statement = try dbQueue.inDatabase { db in
try db.makeUpdateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
+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) {
}
+31 -31
View File
@@ -7,7 +7,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabaseQueueWithPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -16,7 +16,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM data")!, 1)
}
@@ -26,7 +26,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabaseQueueWithoutPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -36,7 +36,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = nil
do {
_ = try makeDatabaseQueue()
_ = try makeDatabaseQueue(filename: "test.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
@@ -49,7 +49,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabaseQueueWithWrongPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -59,7 +59,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "wrong"
do {
_ = try makeDatabaseQueue()
_ = try makeDatabaseQueue(filename: "test.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
@@ -72,7 +72,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabaseQueueWithNewPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -81,7 +81,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.change(passphrase: "newSecret")
try dbQueue.inDatabase { db in
try db.execute("INSERT INTO data (value) VALUES (2)")
@@ -93,7 +93,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "newSecret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM data")!, 2)
}
@@ -103,7 +103,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabasePoolWithPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -112,7 +112,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM data")!, 1)
}
@@ -122,7 +122,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabasePoolWithoutPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -132,7 +132,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = nil
do {
_ = try makeDatabasePool()
_ = try makeDatabasePool(filename: "test.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
@@ -145,7 +145,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabasePoolWithWrongPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -155,7 +155,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "wrong"
do {
_ = try makeDatabasePool()
_ = try makeDatabasePool(filename: "test.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
@@ -168,7 +168,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabasePoolWithNewPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -177,7 +177,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.change(passphrase: "newSecret")
try dbPool.write { db in
try db.execute("INSERT INTO data (value) VALUES (2)")
@@ -187,7 +187,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "newSecret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM data")!, 2)
}
@@ -197,7 +197,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabasePoolWithPassphraseToDatabasePoolWithPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.write { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -206,7 +206,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM data")!, 1)
}
@@ -216,7 +216,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabasePoolWithPassphraseToDatabasePoolWithoutPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.write { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -226,7 +226,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = nil
do {
_ = try makeDatabasePool()
_ = try makeDatabasePool(filename: "test.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
@@ -239,7 +239,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabasePoolWithPassphraseToDatabasePoolWithWrongPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.write { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -249,7 +249,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "wrong"
do {
_ = try makeDatabasePool()
_ = try makeDatabasePool(filename: "test.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
@@ -263,7 +263,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.write { db in
try db.execute("CREATE TABLE data (value INTEGER)")
try db.execute("INSERT INTO data (value) VALUES (1)")
@@ -272,7 +272,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.change(passphrase: "newSecret")
try dbPool.write { db in
try db.execute("INSERT INTO data (value) VALUES (2)")
@@ -282,7 +282,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "newSecret"
let dbPool = try makeDatabasePool()
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM data")!, 2)
}
@@ -292,7 +292,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPragmaPassphraseToDatabaseQueueWithPassphrase() throws {
do {
dbConfiguration.passphrase = nil
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("PRAGMA key = 'secret'")
try db.execute("CREATE TABLE data (value INTEGER)")
@@ -302,7 +302,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM data")!, 1)
}
@@ -312,7 +312,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPragmaPassphraseToDatabaseQueueWithoutPassphrase() throws {
do {
dbConfiguration.passphrase = nil
let dbQueue = try makeDatabaseQueue()
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
try db.execute("PRAGMA key = 'secret'")
try db.execute("CREATE TABLE data (value INTEGER)")
@@ -323,7 +323,7 @@ class EncryptionTests: GRDBTestCase {
do {
dbConfiguration.passphrase = nil
do {
_ = try makeDatabaseQueue()
_ = try makeDatabaseQueue(filename: "test.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
@@ -229,4 +229,63 @@ class FTS4TableBuilderTests: GRDBTestCase {
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["bar"])!, 1)
}
}
func testFTS4SynchronizationCleanup() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "documents") { t in
t.column("id", .integer).primaryKey()
t.column("content", .text)
}
try db.execute("INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
try db.create(virtualTable: "ft_documents", using: FTS4()) { t in
t.synchronize(withTable: "documents")
t.column("content")
}
try db.drop(table: "ft_documents")
try db.dropFTS4SynchronizationTriggers(forTable: "ft_documents")
// It is possible to modify the content table
try db.execute("UPDATE documents SET content = ?", arguments: ["bar"])
try db.execute("INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
try db.execute("DELETE FROM documents WHERE content = ?", arguments: ["foo"])
// It is possible to recreate the FT table
try db.create(virtualTable: "ft_documents", using: FTS4()) { t in
t.synchronize(withTable: "documents")
t.column("content")
}
}
}
func testFTS4SynchronizationCleanupWithLegacySupport() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "documents") { t in
t.column("id", .integer).primaryKey()
t.column("content", .text)
}
try db.execute("INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
try db.create(virtualTable: "ft_documents", using: FTS4()) { t in
t.synchronize(withTable: "documents")
t.column("content")
}
try db.drop(table: "ft_documents")
try db.dropFTS4SynchronizationTriggers(forTable: "documents") // legacy GRDB <= 2.3.1
try db.dropFTS4SynchronizationTriggers(forTable: "ft_documents")
// It is possible to modify the content table
try db.execute("UPDATE documents SET content = ?", arguments: ["bar"])
try db.execute("INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
try db.execute("DELETE FROM documents WHERE content = ?", arguments: ["foo"])
// It is possible to recreate the FT table
try db.create(virtualTable: "ft_documents", using: FTS4()) { t in
t.synchronize(withTable: "documents")
t.column("content")
}
}
}
}
+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")
+60 -1
View File
@@ -128,7 +128,7 @@ class FTS5TableBuilderTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS5()) { t in
t.tokenizer = .unicode61(tokenCharacters: Set(".-".characters))
t.tokenizer = .unicode61(tokenCharacters: Set(".-"))
t.column("content")
}
assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts5(content, tokenize='unicode61 tokenchars ''-.''')")
@@ -219,5 +219,64 @@ class FTS5TableBuilderTests: GRDBTestCase {
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["bar"])!, 1)
}
}
func testFTS5SynchronizationCleanup() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "documents") { t in
t.column("id", .integer).primaryKey()
t.column("content", .text)
}
try db.execute("INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
try db.create(virtualTable: "ft_documents", using: FTS5()) { t in
t.synchronize(withTable: "documents")
t.column("content")
}
try db.drop(table: "ft_documents")
try db.dropFTS5SynchronizationTriggers(forTable: "ft_documents")
// It is possible to modify the content table
try db.execute("UPDATE documents SET content = ?", arguments: ["bar"])
try db.execute("INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
try db.execute("DELETE FROM documents WHERE content = ?", arguments: ["foo"])
// It is possible to recreate the FT table
try db.create(virtualTable: "ft_documents", using: FTS5()) { t in
t.synchronize(withTable: "documents")
t.column("content")
}
}
}
func testFTS5SynchronizationCleanupWithLegacySupport() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "documents") { t in
t.column("id", .integer).primaryKey()
t.column("content", .text)
}
try db.execute("INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
try db.create(virtualTable: "ft_documents", using: FTS5()) { t in
t.synchronize(withTable: "documents")
t.column("content")
}
try db.drop(table: "ft_documents")
try db.dropFTS5SynchronizationTriggers(forTable: "documents") // legacy GRDB <= 2.3.1
try db.dropFTS5SynchronizationTriggers(forTable: "ft_documents")
// It is possible to modify the content table
try db.execute("UPDATE documents SET content = ?", arguments: ["bar"])
try db.execute("INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
try db.execute("DELETE FROM documents WHERE content = ?", arguments: ["foo"])
// It is possible to recreate the FT table
try db.create(virtualTable: "ft_documents", using: FTS5()) { t in
t.synchronize(withTable: "documents")
t.column("content")
}
}
}
}
#endif
+1 -1
View File
@@ -169,7 +169,7 @@ class FTS5TokenizerTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS5()) { t in
t.tokenizer = .unicode61(tokenCharacters: Set(".-".characters))
t.tokenizer = .unicode61(tokenCharacters: Set(".-"))
t.column("content")
}
@@ -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)
}
}
+14 -4
View File
@@ -12,23 +12,27 @@ import XCTest
@testable import GRDB // @testable so that we have access to SQLiteConnectionWillClose
#endif
// Support for Database.logError
var lastResultCode: ResultCode? = nil
var lastMessage: String? = nil
class GRDBTestCase: XCTestCase {
// The default configuration for tests
var dbConfiguration: Configuration!
// Builds a database queue based on dbConfiguration
func makeDatabaseQueue(filename: String = "db.sqlite") throws -> DatabaseQueue {
func makeDatabaseQueue(filename: String? = nil) throws -> DatabaseQueue {
try FileManager.default.createDirectory(atPath: dbDirectoryPath, withIntermediateDirectories: true, attributes: nil)
let dbPath = (dbDirectoryPath as NSString).appendingPathComponent(filename)
let dbPath = (dbDirectoryPath as NSString).appendingPathComponent(filename ?? ProcessInfo.processInfo.globallyUniqueString)
let dbQueue = try DatabaseQueue(path: dbPath, configuration: dbConfiguration)
try setup(dbQueue)
return dbQueue
}
// Builds a database pool based on dbConfiguration
func makeDatabasePool(filename: String = "db.sqlite") throws -> DatabasePool {
func makeDatabasePool(filename: String? = nil) throws -> DatabasePool {
try FileManager.default.createDirectory(atPath: dbDirectoryPath, withIntermediateDirectories: true, attributes: nil)
let dbPath = (dbDirectoryPath as NSString).appendingPathComponent(filename)
let dbPath = (dbDirectoryPath as NSString).appendingPathComponent(filename ?? ProcessInfo.processInfo.globallyUniqueString)
let dbPool = try DatabasePool(path: dbPath, configuration: dbConfiguration)
try setup(dbPool)
return dbPool
@@ -53,6 +57,12 @@ class GRDBTestCase: XCTestCase {
override func setUp() {
super.setUp()
// Must be set prior to any databaase connection
Database.logError = { (resultCode, message) in
lastResultCode = resultCode
lastMessage = message
}
let dbPoolDirectoryName = "GRDBTestCase-\(ProcessInfo.processInfo.globallyUniqueString)"
dbDirectoryPath = (NSTemporaryDirectory() as NSString).appendingPathComponent(dbPoolDirectoryName)
do { try FileManager.default.removeItem(atPath: dbDirectoryPath) } catch { }
@@ -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()
+480
View File
@@ -0,0 +1,480 @@
import XCTest
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private struct Player: RowConvertible, MutablePersistable, Codable {
static let databaseTableName = "players"
var id: Int64?
var name: String?
var score: Int?
var creationDate: Date?
init(id: Int64? = nil, name: String? = nil, score: Int? = nil, creationDate: Date? = nil) {
self.id = id
self.name = name
self.score = score
self.creationDate = creationDate
}
mutating func insert(_ db: Database) throws {
if creationDate == nil {
creationDate = Date()
}
try performInsert(db)
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
class RecordBoxTests: GRDBTestCase {
override func setup(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(table: "players") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text)
t.column("score", .integer)
t.column("creationDate", .datetime)
}
}
}
func testRecordIsEditedAfterInit() {
// Create a Record. No fetch has happen, so we don't know if it is
// identical to its eventual row in the database. So it is edited.
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
XCTAssertTrue(player.hasPersistentChangedValues)
}
func testRecordIsEditedAfterInitFromRow() {
// Create a Record from a row. The row may not come from the database.
// So it is edited.
let row = Row(["name": "Arthur", "score": 41])
let player = RecordBox<Player>(row: row)
XCTAssertTrue(player.hasPersistentChangedValues)
}
func testRecordIsNotEditedAfterFullFetch() throws {
// Fetch a record from a row that contains all the columns in
// persistence container: An update statement, which only saves the
// columns in persistence container would perform no change. So the
// record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try RecordBox<Player>(value: Player(name: "Arthur", score: 41)).insert(db)
let player = try RecordBox<Player>.fetchOne(db, "SELECT * FROM players")!
XCTAssertFalse(player.hasPersistentChangedValues)
}
}
func testRecordIsNotEditedAfterWiderThanFullFetch() throws {
// Fetch a record from a row that contains all the columns in
// persistence container, plus extra ones: An update statement,
// which only saves the columns in persistence container would
// perform no change. So the record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try RecordBox<Player>(value: Player(name: "Arthur", score: 41)).insert(db)
let player = try RecordBox<Player>.fetchOne(db, "SELECT *, 1 AS foo FROM players")!
XCTAssertFalse(player.hasPersistentChangedValues)
}
}
func testRecordIsEditedAfterPartialFetch() throws {
// Fetch a record from a row that does not contain all the columns in
// persistence container: An update statement saves the columns in
// persistence container, so it may perform unpredictable change.
// So the record is edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try RecordBox<Player>(value: Player(name: "Arthur", score: 41)).insert(db)
let player = try RecordBox<Player>.fetchOne(db, "SELECT name FROM players")!
XCTAssertTrue(player.hasPersistentChangedValues)
}
}
func testRecordIsNotEditedAfterInsert() throws {
// After insertion, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
XCTAssertFalse(player.hasPersistentChangedValues)
}
}
func testRecordIsEditedAfterValueChange() throws {
// Any change in a value exposed in persistence container yields a
// record that is edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
let player = RecordBox<Player>(value: Player(name: "Arthur"))
try player.insert(db)
XCTAssertTrue(player.value.name != nil)
player.value.name = "Bobby" // non-nil vs. non-nil
XCTAssertTrue(player.hasPersistentChangedValues)
}
do {
let player = RecordBox<Player>(value: Player(name: "Arthur"))
try player.insert(db)
XCTAssertTrue(player.value.name != nil)
player.value.name = nil // non-nil vs. nil
XCTAssertTrue(player.hasPersistentChangedValues)
}
do {
let player = RecordBox<Player>(value: Player(name: "Arthur"))
try player.insert(db)
XCTAssertTrue(player.value.score == nil)
player.value.score = 41 // nil vs. non-nil
XCTAssertTrue(player.hasPersistentChangedValues)
}
}
}
func testRecordIsNotEditedAfterSameValueChange() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
let player = RecordBox<Player>(value: Player(name: "Arthur"))
try player.insert(db)
XCTAssertTrue(player.value.name != nil)
player.value.name = "Arthur" // non-nil vs. non-nil
XCTAssertFalse(player.hasPersistentChangedValues)
}
do {
let player = RecordBox<Player>(value: Player(name: "Arthur"))
try player.insert(db)
XCTAssertTrue(player.value.score == nil)
player.value.score = nil // nil vs. nil
XCTAssertFalse(player.hasPersistentChangedValues)
}
}
}
func testRecordIsNotEditedAfterUpdate() throws {
// After update, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
player.value.name = "Bobby"
try player.update(db)
XCTAssertFalse(player.hasPersistentChangedValues)
}
}
func testRecordIsNotEditedAfterSave() throws {
// After save, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.save(db)
XCTAssertFalse(player.hasPersistentChangedValues)
player.value.name = "Bobby"
XCTAssertTrue(player.hasPersistentChangedValues)
try player.save(db)
XCTAssertFalse(player.hasPersistentChangedValues)
}
}
func testRecordIsEditedAfterPrimaryKeyChange() throws {
// After reload, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
player.value.id = player.value.id! + 1
XCTAssertTrue(player.hasPersistentChangedValues)
}
}
func testCopyTransfersEditedFlag() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
XCTAssertFalse(player.hasPersistentChangedValues)
XCTAssertFalse(player.copy().hasPersistentChangedValues)
player.value.name = "Barbara"
XCTAssertTrue(player.hasPersistentChangedValues)
XCTAssertTrue(player.copy().hasPersistentChangedValues)
player.hasPersistentChangedValues = false
XCTAssertFalse(player.hasPersistentChangedValues)
XCTAssertFalse(player.copy().hasPersistentChangedValues)
player.hasPersistentChangedValues = true
XCTAssertTrue(player.hasPersistentChangedValues)
XCTAssertTrue(player.copy().hasPersistentChangedValues)
}
}
func testChangesAfterInit() {
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
let changes = player.persistentChangedValues
XCTAssertEqual(changes.count, 4)
for (column, old) in changes {
switch column {
case "id":
XCTAssertTrue(old == nil)
case "name":
XCTAssertTrue(old == nil)
case "score":
XCTAssertTrue(old == nil)
case "creationDate":
XCTAssertTrue(old == nil)
default:
XCTFail("Unexpected column: \(column)")
}
}
}
func testChangesAfterInitFromRow() {
let player = RecordBox<Player>(row: Row(["name": "Arthur", "score": 41]))
let changes = player.persistentChangedValues
XCTAssertEqual(changes.count, 4)
for (column, old) in changes {
switch column {
case "id":
XCTAssertTrue(old == nil)
case "name":
XCTAssertTrue(old == nil)
case "score":
XCTAssertTrue(old == nil)
case "creationDate":
XCTAssertTrue(old == nil)
default:
XCTFail("Unexpected column: \(column)")
}
}
}
func testChangesAfterFullFetch() throws {
// Fetch a record from a row that contains all the columns in
// persistence container: An update statement, which only saves the
// columns in persistence container would perform no change. So the
// record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try RecordBox<Player>(value: Player(name: "Arthur", score: 41)).insert(db)
do {
let player = try RecordBox<Player>.fetchOne(db, "SELECT * FROM players")!
let changes = player.persistentChangedValues
XCTAssertEqual(changes.count, 0)
}
do {
let players = try RecordBox<Player>.fetchAll(db, "SELECT * FROM players")
let changes = players[0].persistentChangedValues
XCTAssertEqual(changes.count, 0)
}
do {
let players = try RecordBox<Player>.fetchCursor(db, "SELECT * FROM players")
let changes = try players.next()!.persistentChangedValues
XCTAssertEqual(changes.count, 0)
}
do {
let player = try RecordBox<Player>.fetchOne(db, "SELECT * FROM players", adapter: SuffixRowAdapter(fromIndex: 0))!
let changes = player.persistentChangedValues
XCTAssertEqual(changes.count, 0)
}
}
}
func testChangesAfterPartialFetch() throws {
// Fetch a record from a row that does not contain all the columns in
// persistence container: An update statement saves the columns in
// persistence container, so it may perform unpredictable change.
// So the record is edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try RecordBox<Player>(value: Player(name: "Arthur", score: 41)).insert(db)
let player = try RecordBox<Player>.fetchOne(db, "SELECT name FROM players")!
let changes = player.persistentChangedValues
XCTAssertEqual(changes.count, 3)
for (column, old) in changes {
switch column {
case "id":
XCTAssertTrue(old == nil)
case "score":
XCTAssertTrue(old == nil)
case "creationDate":
XCTAssertTrue(old == nil)
default:
XCTFail("Unexpected column: \(column)")
}
}
}
}
func testChangesAfterInsert() throws {
// After insertion, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
let changes = player.persistentChangedValues
XCTAssertEqual(changes.count, 0)
}
}
func testChangesAfterValueChange() throws {
// Any change in a value exposed in persistence container yields a
// record that is edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur"))
try player.insert(db)
player.value.name = "Bobby" // non-nil -> non-nil
player.value.score = 41 // nil -> non-nil
player.value.creationDate = nil // non-nil -> nil
let changes = player.persistentChangedValues
XCTAssertEqual(changes.count, 3)
for (column, old) in changes {
switch column {
case "name":
XCTAssertEqual(old, "Arthur".databaseValue)
case "score":
XCTAssertEqual(old, DatabaseValue.null)
case "creationDate":
XCTAssertTrue(Date.fromDatabaseValue(old!) != nil)
default:
XCTFail("Unexpected column: \(column)")
}
}
}
}
func testChangesAfterUpdate() throws {
// After update, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
player.value.name = "Bobby"
try player.update(db)
XCTAssertEqual(player.persistentChangedValues.count, 0)
}
}
func testChangesAfterSave() throws {
// After save, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.save(db)
XCTAssertEqual(player.persistentChangedValues.count, 0)
player.value.name = "Bobby"
let changes = player.persistentChangedValues
XCTAssertEqual(changes.count, 1)
for (column, old) in changes {
switch column {
case "name":
XCTAssertEqual(old, "Arthur".databaseValue)
default:
XCTFail("Unexpected column: \(column)")
}
}
try player.save(db)
XCTAssertEqual(player.persistentChangedValues.count, 0)
}
}
func testChangesAfterPrimaryKeyChange() throws {
// After reload, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
player.value.id = player.value.id! + 1
let changes = player.persistentChangedValues
XCTAssertEqual(changes.count, 1)
for (column, old) in changes {
switch column {
case "id":
XCTAssertEqual(old, (player.value.id! - 1).databaseValue)
default:
XCTFail("Unexpected column: \(column)")
}
}
}
}
func testCopyTransfersChanges() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
XCTAssertEqual(player.persistentChangedValues.count, 0)
XCTAssertEqual(player.copy().persistentChangedValues.count, 0)
player.value.name = "Barbara"
XCTAssertTrue(player.persistentChangedValues.count > 0) // TODO: compare actual changes
XCTAssertEqual(player.persistentChangedValues.count, player.copy().persistentChangedValues.count)
player.hasPersistentChangedValues = false
XCTAssertEqual(player.persistentChangedValues.count, 0)
XCTAssertEqual(player.copy().persistentChangedValues.count, 0)
player.hasPersistentChangedValues = true
XCTAssertTrue(player.persistentChangedValues.count > 0) // TODO: compare actual changes
XCTAssertEqual(player.persistentChangedValues.count, player.copy().persistentChangedValues.count)
}
}
func testUpdateChanges() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
do {
XCTAssertTrue(player.hasPersistentChangedValues)
try player.updateChanges(db)
XCTFail("Expected PersistenceError")
} catch is PersistenceError { }
try player.insert(db)
// Nothing to update
let initialChangesCount = db.totalChangesCount
XCTAssertFalse(player.hasPersistentChangedValues)
try player.updateChanges(db)
XCTAssertEqual(db.totalChangesCount, initialChangesCount)
// Nothing to update
player.value.score = 41
XCTAssertFalse(player.hasPersistentChangedValues)
try player.updateChanges(db)
XCTAssertEqual(db.totalChangesCount, initialChangesCount)
// Update single column
player.value.score = 42
XCTAssertEqual(Set(player.persistentChangedValues.keys), ["score"])
try player.updateChanges(db)
XCTAssertEqual(db.totalChangesCount, initialChangesCount + 1)
XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"score\"=42 WHERE \"id\"=1")
// Update two columns
player.value.name = "Barbara"
player.value.score = 43
XCTAssertEqual(Set(player.persistentChangedValues.keys), ["score", "name"])
try player.updateChanges(db)
XCTAssertEqual(db.totalChangesCount, initialChangesCount + 2)
let fetchedPlayer = try RecordBox<Player>.fetchOne(db, key: player.value.id)!
XCTAssertEqual(fetchedPlayer.value.name, player.value.name)
XCTAssertEqual(fetchedPlayer.value.score, player.value.score)
}
}
}
@@ -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
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more