Compare commits

..
164 Commits
Author SHA1 Message Date
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
Gwendal Roué 188c026c6b v2.2.0 2017-10-31 14:07:23 +01:00
Gwendal Roué caf051f19d Improve jazzy documentation layout 2017-10-31 13:37:48 +01:00
Gwendal Roué c4a3d934a9 Documentation 2017-10-31 13:06:37 +01:00
Gwendal Roué b19424aa23 CHANGELOG.md 2017-10-31 12:51:45 +01:00
Gwendal Roué bc229fa6fd Documentation 2017-10-31 08:48:05 +01:00
Gwendal Roué 9beb5b553b Document that empty deferred transactions are not notified 2017-10-31 08:46:33 +01:00
Gwendal Roué 667e6a8e06 Document that empty deferred transactions are not notified 2017-10-31 08:45:52 +01:00
Gwendal Roué 8f9b667c29 Document that empty deferred transactions are not notified 2017-10-31 08:45:06 +01:00
Gwendal Roué a8e0c76a30 CHANGELOG.md 2017-10-31 08:33:38 +01:00
Gwendal Roué 49609ff08e Fix failing tests for observation of empty deferred transactions 2017-10-31 08:17:48 +01:00
Gwendal Roué efe201e032 More tests for observation of empty deferred transactions 2017-10-31 08:17:30 +01:00
Gwendal Roué 28c903f7ea Failing tests for observation of empty deferred transactions 2017-10-31 08:11:12 +01:00
Gwendal Roué a5b45031d2 Failing tests for observation of empty deferred transactions 2017-10-31 07:31:15 +01:00
Gwendal Roué 42e178b41d Improve tests robustness 2017-10-30 18:21:02 +01:00
Gwendal Roué c3fe2c13f4 More tests for "DROP INDEX" and "DROP TRIGGER" (#267) 2017-10-30 18:15:54 +01:00
Gwendal Roué af8a6872d9 StatementCompilationAuthorizer never returns SQLITE_IGNORE for a "DROP XXX" statement (#267) 2017-10-30 18:12:57 +01:00
Gwendal Roué f40a5e68ea Database.triggerExists(_:) 2017-10-30 18:10:22 +01:00
Gwendal Roué c4ad98426c Pass failing tests for "DROP VIEW" statements (#267) 2017-10-30 17:57:57 +01:00
Gwendal Roué a0e3d4ad69 Failing tests for "DROP VIEW" statements (#267) 2017-10-30 17:39:35 +01:00
Gwendal Roué d64bfe1cec Database.viewExists(_:) 2017-10-30 17:38:52 +01:00
Gwendal Roué 8a213af2ab Cleanup & whitespace 2017-10-30 12:25:12 +01:00
Gwendal Roué f02659e5d7 Remove outdated documentation 2017-10-29 17:05:14 +01:00
Gwendal Roué bdf943c3d9 Fix SPM compilation error 2017-10-29 15:45:35 +01:00
Gwendal Roué 9f1d5bc631 Fix SPM compilation error 2017-10-29 15:28:45 +01:00
Gwendal Roué f2b46679a6 Fix SPM compilation error 2017-10-29 14:35:10 +01:00
Gwendal Roué c5f38af247 Simplify select statement validation 2017-10-29 14:34:53 +01:00
Gwendal Roué 2bfef4f02d Rename DatabaseObservation.swift to TransactionObserver.swift 2017-10-29 14:24:41 +01:00
Gwendal Roué 07ae50cbb0 Detailed documentation of DatabaseObservationBroker 2017-10-29 14:22:22 +01:00
Gwendal Roué 7f10bf4005 Cleanup 2017-10-29 13:27:38 +01:00
Gwendal Roué 9130fe7b38 Cleanup 2017-10-29 12:58:24 +01:00
Gwendal Roué 340dcd1748 Extract transaction observation in the new DatabaseObservationBroker class 2017-10-29 12:22:54 +01:00
Gwendal Roué 8919bb5810 Move transaction and savepoint methods 2017-10-29 11:24:30 +01:00
Gwendal Roué bea98db813 Common code for select & update statements compilation 2017-10-29 11:13:30 +01:00
Gwendal Roué 05a0130c1e More straightforward cached statements API 2017-10-29 10:56:49 +01:00
Gwendal Roué e486437865 Split Database.swift 2017-10-29 10:43:22 +01:00
Gwendal Roué 1043516fb7 Fix sample code in CHANGELOG.md 2017-10-24 19:22:12 +02:00
Gwendal Roué c9b8b81ffb fix version number 2017-10-24 14:06:28 +02:00
Gwendal Roué 99b143a55c v2.1.0 2017-10-24 08:34:10 +02:00
Gwendal Roué 8401f42f3e Documentation 2017-10-24 08:20:33 +02:00
Gwendal Roué f69949edea Explain why Carthage test is commented out in .travis.yml 2017-10-24 08:18:06 +02:00
Gwendal Roué 62e33f294e ReleaseProcess.md 2017-10-24 08:11:13 +02:00
Gwendal Roué 2a8e48ba63 Minor 2017-10-24 08:11:05 +02:00
Gwendal Roué 6372bf663f Update Carthage information 2017-10-23 20:27:46 +02:00
Gwendal Roué ac7cc09bfe CHANGELOG.md 2017-10-23 19:54:38 +02:00
Gwendal Roué c9f0d473cf New FAQ: How do I print a request as SQL? 2017-10-23 19:54:30 +02:00
Gwendal Roué 8a7ffdbb67 CHANGELOG.md 2017-10-23 19:21:38 +02:00
Gwendal Roué d30baaf16c Fix default cached argument value for Request.asSQLRequest(_:cached:) 2017-10-23 19:21:30 +02:00
Gwendal Roué 1981adeb22 Request.asSQLRequest(_:cached:) 2017-10-23 19:20:38 +02:00
Gwendal Roué 8427b8b668 Remove test_CarthageBuild from the test make target 2017-10-23 19:02:09 +02:00
Gwendal Roué 6db590a31b Remove Carthage test from .travis.yml 2017-10-23 19:01:07 +02:00
Gwendal Roué 22faa03a48 Update sample code that create databases
The Application Support directory should generally be preferred.
2017-10-23 18:58:32 +02:00
Gwendal Roué d3cd0ae85a TODO.md 2017-10-23 09:42:40 +02:00
Gwendal Roué b624955bf3 Merge branch 'master' of github.com:groue/GRDB.swift into development 2017-10-15 12:19:35 +02:00
Gwendal Roué 1b20cd14d1 Fix link to SQLite documentation for the "pre-update hook" 2017-10-14 17:54:38 +02:00
Gwendal Roué baf2f780c9 Document that FetchedRecordsController is not suited for large data sets (#263) 2017-10-13 13:16:46 +02:00
Gwendal Roué 9d1997b6cd Typo 2017-10-12 21:54:46 +02:00
Gwendal Roué 313baa0064 Typo 2017-10-12 21:52:51 +02:00
Gwendal Roué 006eee9f51 Document that Record subclasses have to override database methods 2017-10-12 21:51:15 +02:00
Gwendal Roué 2720caf945 Documentation 2017-10-12 20:51:14 +02:00
Gwendal Roué 62faa57bf0 Documentation 2017-10-12 20:50:36 +02:00
Gwendal Roué abbdb995e6 Documentation 2017-10-12 20:46:01 +02:00
Gwendal Roué fd2ae60a65 Fix sample code of conversion from Row to Dictionary 2017-10-12 20:41:48 +02:00
Gwendal Roué 2c4cf2d06b Improve documentation of Codable support, and decrease focus on the Record class. 2017-10-12 20:40:33 +02:00
Gwendal Roué 0f5ec15d47 Test for Carthage integration in an iOS app 2017-10-12 08:26:36 +02:00
Gwendal Roué 1c3dfb346f Travis: move make test_CarthageBuild to the "Test Installation" stage 2017-10-11 22:02:02 +02:00
Darren Clark b76013d60b Travis - re-enable Carthage 2017-10-11 21:45:53 +02:00
Gwendal Roué e3ed95571c Upgrade custom SQLite builds to v3.20.1 2017-10-11 21:43:41 +02:00
Gwendal Roué c749893858 Update sqlcipher from https://github.com/groue/sqlcipher/pull/1 2017-10-11 21:26:37 +02:00
Gwendal Roué 9135be3da6 CHANGELOG 2017-10-11 08:20:34 +02:00
Gwendal Roué 9930fd3938 Fix failing test for drop temporary table 2017-10-11 08:17:57 +02:00
Gwendal Roué c62c3df00d Failing test for drop temporary table 2017-10-11 08:10:22 +02:00
Gwendal Roué 0419d67533 More fiddling with the deadly truncate optimization 2017-10-10 09:01:50 +02:00
Gwendal Roué 32d69c5be0 TODO.md 2017-10-10 08:20:27 +02:00
Gwendal Roué c2fb23c69c Stop using String.characters view 2017-10-10 08:15:28 +02:00
Gwendal Roué 47611e14f7 v2.0.3 2017-10-09 08:11:06 +02:00
Gwendal Roué b90f876b5b Records that adopt Encodable encode null columns 2017-10-09 08:06:46 +02:00
Gwendal Roué 9037d51bc7 Failing test for Encodable+Persistable (null values are not encoded) 2017-10-09 08:03:43 +02:00
Gwendal Roué fb8c68f5e0 Fix compiler error 2017-10-07 07:41:17 +02:00
Gwendal Roué 4995b5bb8c Group truncate optimization tests together 2017-10-07 06:51:13 +02:00
Gwendal Roué c87ebfd4eb CHANGELOG.md 2017-10-07 05:49:46 +02:00
91 changed files with 11113 additions and 7635 deletions

No files matched your search

+50 -44
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,98 +15,98 @@ jobs:
###########################################
## Test GRDB
# Test GRDBOSX (Xcode 9)
# Test GRDBOSX (Xcode 9.1)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.1
env:
- TID=GRDBOSX (Xcode 9, macOS 10.12)
- TID=GRDBOSX (Xcode 9.1, macOS)
script: make test_framework_GRDBOSX
# Test GRDBWatchOS (Xcode 9)
# Test GRDBWatchOS (Xcode 9.1)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.1
env:
- TID=GRDBWatchOS (Xcode 9, watchOS)
- TID=GRDBWatchOS (Xcode 9.1, watchOS)
script: make test_framework_GRDBWatchOS
# Test GRDBiOS (Xcode 9, iOS <MAXIMUM VERSION>)
# Test GRDBiOS (Xcode 9.1, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.1
env:
- TID=GRDBiOS (Xcode 9, iOS <MAX>)
- TID=GRDBiOS (Xcode 9.1, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget
# Test GRDBiOS (Xcode 9, iOS <MINIMUM VERSION>))
# Test GRDBiOS (Xcode 9.1, iOS <MINIMUM VERSION>))
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.1
env:
- TID=GRDBiOS (Xcode 9, iOS <MIN>)
- TID=GRDBiOS (Xcode 9.1, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
# Test GRDB [SPM] (Xcode 9, macOS 10.12)
# Test GRDB [SPM] (Xcode 9.1, macOS)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.1
env:
- TID=GRDB [SPM] (Xcode 9, macOS 10.12)
- TID=GRDB [SPM] (Xcode 9.1, macOS)
script: make test_SPM
###########################################
## Test GRDB (Custom SQLite)
# Test GRDBCustomSQLiteOSX (Xcode 9)
# Test GRDBCustomSQLiteOSX (Xcode 9.1)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.1
env:
- TID=GRDBCustomSQLiteOSX (Xcode 9, macOS 10.12)
- TID=GRDBCustomSQLiteOSX (Xcode 9.1, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
# Test GRDBCustomSQLiteiOS (Xcode 9, iOS <MAXIMUM VERSION>)
# Test GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.1
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9, iOS <MAX>)
- TID=GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
# Test GRDBCustomSQLiteiOS (Xcode 9, iOS <MINIMUM VERSION>))
# Test GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MINIMUM VERSION>))
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.1
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9, iOS <MIN>)
- TID=GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test GRDB (SQLCipher)
# Test GRDBCipherOSX (Xcode 9)
# Test GRDBCipherOSX (Xcode 9.1)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.1
env:
- TID=GRDBCipherOSX (Xcode 9, macOS 10.12)
- TID=GRDBCipherOSX (Xcode 9.1, macOS)
script: make test_framework_GRDBCipherOSX
# Test GRDBCipheriOS (Xcode 9, iOS <MAXIMUM VERSION>)
# Test GRDBCipheriOS (Xcode 9.1, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.1
env:
- TID=GRDBCipheriOS (Xcode 9, iOS <MAX>)
- TID=GRDBCipheriOS (Xcode 9.1, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
# Test GRDBCipheriOS (Xcode 9, iOS <MINIMUM VERSION>))
# Test GRDBCipheriOS (Xcode 9.1, iOS <MINIMUM VERSION>))
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.1
env:
- TID=GRDBCipheriOS (Xcode 9, iOS <MIN>)
- TID=GRDBCipheriOS (Xcode 9.1, iOS <MIN>)
script: make test_framework_GRDBCipheriOS_minTarget
###########################################
@@ -112,7 +115,7 @@ jobs:
# Manual Install
- stage: Test Installation
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.1
env:
- TID=Manual Install
script: make test_install_manual
@@ -120,14 +123,14 @@ jobs:
# Manual Install (GRDBCipher)
- stage: Test Installation
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
osx_image: xcode9.1
env:
- TID=Manual Install (GRDBCipher)
script: make test_install_GRDBCipher
# Cocoapods Lint
- stage: Test Installation
osx_image: xcode9
osx_image: xcode9.1
install:
- gem install cocoapods # Since Travis is not always on latest version
env:
@@ -136,16 +139,19 @@ jobs:
# SPM Install
- stage: Test Installation
osx_image: xcode9
osx_image: xcode9.1
env:
- TID=SPM
script: make test_install_SPM
## The following doesn’t work, as `make test_CarthageBuild` does not yet work.
## Carthage Build
#- stage: Carthage
# osx_image: xcode9
# before_install:
# - brew update
# - brew outdated carthage || brew upgrade carthage
# script: make test_CarthageBuild
## Commented out until `make test_CarthageBuild` performs *reliably*.
## See https://github.com/groue/GRDB.swift/pull/262
# - stage: Test Installation
# osx_image: xcode9.1
# before_install:
# - brew update
# - brew outdated carthage || brew upgrade carthage
# env:
# - TID=Carthages
# script: make test_CarthageBuild
+144 -2
View File
@@ -1,6 +1,148 @@
Release Notes
=============
## 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)
**New**
- `Database.viewExists(_:)` returns whether a view exists in the database.
- `Database.triggerExists(_:)` returns whether a trigger exists in the database.
**Fixed**
- `DROP VIEW` statements would not drop views ([#267](https://github.com/groue/GRDB.swift/issues/267))
- GRDB used to incorrectly send incomplete transaction notifications to [transaction observers](https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol) in the case of empty deferred transactions. This is no longer the case. Since empty deferred transactions have SQLite consider that no transaction started at all, they are no longer notified to transaction observers:
```sql
-- Nothing happens, and thus no notification is sent
BEGIN TRANSACTION
COMMIT
```
Those empty deferred transactions still count for the [afterNextTransactionCommit](https://github.com/groue/GRDB.swift/blob/master/README.md#after-commit-hook) database method, and the `.nextTransaction` [observation extent](https://github.com/groue/GRDB.swift/blob/master/README.md#observation-extent).
## 2.1.0
Released October 24, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.0.3...v2.1.0)
### New
- GRDBCipher can now build from command line ([groue/sqlcipher/pull/1](https://github.com/groue/sqlcipher/pull/1) by [Darren Clark](https://github.com/darrenclark))
- Upgrade custom SQLite builds to [v3.20.1](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- The new method `Request.asSQLRequest` allows to inspect the sql and arguments of any request:
```swift
let request = Player.all()
let sql = try request.asSQLRequest(db).sql
print(sql) // Prints "SELECT * FROM players"
```
- StatementArguments adopts Equatable
### Fixed
- `DROP TABLE` statements would not drop temporary tables.
### Documentation Diff
- New FAQ: [How do I create a database in my application?](https://github.com/groue/GRDB.swift/blob/master/README.md#how-do-i-create-a-database-in-my-application)
- New FAQ: [How do I print a request as SQL?](https://github.com/groue/GRDB.swift/blob/master/README.md#how-do-i-print-a-request-as-sql)
- The [Codable Record](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records) chapter has been enhanced with more information and sample code.
### API diff
```diff
extension Request {
+ func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest
}
struct SQLRequest {
+ let sql: String
+ let arguments: StatementArguments?
+ let adapter: RowAdapter?
}
```
## 2.0.3
Released October 9, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.0.2...v2.0.3)
**Fixed**: Record types that conform to Encodable now encode their null columns.
## 2.0.2
Released October 5, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.0.1...v2.0.2)
@@ -114,7 +256,7 @@ New features have been added in order to plug a few holes and support the [RxGRD
- Query interface requests learned how to limit the number of deleted rows:
```swift
// Delete the worse ten players:
// Delete the last ten players:
// DELETE FROM players ORDER BY score LIMIT 10
let request = Player.order(scoreColumn).limit(10)
try request.deleteAll(db)
@@ -186,7 +328,7 @@ New features have been added in order to plug a few holes and support the [RxGRD
- The deprecated `TableMapping.primaryKeyRowComparator` method has been removed.
### Documentation diff
### Documentation Diff
- [WatchOS installation procedure](https://github.com/groue/GRDB.swift#installation) has been updated with new instructions.
- The [introduction to multithreading with database pools](https://github.com/groue/GRDB.swift#database-pools) has been enhanced.
@@ -14,9 +14,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
private func setupDatabase(_ application: UIApplication) throws {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
let databasePath = documentsPath.appendingPathComponent("db.sqlite")
dbQueue = try AppDatabase.openDatabase(atPath: databasePath)
let databaseURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path)
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
+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.0](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.0.2
git checkout v2.4.2
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**.
+2 -2
View File
@@ -497,7 +497,7 @@ Build a `value BETWEEN min AND max` expression from Swift ranges:
#### The COUNT Function
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.0/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.0/Functions.html) functions:
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.4/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.4/Functions.html) functions:
```swift
// SQLExpression: COUNT(email)
@@ -588,4 +588,4 @@ You may want to compare it to another protocol, SQLSpecificExpressible, which ha
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `cast` function, it is Database.ColumnType.
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/2.0/Protocols/SQLExpression.html) protocol.
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/SQLExpression.html) protocol.
+4 -1
View File
@@ -24,9 +24,12 @@ To release a new GRDB version:
- Commit and tag
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
- Push to the master branch
- Push to the Swift3 branch
- Push to the Swift4 branch
- `pod trunk push --allow-warnings GRDB.swift.podspec`
- `pod trunk push --allow-warnings GRDBCipher.podspec`
- `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.0.2'
s.version = '2.4.2'
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>
+456
View File
@@ -0,0 +1,456 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
// MARK: - Database Schema
/// Clears the database schema cache.
///
/// You may need to clear the cache manually if the database schema is
/// modified by another connection.
public func clearSchemaCache() {
SchedulingWatchdog.preconditionValidQueue(self)
schemaCache.clear()
// We also clear updateStatementCache and selectStatementCache despite
// the automatic statement recompilation (see https://www.sqlite.org/c3ref/prepare.html)
// because the automatic statement recompilation only happens a
// limited number of times.
internalStatementCache.clear()
publicStatementCache.clear()
}
/// Returns whether a table exists.
public func tableExists(_ tableName: String) throws -> Bool {
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'table' AND LOWER(name) = ?", arguments: [tableName.lowercased()]) != nil
}
/// Returns whether a view exists.
public func viewExists(_ viewName: String) throws -> Bool {
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'view' AND LOWER(name) = ?", arguments: [viewName.lowercased()]) != nil
}
/// Returns whether a trigger exists.
public func triggerExists(_ triggerName: String) throws -> Bool {
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'trigger' AND LOWER(name) = ?", arguments: [triggerName.lowercased()]) != nil
}
/// The primary key for table named `tableName`.
///
/// All tables have a primary key, even when it is not explicit. When a
/// table has no explicit primary key, the result is the hidden
/// "rowid" column.
///
/// - throws: A DatabaseError if table does not exist.
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
SchedulingWatchdog.preconditionValidQueue(self)
if let primaryKey = schemaCache.primaryKey(tableName) {
return primaryKey
}
// https://www.sqlite.org/pragma.html
//
// > PRAGMA database.table_info(table-name);
// >
// > This pragma returns one row for each column in the named table.
// > Columns in the result set include the column name, data type,
// > whether or not the column can be NULL, and the default value for
// > the column. The "pk" column in the result set is zero for columns
// > that are not part of the primary key, and is the index of the
// > column in the primary key for columns that are part of the primary
// > key.
//
// CREATE TABLE players (
// id INTEGER PRIMARY KEY,
// name TEXT,
// score INTEGER)
//
// PRAGMA table_info("players")
//
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
let columns = try self.columns(in: tableName)
let primaryKey: PrimaryKeyInfo
let pkColumns = columns
.filter { $0.primaryKeyIndex > 0 }
.sorted { $0.primaryKeyIndex < $1.primaryKeyIndex }
switch pkColumns.count {
case 0:
// No explicit primary key => primary key is hidden rowID column
primaryKey = .hiddenRowID
case 1:
// Single column
let pkColumn = pkColumns.first!
// https://www.sqlite.org/lang_createtable.html:
//
// > With one exception noted below, if a rowid table has a primary
// > key that consists of a single column and the declared type of
// > that column is "INTEGER" in any mixture of upper and lower
// > case, then the column becomes an alias for the rowid. Such a
// > column is usually referred to as an "integer primary key".
// > A PRIMARY KEY column only becomes an integer primary key if the
// > declared type name is exactly "INTEGER". Other integer type
// > names like "INT" or "BIGINT" or "SHORT INTEGER" or "UNSIGNED
// > INTEGER" causes the primary key column to behave as an ordinary
// > table column with integer affinity and a unique index, not as
// > an alias for the rowid.
// >
// > The exception mentioned above is that if the declaration of a
// > column with declared type "INTEGER" includes an "PRIMARY KEY
// > DESC" clause, it does not become an alias for the rowid [...]
//
// FIXME: We ignore the exception, and consider all INTEGER primary
// keys as aliases for the rowid:
if pkColumn.type.uppercased() == "INTEGER" {
primaryKey = .rowID(pkColumn.name)
} else {
primaryKey = .regular([pkColumn.name])
}
default:
// Multi-columns primary key
primaryKey = .regular(pkColumns.map { $0.name })
}
schemaCache.set(primaryKey: primaryKey, forTable: tableName)
return primaryKey
}
/// The number of columns in the table named `tableName`.
///
/// - throws: A DatabaseError if table does not exist.
public func columnCount(in tableName: String) throws -> Int {
return try columns(in: tableName).count
}
/// The indexes on table named `tableName`; returns the empty array if the
/// table does not exist.
///
/// Note: SQLite does not define any index for INTEGER PRIMARY KEY columns:
/// this method does not return any index that represents this primary key.
///
/// If you want to know if a set of columns uniquely identify a row, prefer
/// table(_:hasUniqueKey:) instead.
public func indexes(on tableName: String) throws -> [IndexInfo] {
if let indexes = schemaCache.indexes(on: tableName) {
return indexes
}
let indexes = try Row.fetchAll(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row -> IndexInfo in
let indexName: String = row[1]
let unique: Bool = row[2]
let columns = try Row.fetchAll(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
.map { ($0[0] as Int, $0[2] as String) }
.sorted { $0.0 < $1.0 }
.map { $0.1 }
return IndexInfo(name: indexName, columns: columns, unique: unique)
}
schemaCache.set(indexes: indexes, forTable: tableName)
return indexes
}
/// True if a sequence of columns uniquely identifies a row, that is to say
/// if the columns are the primary key, or if there is a unique index on them.
public func table<T: Sequence>(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T.Iterator.Element == String {
return try columnsForUniqueKey(Array(columns), in: tableName) != nil
}
/// The foreign keys defined on table named `tableName`.
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
if let foreignKeys = schemaCache.foreignKeys(on: tableName) {
return foreignKeys
}
var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = []
var previousId: Int? = nil
for row in try Row.fetchAll(self, "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
// row = <Row id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"...">
let id: Int = row[0]
let seq: Int = row[1]
let table: String = row[2]
let origin: String = row[3]
let destination: String? = row[4]
if previousId == id {
rawForeignKeys[rawForeignKeys.count - 1].mapping.append((origin: origin, destination: destination, seq: seq))
} else {
rawForeignKeys.append((destinationTable: table, mapping: [(origin: origin, destination: destination, seq: seq)]))
previousId = id
}
}
let foreignKeys = try rawForeignKeys.map { (destinationTable, columnMapping) -> ForeignKeyInfo in
let orderedMapping = columnMapping
.sorted { $0.seq < $1.seq }
.map { (origin: $0.origin, destination: $0 .destination) }
let completeMapping: [(origin: String, destination: String)]
if orderedMapping.contains(where: { (_, destination) in destination == nil }) {
let pk = try primaryKey(destinationTable)
completeMapping = zip(pk.columns, orderedMapping).map { (pkColumn, arrow) in
(origin: arrow.origin, destination: pkColumn)
}
} else {
completeMapping = orderedMapping.map { (origin, destination) in
(origin: origin, destination: destination!)
}
}
return ForeignKeyInfo(destinationTable: destinationTable, mapping: completeMapping)
}
schemaCache.set(foreignKeys: foreignKeys, forTable: tableName)
return foreignKeys
}
}
extension Database {
/// The columns in the table named `tableName`.
///
/// - throws: A DatabaseError if table does not exist.
func columns(in tableName: String) throws -> [ColumnInfo] {
if let columns = schemaCache.columns(in: tableName) {
return columns
}
// https://www.sqlite.org/pragma.html
//
// > PRAGMA database.table_info(table-name);
// >
// > This pragma returns one row for each column in the named table.
// > Columns in the result set include the column name, data type,
// > whether or not the column can be NULL, and the default value for
// > the column. The "pk" column in the result set is zero for columns
// > that are not part of the primary key, and is the index of the
// > column in the primary key for columns that are part of the primary
// > key.
//
// CREATE TABLE players (
// id INTEGER PRIMARY KEY,
// firstName TEXT,
// lastName TEXT)
//
// PRAGMA table_info("players")
//
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
if sqlite3_libversion_number() < 3008005 {
// Work around a bug in SQLite where PRAGMA table_info would
// return a result even after the table was deleted.
if try !tableExists(tableName) {
throw DatabaseError(message: "no such table: \(tableName)")
}
}
let columns = try ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
guard columns.count > 0 else {
throw DatabaseError(message: "no such table: \(tableName)")
}
schemaCache.set(columns: columns, forTable: tableName)
return columns
}
/// If there exists a unique key on columns, return the columns
/// ordered as the matching index (or primay key). Case of returned columns
/// is not guaranteed.
func columnsForUniqueKey<T: Sequence>(_ columns: T, in tableName: String) throws -> [String]? where T.Iterator.Element == String {
let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist
let lowercasedColumns = Set(columns.map { $0.lowercased() })
if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns {
return primaryKey.columns
}
if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) {
// There is an explicit unique index on the columns
return index.columns
}
return nil
}
}
/// A column of a table
struct ColumnInfo : RowConvertible {
// CREATE TABLE players (
// id INTEGER PRIMARY KEY,
// firstName TEXT,
// lastName TEXT)
//
// PRAGMA table_info("players")
//
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
let name: String
let type: String
let notNull: Bool
let defaultDatabaseValue: DatabaseValue
let primaryKeyIndex: Int
init(row: Row) {
name = row["name"]
type = row["type"]
notNull = row["notnull"]
defaultDatabaseValue = row["dflt_value"]
primaryKeyIndex = row["pk"]
}
}
/// An index on a database table.
///
/// See `Database.indexes(on:)`
public struct IndexInfo {
/// The name of the index
public let name: String
/// The indexed columns
public let columns: [String]
/// True if the index is unique
public let isUnique: Bool
init(name: String, columns: [String], unique: Bool) {
self.name = name
self.columns = columns
self.isUnique = unique
}
}
/// Primary keys are returned from the Database.primaryKey(_:) method.
///
/// When the table's primary key is the rowid:
///
/// // CREATE TABLE items (name TEXT)
/// let pk = try db.primaryKey("items")
/// pk.columns // ["rowid"]
/// pk.rowIDColumn // nil
/// pk.isRowID // true
///
/// // CREATE TABLE citizens (
/// // id INTEGER PRIMARY KEY,
/// // name TEXT
/// // )
/// let pk = try db.primaryKey("citizens")!
/// pk.columns // ["id"]
/// pk.rowIDColumn // "id"
/// pk.isRowID // true
///
/// When the table's primary key is not the rowid:
///
/// // CREATE TABLE countries (
/// // isoCode TEXT NOT NULL PRIMARY KEY
/// // name TEXT
/// // )
/// let pk = db.primaryKey("countries")!
/// pk.columns // ["isoCode"]
/// pk.rowIDColumn // nil
/// pk.isRowID // false
///
/// // CREATE TABLE citizenships (
/// // citizenID INTEGER NOT NULL REFERENCES citizens(id)
/// // countryIsoCode TEXT NOT NULL REFERENCES countries(isoCode)
/// // PRIMARY KEY (citizenID, countryIsoCode)
/// // )
/// let pk = db.primaryKey("citizenships")!
/// pk.columns // ["citizenID", "countryIsoCode"]
/// pk.rowIDColumn // nil
/// pk.isRowID // false
public struct PrimaryKeyInfo {
private enum Impl {
/// The hidden rowID.
case hiddenRowID
/// An INTEGER PRIMARY KEY column that aliases the Row ID.
/// Associated string is the column name.
case rowID(String)
/// Any primary key, but INTEGER PRIMARY KEY.
/// Associated strings are column names.
case regular([String])
}
private let impl: Impl
static func rowID(_ column: String) -> PrimaryKeyInfo {
return PrimaryKeyInfo(impl: .rowID(column))
}
static func regular(_ columns: [String]) -> PrimaryKeyInfo {
assert(!columns.isEmpty)
return PrimaryKeyInfo(impl: .regular(columns))
}
static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID)
/// The columns in the primary key; this array is never empty.
public var columns: [String] {
switch impl {
case .hiddenRowID:
return [Column.rowID.name]
case .rowID(let column):
return [column]
case .regular(let columns):
return columns
}
}
/// When not nil, the name of the column that contains the INTEGER PRIMARY KEY.
public var rowIDColumn: String? {
switch impl {
case .hiddenRowID:
return nil
case .rowID(let column):
return column
case .regular:
return nil
}
}
/// When true, the primary key is the rowid:
public var isRowID: Bool {
switch impl {
case .hiddenRowID:
return true
case .rowID:
return true
case .regular:
return false
}
}
}
/// You get foreign keys from table names, with the
/// `foreignKeys(on:)` method.
public struct ForeignKeyInfo {
/// The name of the destination table
public let destinationTable: String
/// The column to column mapping
public let mapping: [(origin: String, destination: String)]
/// The origin columns
public var originColumns: [String] {
return mapping.map { $0.origin }
}
/// The destination columns
public var destinationColumns: [String] {
return mapping.map { $0.destination }
}
}
+225
View File
@@ -0,0 +1,225 @@
import Foundation
extension Database {
// MARK: - Statements
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
/// - parameter sql: An SQL query.
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeSelectStatement(_ sql: String) throws -> SelectStatement {
return try makeSelectStatement(sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?", prepFlags: 0)
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
/// - parameter sql: An SQL query.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeSelectStatement(_ sql: String, prepFlags: Int32) throws -> SelectStatement {
return try SelectStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
/// The returned statement may have already been used: it may or may not
/// contain values for its eventual arguments.
///
/// - parameter sql: An SQL query.
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func cachedSelectStatement(_ sql: String) throws -> SelectStatement {
return try publicStatementCache.selectStatement(sql)
}
/// Returns a cached statement that does not conflict with user's cached statements.
func internalCachedSelectStatement(_ sql: String) throws -> SelectStatement {
return try internalStatementCache.selectStatement(sql)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
/// - parameter sql: An SQL query.
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement {
return try makeUpdateStatement(sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)", prepFlags: 0)
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
/// - parameter sql: An SQL query.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeUpdateStatement(_ sql: String, prepFlags: Int32) throws -> UpdateStatement {
return try UpdateStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedUpdateStatement("INSERT INTO players (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
/// The returned statement may have already been used: it may or may not
/// contain values for its eventual arguments.
///
/// - parameter sql: An SQL query.
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement {
return try publicStatementCache.updateStatement(sql)
}
/// Returns a cached statement that does not conflict with user's cached statements.
func internalCachedUpdateStatement(_ sql: String) throws -> UpdateStatement {
return try internalStatementCache.updateStatement(sql)
}
/// Executes one or several SQL statements, separated by semi-colons.
///
/// try db.execute(
/// "INSERT INTO players (name) VALUES (:name)",
/// arguments: ["name": "Arthur"])
///
/// try db.execute("""
/// INSERT INTO players (name) VALUES (?);
/// INSERT INTO players (name) VALUES (?);
/// INSERT INTO players (name) VALUES (?);
/// """, arguments; ['Arthur', 'Barbara', 'Craig'])
///
/// This method may throw a DatabaseError.
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(_ sql: String, arguments: StatementArguments? = nil) throws {
// This method is like sqlite3_exec (https://www.sqlite.org/c3ref/exec.html)
// It adds support for arguments, and the tricky part is to consume
// arguments as statements are executed.
//
// Here we build two functions:
// - consumeArguments returns arguments for a statement
// - validateRemainingArguments validates the remaining arguments, after
// all statements have been executed, in the same way
// as Statement.validate(arguments:)
var arguments = arguments ?? StatementArguments()
let initialValuesCount = arguments.values.count
let consumeArguments = { (statement: UpdateStatement) throws -> StatementArguments in
let bindings = try arguments.consume(statement, allowingRemainingValues: true)
return StatementArguments(bindings)
}
let validateRemainingArguments = {
if !arguments.values.isEmpty {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)")
}
}
// Iterate SQL statements
let sqlCodeUnits = sql.utf8CString
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
let sqlEnd = sqlStart + sqlCodeUnits.count
var statementStart = sqlStart
while statementStart < sqlEnd - 1 {
var statementEnd: UnsafePointer<Int8>? = nil
do {
let statement: UpdateStatement
// Compile
do {
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
authorizer = statementCompilationAuthorizer
defer { authorizer = nil }
statement = try UpdateStatement(
database: self,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: 0,
authorizer: statementCompilationAuthorizer)
}
// Execute
let arguments = try consumeArguments(statement)
statement.unsafeSetArguments(arguments)
try statement.execute()
// Next
statementStart = statementEnd!
} catch is EmptyStatementError {
// End
break
}
}
}
// Force arguments validity: it is a programmer error to provide
// arguments that do not match the statement.
try! validateRemainingArguments() // throws if there are remaining arguments.
}
}
extension Database {
func updateStatementWillExecute(_ statement: UpdateStatement) {
observationBroker.updateStatementWillExecute(statement)
}
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
if statement.invalidatesDatabaseSchemaCache {
clearSchemaCache()
}
try observationBroker.updateStatementDidExecute(statement)
}
func updateStatementDidFail(_ statement: UpdateStatement) throws {
// Failed statements can not be reused, because sqlite3_reset won't
// be able to restore the statement to its initial state:
// https://www.sqlite.org/c3ref/reset.html
//
// So make sure we clear this statement from the cache.
internalStatementCache.remove(statement)
publicStatementCache.remove(statement)
try observationBroker.updateStatementDidFail(statement)
}
func selectStatementDidFail(_ statement: SelectStatement) {
// Failed statements can not be reused, because sqlite3_reset won't
// be able to restore the statement to its initial state:
// https://www.sqlite.org/c3ref/reset.html
//
// So make sure we clear this statement from the cache.
internalStatementCache.remove(statement)
publicStatementCache.remove(statement)
}
}
+762 -2593
View File
File diff suppressed because it is too large. Load diff
+51
View File
@@ -0,0 +1,51 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A Collation is a string comparison function used by SQLite.
public final class DatabaseCollation {
public let name: String
let function: (Int32, UnsafeRawPointer?, Int32, UnsafeRawPointer?) -> ComparisonResult
/// Creates a collation.
///
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// db.add(collation: collation)
/// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard")
///
/// - parameters:
/// - name: The function name.
/// - function: A function that compares two strings.
public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) {
self.name = name
self.function = { (length1, buffer1, length2, buffer2) in
// Buffers are not C strings: they do not end with \0.
let string1 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped), length: Int(length1), encoding: .utf8, freeWhenDone: false)!
let string2 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped), length: Int(length2), encoding: .utf8, freeWhenDone: false)!
return function(string1, string2)
}
}
}
extension DatabaseCollation : Hashable {
public var hashValue: Int {
// Collation equality is based on the sqlite3_strnicmp SQLite function.
// (see https://www.sqlite.org/c3ref/create_collation.html). Computing
// a hash value that honors the Swift Hashable contract (value equality
// implies hash equality) is thus non trivial. But it's not that
// important, since this hashValue is only used when one adds
// or removes a collation from a database connection.
return 0
}
/// Two collations are equal if they share the same name (case insensitive)
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
}
}
+22 -20
View File
@@ -5,7 +5,7 @@ import Foundation
import SQLite3
#endif
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
public struct ResultCode : RawRepresentable {
public let rawValue: Int32
public init(rawValue: Int32) {
@@ -25,24 +25,6 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
return self == primaryResultCode
}
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)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
} else {
return "\(rawValue)"
}
#endif
}
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
return lhs.rawValue == rhs.rawValue
}
/// Returns true if the code on the left matches the code on the right.
///
/// Primary result codes match themselves and their extended result codes,
@@ -155,7 +137,28 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8)))
public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8)))
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
}
extension ResultCode : Equatable {
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension ResultCode : CustomStringConvertible {
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)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
} else {
return "\(rawValue)"
}
#endif
}
}
/// DatabaseError wraps an SQLite error.
@@ -221,7 +224,6 @@ public struct DatabaseError : Error {
}
extension DatabaseError: CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
var description = "SQLite error \(resultCode.rawValue)"
if let sql = sql {
+58 -55
View File
@@ -10,8 +10,25 @@ import Foundation
/// A DatabasePool grants concurrent accesses to an SQLite database.
public final class DatabasePool {
private let writer: SerializedDatabase
private var readerConfig: Configuration
private var readerPool: Pool<SerializedDatabase>!
// MARK: - Initializers
private var functions = Set<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
#if os(iOS)
private weak var application: UIApplication?
#endif
// MARK: - Database Information
/// The path to the database.
public var path: String {
return writer.path
}
// MARK: - Initializer
/// Opens the SQLite database at path *path*.
///
@@ -27,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 {
@@ -67,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 {
@@ -91,18 +105,12 @@ public final class DatabasePool {
NotificationCenter.default.removeObserver(self)
}
#endif
// MARK: - Configuration
/// The path to the database.
public var path: String {
return writer.path
}
// MARK: - WAL Management
}
extension DatabasePool {
// MARK: - WAL Checkpoints
/// Runs a WAL checkpoint
///
/// See https://www.sqlite.org/wal.html and
@@ -121,10 +129,12 @@ public final class DatabasePool {
}
}
}
}
extension DatabasePool {
// MARK: - Memory management
/// Free as much memory as possible.
///
/// This method blocks the current thread until all database accesses are completed.
@@ -155,8 +165,6 @@ public final class DatabasePool {
center.addObserver(self, selector: #selector(DatabasePool.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
}
private var application: UIApplication!
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
guard let application = application else {
return
@@ -183,24 +191,12 @@ public final class DatabasePool {
}
}
#endif
// MARK: - Not public
private let writer: SerializedDatabase
private var readerConfig: Configuration
private var readerPool: Pool<SerializedDatabase>! = nil // var and nil-initialized so that we can use `self` when creating readerPool in DatabasePool.init()
private var functions = Set<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
}
// =========================================================================
// MARK: - Encryption
#if SQLITE_HAS_CODEC
extension DatabasePool {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
public func change(passphrase: String) throws {
@@ -212,14 +208,10 @@ public final class DatabasePool {
}
#endif
// =========================================================================
// MARK: - DatabaseReader
extension DatabasePool : DatabaseReader {
// MARK: - Read From Database
// MARK: - Reading from Database
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result. The block is wrapped in a deferred transaction.
///
@@ -255,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
}
@@ -292,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)
}
}
}
@@ -328,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)
}
}
}
}
@@ -355,7 +357,6 @@ extension DatabasePool : DatabaseReader {
return readers.first { $0.onValidQueue }
}
// MARK: - Functions
/// Add or redefine an SQL function.
@@ -387,7 +388,6 @@ extension DatabasePool : DatabaseReader {
}
}
// MARK: - Collations
/// Add or redefine a collation.
@@ -417,10 +417,6 @@ extension DatabasePool : DatabaseReader {
}
}
// =========================================================================
// MARK: - DatabaseWriter
extension DatabasePool : DatabaseWriter {
// MARK: - Writing in Database
@@ -510,13 +506,13 @@ extension DatabasePool : DatabaseWriter {
return try writer.reentrantSync(block)
}
// MARK: - Reading from Database
/// 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
@@ -582,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:
@@ -602,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
}
}
+58 -86
View File
@@ -6,6 +6,22 @@ import UIKit
/// A DatabaseQueue serializes access to an SQLite database.
public final class DatabaseQueue {
private var serializedDatabase: SerializedDatabase
#if os(iOS)
private weak var application: UIApplication?
#endif
// MARK: - Configuration
/// The database configuration
public var configuration: Configuration {
return serializedDatabase.configuration
}
/// The path to the database file; it is ":memory:" for in-memory databases.
public var path: String {
return serializedDatabase.path
}
// MARK: - Initializers
@@ -50,23 +66,12 @@ public final class DatabaseQueue {
NotificationCenter.default.removeObserver(self)
}
#endif
// MARK: - Configuration
/// The database configuration
public var configuration: Configuration {
return serializedDatabase.configuration
}
/// The path to the database file; it is ":memory:" for in-memory databases.
public var path: String {
return serializedDatabase.path
}
// MARK: - Database access
}
extension DatabaseQueue {
// MARK: - Database Access
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
@@ -111,10 +116,12 @@ public final class DatabaseQueue {
}
}
}
}
extension DatabaseQueue {
// MARK: - Memory management
/// Free as much memory as possible.
///
/// This method blocks the current thread until all database accesses are completed.
@@ -124,7 +131,6 @@ public final class DatabaseQueue {
inDatabase { $0.releaseMemory() }
}
#if os(iOS)
/// Listens to UIApplicationDidEnterBackgroundNotification and
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
@@ -140,8 +146,6 @@ public final class DatabaseQueue {
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
}
private var application: UIApplication?
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
guard let application = application else {
return
@@ -168,37 +172,13 @@ public final class DatabaseQueue {
}
}
#endif
// MARK: - Not public
// https://www.sqlite.org/isolation.html
//
// > Within a single database connection X, a SELECT statement always
// > sees all changes to the database that are completed prior to the
// > start of the SELECT statement, whether committed or uncommitted.
// > And the SELECT statement obviously does not see any changes that
// > occur after the SELECT statement completes. But what about changes
// > that occur while the SELECT statement is running? What if a SELECT
// > statement is started and the sqlite3_step() interface steps through
// > roughly half of its output, then some UPDATE statements are run by
// > the application that modify the table that the SELECT statement is
// > reading, then more calls to sqlite3_step() are made to finish out
// > the SELECT statement? Will the later steps of the SELECT statement
// > see the changes made by the UPDATE or not? The answer is that this
// > behavior is undefined.
//
// This is why we use a serialized database:
private var serializedDatabase: SerializedDatabase
}
// =========================================================================
// MARK: - Encryption
#if SQLITE_HAS_CODEC
extension DatabaseQueue {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
public func change(passphrase: String) throws {
try inDatabase { try $0.change(passphrase: passphrase) }
@@ -206,14 +186,10 @@ public final class DatabaseQueue {
}
#endif
// =========================================================================
// MARK: - DatabaseReader
extension DatabaseQueue : DatabaseReader {
// MARK: - DatabaseReader Protocol Adoption
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result.
///
@@ -261,7 +237,6 @@ extension DatabaseQueue : DatabaseReader {
return try serializedDatabase.reentrantSync(block)
}
// MARK: - Functions
/// Add or redefine an SQL function.
@@ -285,7 +260,6 @@ extension DatabaseQueue : DatabaseReader {
inDatabase { $0.remove(function: function) }
}
// MARK: - Collations
/// Add or redefine a collation.
@@ -307,14 +281,10 @@ extension DatabaseQueue : DatabaseReader {
}
}
// =========================================================================
// MARK: - DatabaseWriter
extension DatabaseQueue : DatabaseWriter {
// MARK: - DatabaseWriter Protocol Adoption
/// Alias for `inDatabase`. See `DatabaseWriter.write`.
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
return try inDatabase(block)
@@ -326,20 +296,28 @@ 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`.
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
}
}
/// Synchronously executes a block in a protected dispatch queue, and
@@ -356,19 +334,13 @@ extension DatabaseQueue : DatabaseWriter {
}
}
// Wraps the block between two `PRAGMA query_only` statements.
//
// This method is unsafe because the two calls to `PRAGMA query_only` are
// not guaranteed to be serialized (some other thread could mess with this).
private func readOnly<T>(_ db: Database, _ block: (Database) throws -> T) rethrows -> T {
if db.configuration.readonly {
guard !db.configuration.readonly else {
return try block(db)
} else {
try! db.execute("PRAGMA query_only = 1") // Assume can't fail
let result = try block(db)
try! db.execute("PRAGMA query_only = 0") // Assume can't fail
return result
}
// Assume those pragmas never fail
try! db.execute("PRAGMA query_only = 1")
defer { try! db.execute("PRAGMA query_only = 0") }
return try block(db)
}
+6
View File
@@ -221,6 +221,8 @@ public final class AnyDatabaseReader : DatabaseReader {
self.base = base
}
// MARK: - Reading from Database
public func read<T>(_ block: (Database) throws -> T) throws -> T {
return try base.read(block)
}
@@ -233,6 +235,8 @@ public final class AnyDatabaseReader : DatabaseReader {
return try base.unsafeReentrantRead(block)
}
// MARK: - Functions
public func add(function: DatabaseFunction) {
base.add(function: function)
}
@@ -241,6 +245,8 @@ public final class AnyDatabaseReader : DatabaseReader {
base.remove(function: function)
}
// MARK: - Collations
public func add(collation: DatabaseCollation) {
base.add(collation: collation)
}
+18 -47
View File
@@ -1,9 +1,4 @@
/// 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()
@@ -21,13 +16,13 @@ protocol DatabaseSchemaCache {
}
/// A thread-unsafe database schema cache
final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
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() {
primaryKeys = [:]
columns = [:]
indexes = [:]
@@ -38,7 +33,7 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
return primaryKeys[table]
}
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
primaryKeys[table] = primaryKey
}
@@ -46,7 +41,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 +49,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 +57,24 @@ 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 primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil }
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
return cache.read { $0.primaryKey(table) }
}
func columns(in table: String) -> [ColumnInfo]? { return nil }
mutating func set(columns: [ColumnInfo], forTable table: String) { }
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
cache.write { $0.set(primaryKey: primaryKey, forTable: table) }
}
func indexes(on table: String) -> [IndexInfo]? { return nil }
mutating func set(indexes: [IndexInfo], forTable table: String) { }
func columns(in table: String) -> [ColumnInfo]? {
return cache.read { $0.columns(in: table) }
}
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 }
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { }
}
+5 -21
View File
@@ -11,6 +11,11 @@ import Foundation
///
/// See https://www.sqlite.org/datatype3.html
public struct DatabaseValue {
/// The SQLite storage
public let storage: Storage
/// The NULL DatabaseValue.
public static let null = DatabaseValue(storage: .null)
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
public enum Storage : Equatable {
@@ -62,12 +67,6 @@ public struct DatabaseValue {
}
}
/// The SQLite storage
public let storage: Storage
/// The NULL DatabaseValue.
public static let null = DatabaseValue(storage: .null)
/// Creates a DatabaseValue from Any.
///
/// The result is nil unless object adopts DatabaseValueConvertible.
@@ -78,7 +77,6 @@ public struct DatabaseValue {
self = convertible.databaseValue
}
// MARK: - Extracting Value
/// Returns true if databaseValue is NULL.
@@ -91,7 +89,6 @@ public struct DatabaseValue {
}
}
// MARK: - Not Public
init(storage: Storage) {
@@ -147,10 +144,8 @@ public struct DatabaseValue {
}
}
// MARK: - Hashable & Equatable
/// DatabaseValue adopts Hashable.
extension DatabaseValue : Hashable {
/// The hash value
@@ -207,7 +202,6 @@ extension DatabaseValue : Hashable {
}
}
// MARK: - Lossless conversions
extension DatabaseValue {
@@ -286,10 +280,6 @@ extension DatabaseValue {
}
}
// MARK: - DatabaseValueConvertible & SQLExpressible & SQLExpression
/// DatabaseValue adopts DatabaseValueConvertible.
extension DatabaseValue : DatabaseValueConvertible {
/// Returns self
public var databaseValue: DatabaseValue {
@@ -303,14 +293,12 @@ extension DatabaseValue : DatabaseValueConvertible {
}
extension DatabaseValue : SQLExpressible {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var sqlExpression: SQLExpression {
return self
}
}
/// DatabaseValue adopts SQLExpression.
extension DatabaseValue : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
@@ -355,11 +343,7 @@ extension DatabaseValue : SQLExpression {
}
}
// MARK: - CustomStringConvertible
/// DatabaseValue adopts CustomStringConvertible.
extension DatabaseValue : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
switch storage {
case .null:
-3
View File
@@ -30,9 +30,7 @@ public protocol DatabaseValueConvertible : SQLExpressible {
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
}
// SQLExpressible adoption
extension DatabaseValueConvertible {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var sqlExpression: SQLExpression {
return databaseValue
@@ -132,7 +130,6 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
extension DatabaseValueConvertible {
// MARK: Fetching From SelectStatement
/// Returns a cursor over values fetched from a prepared statement.
+36 -70
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
}
@@ -136,6 +94,8 @@ public final class AnyDatabaseWriter : DatabaseWriter {
self.base = base
}
// MARK: - Reading from Database
public func read<T>(_ block: (Database) throws -> T) throws -> T {
return try base.read(block)
}
@@ -148,21 +108,11 @@ public final class AnyDatabaseWriter : DatabaseWriter {
return try base.unsafeReentrantRead(block)
}
public func add(function: DatabaseFunction) {
base.add(function: function)
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
try base.readFromCurrentState(block)
}
public func remove(function: DatabaseFunction) {
base.remove(function: function)
}
public func add(collation: DatabaseCollation) {
base.add(collation: collation)
}
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
// MARK: - Writing in Database
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
return try base.write(block)
@@ -171,8 +121,24 @@ public final class AnyDatabaseWriter : DatabaseWriter {
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
return try base.unsafeReentrantWrite(block)
}
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
try base.readFromCurrentState(block)
// MARK: - Functions
public func add(function: DatabaseFunction) {
base.add(function: function)
}
public func remove(function: DatabaseFunction) {
base.remove(function: function)
}
// MARK: - Collations
public func add(collation: DatabaseCollation) {
base.add(collation: collation)
}
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
}
+37 -10
View File
@@ -36,6 +36,18 @@ extension Request {
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
}
/// Returns an equivalent SQLRequest.
///
/// - parameters:
/// - db: A database connection.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: An SQLRequest
public func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest {
let (statement, adapter) = try prepare(db)
return SQLRequest(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached)
}
}
extension Request {
@@ -126,6 +138,11 @@ public struct AnyRequest : Request {
/// A Request built from raw SQL.
public struct SQLRequest : Request {
public let sql: String
public let arguments: StatementArguments?
public let adapter: RowAdapter?
private let cache: Cache?
/// Creates a new request from an SQL string, optional arguments, and
/// optional row adapter.
///
@@ -140,7 +157,7 @@ public struct SQLRequest : Request {
/// prepared statement.
/// - returns: A SQLRequest
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .user : nil)
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil)
}
/// Creates a new request from an SQL string, optional arguments, and
@@ -155,11 +172,11 @@ public struct SQLRequest : Request {
/// - adapter: Optional RowAdapter.
/// - statementCacheName: Optional statement cache name.
/// - returns: A SQLRequest
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache statementCacheName: Database.StatementCacheName?) {
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
self.sql = sql
self.arguments = arguments
self.adapter = adapter
self.statementCacheName = statementCacheName
self.cache = cache
}
/// A tuple that contains a prepared statement that is ready to be
@@ -168,10 +185,13 @@ public struct SQLRequest : Request {
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let statement: SelectStatement
if let statementCacheName = statementCacheName {
statement = try db.selectStatement(sql, fromCache: statementCacheName)
} else {
switch cache {
case .none:
statement = try db.makeSelectStatement(sql)
case .public?:
statement = try db.cachedSelectStatement(sql)
case .internal?:
statement = try db.internalCachedSelectStatement(sql)
}
if let arguments = arguments {
try statement.setArgumentsWithValidation(arguments)
@@ -179,10 +199,17 @@ public struct SQLRequest : Request {
return (statement, adapter)
}
private let sql: String
private let arguments: StatementArguments?
private let adapter: RowAdapter?
private let statementCacheName: Database.StatementCacheName?
/// There are two statement caches: one for statements generated by the
/// user, and one for the statements generated by GRDB. Those are separated
/// so that GRDB has no opportunity to inadvertently modify the arguments of
/// user's cached statements.
enum Cache {
/// The public cache, for library user
case `public`
/// The internal cache, for grdb
case `internal`
}
}
/// The protocol for requests that know how to decode database rows.
+15 -16
View File
@@ -7,6 +7,21 @@ import Foundation
/// A database row.
public final class Row {
let impl: RowImpl
/// Unless we are producing a row array, we use a single row when iterating
/// a statement:
///
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// let players = try Player.fetchAll(db, "SELECT ...")
///
/// This row keeps an unmanaged reference to the statement, and a handle to
/// the sqlite statement, so that we avoid many retain/release invocations.
///
/// The statementRef is released in deinit.
let statementRef: Unmanaged<SelectStatement>?
let sqliteStatement: SQLiteStatement?
/// The number of columns in the row.
public let count: Int
@@ -51,26 +66,11 @@ public final class Row {
// MARK: - Not Public
let impl: RowImpl
/// Returns true if and only if the row was fetched from a database.
var isFetched: Bool {
return impl.isFetched
}
/// Unless we are producing a row array, we use a single row when iterating
/// a statement:
///
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// let players = try Player.fetchAll(db, "SELECT ...")
///
/// This row keeps an unmanaged reference to the statement, and a handle to
/// the sqlite statement, so that we avoid many retain/release invocations.
///
/// The statementRef is released in deinit.
let statementRef: Unmanaged<SelectStatement>?
let sqliteStatement: SQLiteStatement?
deinit {
statementRef?.release()
}
@@ -830,7 +830,6 @@ extension Row : Hashable {
/// Row adopts CustomStringConvertible.
extension Row: CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return "<Row"
+ map { (column, dbValue) in
+155 -70
View File
@@ -8,6 +8,9 @@ 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 {
}
@@ -25,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.
@@ -42,7 +44,12 @@ public class Statement {
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - throws: DatabaseError in case of compilation error, and
/// EmptyStatementError if the compiled string is blank or empty.
init(database: Database, statementStart: UnsafePointer<Int8>, statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>, prepFlags: Int32) throws {
init(
database: Database,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
prepFlags: Int32) throws
{
SchedulingWatchdog.preconditionValidQueue(database)
var sqliteStatement: SQLiteStatement? = nil
@@ -58,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:
@@ -105,7 +109,7 @@ public class Statement {
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, Int32($0 + 1)) else {
return nil
}
return String(String(cString: cString).characters.dropFirst()) // Drop initial ":", "@", "$"
return String(String(cString: cString).dropFirst()) // Drop initial ":", "@", "$"
}
}()
@@ -135,7 +139,7 @@ public class Statement {
clearBindings()
var valuesIterator = arguments.values.makeIterator()
for (index, argumentName) in sqliteArgumentNames.enumerated() {
for (index, argumentName) in zip(Int32(1)..., sqliteArgumentNames) {
if let argumentName = argumentName, let value = arguments.namedValues[argumentName] {
bind(value, at: index)
} else if let value = valuesIterator.next() {
@@ -156,26 +160,26 @@ public class Statement {
// Apply
reset()
clearBindings()
for (index, dbValue) in bindings.enumerated() {
for (index, dbValue) in zip(Int32(1)..., bindings) {
bind(dbValue, at: index)
}
}
// 0-based index
private func bind(_ dbValue: DatabaseValue, at index: Int) {
// 1-based index
private func bind(_ dbValue: DatabaseValue, at index: Int32) {
let code: Int32
switch dbValue.storage {
case .null:
code = sqlite3_bind_null(sqliteStatement, Int32(index + 1))
code = sqlite3_bind_null(sqliteStatement, index)
case .int64(let int64):
code = sqlite3_bind_int64(sqliteStatement, Int32(index + 1), int64)
code = sqlite3_bind_int64(sqliteStatement, index, int64)
case .double(let double):
code = sqlite3_bind_double(sqliteStatement, Int32(index + 1), double)
code = sqlite3_bind_double(sqliteStatement, index, double)
case .string(let string):
code = sqlite3_bind_text(sqliteStatement, Int32(index + 1), string, -1, SQLITE_TRANSIENT)
code = sqlite3_bind_text(sqliteStatement, index, string, -1, SQLITE_TRANSIENT)
case .blob(let data):
code = data.withUnsafeBytes { bytes in
sqlite3_bind_blob(sqliteStatement, Int32(index + 1), bytes, Int32(data.count), SQLITE_TRANSIENT)
sqlite3_bind_blob(sqliteStatement, index, bytes, Int32(data.count), SQLITE_TRANSIENT)
}
}
@@ -206,15 +210,75 @@ public class Statement {
try! validate(arguments: self.arguments)
}
}
/// Utility function for cursors
func cursorReset(arguments: StatementArguments? = nil) {
SchedulingWatchdog.preconditionValidQueue(database)
prepare(withArguments: arguments)
reset()
}
}
// 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
@@ -227,7 +291,7 @@ public class Statement {
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
/// }
public final class SelectStatement : Statement {
public final class SelectStatement : Statement, AuthorizedStatement {
/// Information about the table and columns read by a SelectStatement
public private(set) var selectionInfo: SelectionInfo
@@ -243,29 +307,38 @@ public final class SelectStatement : Statement {
/// - authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error, and
/// EmptyStatementError if the compiled string is blank or empty.
init(database: Database, statementStart: UnsafePointer<Int8>, statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>, prepFlags: Int32, authorizer: StatementCompilationAuthorizer) throws {
init(
database: Database,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
{
self.selectionInfo = SelectionInfo()
try super.init(
database: database,
statementStart: statementStart,
statementEnd: statementEnd,
prepFlags: prepFlags)
Database.preconditionValidSelectStatement(sql: sql, authorizer: authorizer)
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
}
/// The number of columns in the resulting rows.
public lazy var columnCount: Int = {
Int(sqlite3_column_count(self.sqliteStatement))
}()
public var columnCount: Int {
return Int(sqlite3_column_count(self.sqliteStatement))
}
/// The column names, ordered from left to right.
public lazy var columnNames: [String] = {
let sqliteStatement = self.sqliteStatement
return (0..<self.columnCount).map { (index: Int) -> String in String(cString: sqlite3_column_name(sqliteStatement, Int32(index))) }
return (0..<Int32(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
}()
/// Cache for indexOfColumn(). Keys are lowercase.
/// Cache for index(ofColumn:). Keys are lowercase.
private lazy var columnIndexes: [String: Int] = {
return Dictionary(
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
@@ -284,9 +357,31 @@ public final class SelectStatement : Statement {
func cursor(arguments: StatementArguments? = nil) -> StatementCursor {
return StatementCursor(statement: self, arguments: arguments)
}
/// Utility function for cursors
func cursorReset(arguments: StatementArguments? = nil) {
SchedulingWatchdog.preconditionValidQueue(database)
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)
}
@@ -311,24 +406,10 @@ public final class SelectStatement : Statement {
self.init(isUnknown: false)
}
static func unknown() -> SelectionInfo {
return self.init(isUnknown: true)
}
/// If true, selection is unknown
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> = []
private init(isUnknown: Bool) {
self.isUnknown = isUnknown
}
/// A textual representation of `self`.
public var description: String {
if isUnknown {
return "unknown"
@@ -394,22 +475,14 @@ public final class StatementCursor: Cursor {
/// try statement.execute(arguments: ["Barbara"])
/// return .commit
/// }
public final class UpdateStatement : Statement {
enum TransactionStatementInfo {
enum SavepointAction : String {
case begin = "BEGIN"
case release = "RELEASE"
case rollback = "ROLLBACK"
}
enum TransactionAction : String {
case begin = "BEGIN"
case commit = "COMMIT"
case rollback = "ROLLBACK"
}
case transaction(action: TransactionAction)
case savepoint(name: String, action: SavepointAction)
public final class UpdateStatement : Statement, AuthorizedStatement {
enum TransactionEffect {
case beginTransaction
case commitTransaction
case rollbackTransaction
case beginSavepoint(String)
case releaseSavepoint(String)
case rollbackSavepoint(String)
}
/// If true, the database schema cache gets invalidated after this statement
@@ -420,7 +493,7 @@ public final class UpdateStatement : Statement {
/// when executed
private(set) var needsTruncateOptimizationPreventionDuringExecution: Bool
private(set) var transactionStatementInfo: TransactionStatementInfo?
private(set) var transactionEffect: TransactionEffect?
private(set) var databaseEventKinds: [DatabaseEventKind]
/// Creates a prepared statement.
@@ -435,7 +508,13 @@ public final class UpdateStatement : Statement {
/// - authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error, and
/// EmptyStatementError if the compiled string is blank or empty.
init(database: Database, statementStart: UnsafePointer<Int8>, statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>, prepFlags: Int32, authorizer: StatementCompilationAuthorizer) throws {
init(
database: Database,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
{
self.invalidatesDatabaseSchemaCache = false
self.needsTruncateOptimizationPreventionDuringExecution = false
self.databaseEventKinds = []
@@ -446,7 +525,7 @@ public final class UpdateStatement : Statement {
prepFlags: prepFlags)
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
self.needsTruncateOptimizationPreventionDuringExecution = authorizer.needsTruncateOptimizationPreventionDuringExecution
self.transactionStatementInfo = authorizer.transactionStatementInfo
self.transactionEffect = authorizer.transactionEffect
self.databaseEventKinds = authorizer.databaseEventKinds
}
@@ -487,7 +566,7 @@ public final class UpdateStatement : Statement {
case SQLITE_DONE:
database.authorizer = nil
database.updateStatementDidExecute(self)
try database.updateStatementDidExecute(self)
return
case let code:
@@ -574,6 +653,8 @@ public final class UpdateStatement : Statement {
/// print(row)
/// // Prints <Row two:2 foo:"foo" one:1 foo2:"foo" bar:"bar">
public struct StatementArguments {
var values: [DatabaseValue] = []
var namedValues: [String: DatabaseValue] = [:]
public var isEmpty: Bool {
return values.isEmpty && namedValues.isEmpty
@@ -831,9 +912,6 @@ public struct StatementArguments {
// MARK: Not Public
var values: [DatabaseValue] = []
var namedValues: [String: DatabaseValue] = [:]
mutating func consume(_ statement: Statement, allowingRemainingValues: Bool) throws -> [DatabaseValue] {
let initialValuesCount = values.count
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
@@ -879,7 +957,6 @@ extension StatementArguments : ExpressibleByDictionaryLiteral {
}
extension StatementArguments : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
let valuesDescriptions = values.map { $0.description }
let namedValuesDescriptions = namedValues.map { (key, value) -> String in
@@ -889,6 +966,14 @@ extension StatementArguments : CustomStringConvertible {
}
}
extension StatementArguments : Equatable {
public static func == (lhs: StatementArguments, rhs: StatementArguments) -> Bool {
if lhs.values != rhs.values { return false }
if lhs.namedValues != rhs.namedValues { return false }
return true
}
}
/// A thread-unsafe statement cache
struct StatementCache {
unowned let db: Database
+180
View File
@@ -0,0 +1,180 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A protocol around sqlite3_set_authorizer
protocol StatementAuthorizer : class {
func authorize(
_ actionCode: Int32,
_ cString1: UnsafePointer<Int8>?,
_ cString2: UnsafePointer<Int8>?,
_ cString3: UnsafePointer<Int8>?,
_ cString4: UnsafePointer<Int8>?)
-> Int32
}
/// A class that gathers information about one statement during its compilation.
final class StatementCompilationAuthorizer : StatementAuthorizer {
/// What this statements reads
var selectionInfo = SelectStatement.SelectionInfo()
/// What this statements writes
var databaseEventKinds: [DatabaseEventKind] = []
/// True if a statement alter the schema in a way that required schema cache
/// invalidation. For example, adding a column to a table invalidates the
/// schema cache, but not creating a table.
var invalidatesDatabaseSchemaCache = false
/// Not nil if a statement is a BEGIN/COMMIT/ROLLBACK/RELEASE transaction or
/// savepoint statement.
var transactionEffect: UpdateStatement.TransactionEffect?
/// True if statement may trigger the truncate optimization
var needsTruncateOptimizationPreventionDuringExecution = false
private var isDropStatement = false
func authorize(
_ actionCode: Int32,
_ cString1: UnsafePointer<Int8>?,
_ cString2: UnsafePointer<Int8>?,
_ cString3: UnsafePointer<Int8>?,
_ cString4: UnsafePointer<Int8>?)
-> Int32
{
// print("StatementCompilationAuthorizer: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
switch actionCode {
case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE,
SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX:
isDropStatement = true
invalidatesDatabaseSchemaCache = true
return SQLITE_OK
case SQLITE_DROP_VIEW, SQLITE_DROP_TEMP_VIEW,
SQLITE_DROP_TRIGGER, SQLITE_CREATE_TEMP_TRIGGER:
isDropStatement = true
return SQLITE_OK
case SQLITE_DETACH, SQLITE_ALTER_TABLE,
SQLITE_CREATE_INDEX, SQLITE_CREATE_TEMP_INDEX:
invalidatesDatabaseSchemaCache = true
return SQLITE_OK
case SQLITE_READ:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
if columnName.isEmpty {
// SELECT COUNT(*) FROM table
selectionInfo.insert(allColumnsOfTable: tableName)
} else {
// SELECT column FROM table
selectionInfo.insert(column: columnName, ofTable: tableName)
}
return SQLITE_OK
case SQLITE_INSERT:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
databaseEventKinds.append(.insert(tableName: tableName))
return SQLITE_OK
case SQLITE_DELETE:
if isDropStatement { return SQLITE_OK }
guard let cString1 = cString1 else { return SQLITE_OK }
guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK }
guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK }
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:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
insertUpdateEventKind(tableName: tableName, columnName: columnName)
return SQLITE_OK
case SQLITE_TRANSACTION:
guard let cString1 = cString1 else { return SQLITE_OK }
if strcmp(cString1, "BEGIN") == 0 {
transactionEffect = .beginTransaction
} else if strcmp(cString1, "COMMIT") == 0 {
transactionEffect = .commitTransaction
} else if strcmp(cString1, "ROLLBACK") == 0 {
transactionEffect = .rollbackTransaction
}
return SQLITE_OK
case SQLITE_SAVEPOINT:
guard let cString1 = cString1 else { return SQLITE_OK }
guard let name = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
if strcmp(cString1, "BEGIN") == 0 {
transactionEffect = .beginSavepoint(name)
} else if strcmp(cString1, "RELEASE") == 0 {
transactionEffect = .releaseSavepoint(name)
} else if strcmp(cString1, "ROLLBACK") == 0 {
transactionEffect = .rollbackSavepoint(name)
}
return SQLITE_OK
case SQLITE_FUNCTION:
// Starting SQLite 3.19.0, `SELECT COUNT(*) FROM table` triggers
// an authorization callback for SQLITE_READ with an empty
// column: http://www.sqlite.org/changes.html#version_3_19_0
//
// 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.
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
}
return SQLITE_OK
default:
return SQLITE_OK
}
}
func insertUpdateEventKind(tableName: String, columnName: String) {
for (index, eventKind) in databaseEventKinds.enumerated() {
if case .update(let t, let columnNames) = eventKind, t == tableName {
var columnNames = columnNames
columnNames.insert(columnName)
databaseEventKinds[index] = .update(tableName: tableName, columnNames: columnNames)
return
}
}
databaseEventKinds.append(.update(tableName: tableName, columnNames: [columnName]))
}
}
/// This authorizer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
/// 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.
final class TruncateOptimizationBlocker : StatementAuthorizer {
func authorize(
_ actionCode: Int32,
_ cString1: UnsafePointer<Int8>?,
_ cString2: UnsafePointer<Int8>?,
_ cString3: UnsafePointer<Int8>?,
_ cString4: UnsafePointer<Int8>?)
-> Int32
{
// print("TruncateOptimizationBlocker: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK
}
}
File diff suppressed because it is too large. Load diff
+16 -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;
""")
@@ -313,3 +313,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
+1 -1
View File
@@ -38,7 +38,7 @@
extension Database {
// MARK: - Custom FTS5 Tokenizers
// MARK: - FTS5
private class FTS5TokenizerConstructor {
let db: Database
+2
View File
@@ -77,6 +77,8 @@
extension Database {
// MARK: - FTS5
/// Creates a pattern from a raw pattern string; throws DatabaseError on
/// invalid syntax.
///
+2 -1
View File
@@ -106,8 +106,9 @@
}
extension Database {
/// MARK: - FTS5 Tokenizers
// MARK: - FTS5
/// Private type that makes a pre-registered FTS5 tokenizer available
/// through the FTS5Tokenizer protocol.
private final class FTS5RegisteredTokenizer : FTS5Tokenizer {
@@ -462,9 +462,8 @@ struct SQLExpressionCollate : SQLExpression {
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
let sql = expression.expressionSQL(&arguments)
let chars = sql.characters
if chars.last! == ")" {
return String(chars.prefix(upTo: chars.index(chars.endIndex, offsetBy: -1))) + " COLLATE " + collationName.rawValue + ")"
if sql.last! == ")" {
return String(sql.prefix(upTo: sql.index(sql.endIndex, offsetBy: -1))) + " COLLATE " + collationName.rawValue + ")"
} else {
return sql + " COLLATE " + collationName.rawValue
}
+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
+1 -1
View File
@@ -39,7 +39,7 @@ public protocol VirtualTableModule {
extension Database {
// MARK: - Database Schema: Virtual Table
// MARK: - Database Schema
/// Creates a virtual database table.
///
@@ -1004,8 +1004,6 @@ public enum FetchedRecordChange {
}
extension FetchedRecordChange: CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
switch self {
case .insertion(let indexPath):
+21 -2
View File
@@ -28,7 +28,6 @@ private struct PersistableKeyedEncodingContainer<Key: CodingKey> : KeyedEncoding
mutating func encode(_ value: Float, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Double, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: String, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encodeNil(forKey key: Key) throws { encode(nil, key.stringValue) }
/// Encodes the given value for the given key.
///
@@ -45,6 +44,24 @@ private struct PersistableKeyedEncodingContainer<Key: CodingKey> : KeyedEncoding
}
}
// Provide explicit encoding of optionals, because default implementation does not encode nil values.
mutating func encodeNil(forKey key: Key) throws { encode(nil, key.stringValue) }
mutating func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Float?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: Double?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent(_ value: String?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
mutating func encodeIfPresent<T>(_ value: T?, forKey key: Key) throws where T : Encodable { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
/// Stores a keyed encoding container for the given key and returns it.
///
/// - parameter keyType: The key type to use for the container.
@@ -189,6 +206,8 @@ extension MutablePersistable where Self: Encodable {
try! self.encode(to: encoder)
}
}
encode { (value, key) in container[key] = value }
encode { (value, key) in
container[key] = value
}
}
}
+4 -5
View File
@@ -21,7 +21,6 @@ public enum PersistenceError: Error {
}
extension PersistenceError : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
switch self {
case .recordNotFound(let persistable):
@@ -824,7 +823,7 @@ final class DAO {
onConflict: onConflict,
tableName: databaseTableName,
insertedColumns: persistenceContainer.columns)
let statement = try db.updateStatement(query.sql, fromCache: .grdb)
let statement = try db.internalCachedUpdateStatement(query.sql)
statement.unsafeSetArguments(StatementArguments(persistenceContainer.values))
return statement
}
@@ -870,7 +869,7 @@ final class DAO {
tableName: databaseTableName,
updatedColumns: updatedColumns,
conditionColumns: primaryKeyColumns)
let statement = try db.updateStatement(query.sql, fromCache: .grdb)
let statement = try db.internalCachedUpdateStatement(query.sql)
statement.unsafeSetArguments(StatementArguments(updatedValues + primaryKeyValues))
return statement
}
@@ -887,7 +886,7 @@ final class DAO {
let query = DeleteQuery(
tableName: databaseTableName,
conditionColumns: primaryKeyColumns)
let statement = try db.updateStatement(query.sql, fromCache: .grdb)
let statement = try db.internalCachedUpdateStatement(query.sql)
statement.unsafeSetArguments(StatementArguments(primaryKeyValues))
return statement
}
@@ -904,7 +903,7 @@ final class DAO {
let query = ExistsQuery(
tableName: databaseTableName,
conditionColumns: primaryKeyColumns)
let statement = try db.selectStatement(query.sql, fromCache: .grdb)
let statement = try db.internalCachedSelectStatement(query.sql)
statement.unsafeSetArguments(StatementArguments(primaryKeyValues))
return statement
}
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDBCipher'
s.version = '2.0.2'
s.version = '2.4.2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
+3091
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">
+2446
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>
@@ -36,7 +50,7 @@
BlueprintIdentifier = "F3BA80401CFB2AD7003DC1BA"
BuildableName = "GRDBCustomSQLiteiOSTests.xctest"
BlueprintName = "GRDBCustomSQLiteiOSTests"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCustom.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
@@ -46,7 +60,7 @@
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteiOS"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCustom.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
@@ -69,7 +83,7 @@
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteiOS"
ReferencedContainer = "container:GRDB.xcodeproj">
ReferencedContainer = "container:GRDBCustom.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
@@ -87,7 +101,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:
+24 -13
View File
@@ -46,8 +46,11 @@ 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)
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)
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0"
else
# Xcode < 9.0 is not supported
@@ -127,7 +130,7 @@ test_framework_GRDBiOS_minTarget:
test_framework_GRDBCustomSQLiteOSX: SQLiteCustom
$(XCODEBUILD) \
-project GRDB.xcodeproj \
-project GRDBCustom.xcodeproj \
-scheme GRDBCustomSQLiteOSX \
$(TEST_ACTIONS) \
$(XCPRETTY)
@@ -136,7 +139,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 +147,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 +155,7 @@ test_framework_GRDBCustomSQLiteiOS_minTarget: SQLiteCustom
test_framework_GRDBCipherOSX: SQLCipher
$(XCODEBUILD) \
-project GRDB.xcodeproj \
-project GRDBCipher.xcodeproj \
-scheme GRDBCipherOSX \
$(TEST_ACTIONS) \
$(XCPRETTY)
@@ -161,7 +164,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 +172,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
@@ -222,6 +226,13 @@ test_CarthageBuild: SQLiteCustom SQLCipher
ifdef CARTHAGE
rm -rf Carthage
$(CARTHAGE) build --no-skip-current
$(XCODEBUILD) \
-project Tests/Carthage/GRDBiOS/iOS.xcodeproj \
-scheme iOS \
-configuration Release \
-destination $(MAX_IOS_DESTINATION) \
clean build \
$(XCPRETTY)
else
@echo Carthage must be installed for test_CarthageBuild
@exit 1
@@ -233,10 +244,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
@@ -285,10 +296,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.0 \
--module-version 2.0 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v2.4.2 \
--module-version 2.4 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/2.0/ \
--root-url http://groue.github.io/GRDB.swift/docs/2.4/ \
--output Documentation/Reference \
--podspec GRDB.swift.podspec
else
+265 -99
View File
@@ -1,9 +1,9 @@
GRDB 2.0 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](https://developer.apple.com/swift/) [![Platforms](https://img.shields.io/cocoapods/p/GRDB.swift.svg)](https://developer.apple.com/swift/) [![License](https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000)](/LICENSE) [![Build Status](https://travis-ci.org/groue/GRDB.swift.svg?branch=master)](https://travis-ci.org/groue/GRDB.swift)
GRDB 2 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](https://developer.apple.com/swift/) [![Platforms](https://img.shields.io/cocoapods/p/GRDB.swift.svg)](https://developer.apple.com/swift/) [![License](https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000)](/LICENSE) [![Build Status](https://travis-ci.org/groue/GRDB.swift.svg?branch=master)](https://travis-ci.org/groue/GRDB.swift)
==========
### A toolkit for SQLite databases, with a focus on application development
**Latest release**: October 5, 2017 • version 2.0.2 • [CHANGELOG](CHANGELOG.md)
**Latest release**: January 5, 2018 • version 2.4.2 • [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.0 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](
| 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.0.2** |
| **Swift 4** | **v2.4.2** |
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.0/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/2.4/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.0.
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.0.2")
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.4.2")
]
)
```
@@ -275,14 +275,14 @@ Note that Linux is not currently supported.
## Carthage
Carthage does not support the variety of frameworks built by GRDB (standard SQLite, custom SQLite, SQLCipher).
Carthage can build GRDB frameworks, but it can also inexplicably fail. This installation method is thus *unsupported*.
Any pull request that has the `make test_CarthageBuild` command successfully complete will be greatly appreciated, though. Bring your local Xcode guru!
If you decide to use Carthage despite this warning, and get any Carthage-related error, please open an issue in the [Carthage repo](https://github.com/Carthage/Carthage/issues), ask [Stack Overflow](http://stackoverflow.com), summon your local Xcode guru, or submit a pull request that has the `make test_CarthageBuild` command succeed 100% of the time (one time is not enough). See [#262](https://github.com/groue/GRDB.swift/pull/262) for more information.
## Manually
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.0.2) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.0.2` command.
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.4.2) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.4.2` command.
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.0/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.4/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.0/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.4/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.0/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.4/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.0/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.4/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift. As such, cursors come with many methods: `contains`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `map`, `reduce`:
```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.0/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.4/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:
@@ -933,7 +933,7 @@ for (columnName, dbValue) in row { ... } // ("foo", 1), ("foo", 2)
- A `[String: DatabaseValue]` dictionary that keeps leftmost value in case of duplicated column name:
```swift
let dict = Dictionary(row, uniquingKeysWith: { $0 })
let dict = Dictionary(row, uniquingKeysWith: { (left, _) in left })
```
- A `[String: AnyObject]` dictionary which keeps rightmost value in case of duplicated column name. This dictionary is identical to FMResultSet's resultDictionary from FMDB. It contains NSNull values for null columns, and can be shared with Objective-C:
@@ -943,7 +943,7 @@ for (columnName, dbValue) in row { ... } // ("foo", 1), ("foo", 2)
row.map { (column, dbValue) in
(column, dbValue.storage.value as AnyObject)
},
uniquingKeysWith: { $1 })
uniquingKeysWith: { (_, right) in right })
```
- A `[String: Any]` dictionary that can feed, for example, JSONSerialization:
@@ -953,7 +953,7 @@ for (columnName, dbValue) in row { ... } // ("foo", 1), ("foo", 2)
row.map { (column, dbValue) in
(column, dbValue.storage.value)
},
uniquingKeysWith: { $0 })
uniquingKeysWith: { (left, _) in left })
```
See the documentation of [`Dictionary.init(_:uniquingKeysWith:)`](https://developer.apple.com/documentation/swift/dictionary/2892961-init) for more information.
@@ -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.0/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/2.4/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.0/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.4/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.0/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.4/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters:
### 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.0/Structs/Configuration.html)
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/2.0/Classes/Database.html)
- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.4/Structs/Configuration.html)
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/2.4/Classes/Database.html)
- `sqlite3_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.0/Classes/Statement.html)
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/2.0/Structs/Configuration.html)
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/2.0/Classes/DatabasePool.html)
- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/2.4/Classes/Statement.html)
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/2.4/Structs/Configuration.html)
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/2.4/Classes/DatabasePool.html)
Records
@@ -1840,14 +1840,12 @@ Your custom structs and classes can adopt each protocol individually, and opt in
- [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)
- [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key)
- **[List of Record Methods](#list-of-record-methods)**
**Records, Swift Archival & Serialization**
- [Codable Records](#codable-records)
- [List of Record Methods](#list-of-record-methods)
- [The Query Interface](#the-query-interface)
### Inserting Records
@@ -1944,13 +1942,15 @@ let playerWithEmailCount = try Player.filter(emailColumn != nil).fetchCount(db)
```
You can now jump to:
Details follow:
- [Record Protocols Overview](#record-protocols-overview)
- [RowConvertible Protocol](#rowconvertible-protocol)
- [TableMapping Protocol](#tablemapping-protocol)
- [Persistable Protocol](#persistable-protocol)
- [Codable Records](#codable-records)
- [Record Class](#record-class)
- [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key)
- [List of Record Methods](#list-of-record-methods)
- [The Query Interface](#the-query-interface)
@@ -2125,7 +2125,7 @@ try Place.fetchAll(db, "SELECT ...", arguments:...) // [Place]
try Place.fetchOne(db, "SELECT ...", arguments:...) // Place?
```
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.0/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.4/Structs/StatementArguments.html) for more information about the query arguments.
## TableMapping Protocol
@@ -2432,13 +2432,106 @@ 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
// 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, and provides the full toolkit in one go: fetching and persistence methods, as well as changes tracking (see the [list of record methods](#list-of-record-methods) for an overview).
**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 inherit their features from the [RowConvertible, TableMapping, and Persistable](#record-protocols-overview) protocols. Check their documentation for more information.
For example, here is a fully functional Record subclass:
Record subclasses define their custom database relationship by overriding database methods:
```swift
class Place : Record {
@@ -2469,7 +2562,7 @@ class Place : Record {
container["longitude"] = coordinate.longitude
}
/// Update record ID after a successful insertion
/// When relevant, update record ID after a successful insertion
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
@@ -2479,7 +2572,7 @@ class Place : Record {
### Changes Tracking
**The [Record](#record-class) class provides 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.
@@ -2721,31 +2814,6 @@ let player = try Player.fetchOne(statement, arguments: [1]) // Player?
```
## 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)
}
```
> :point_up: **Note**: Some types 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.
The Query Interface
===================
@@ -3121,7 +3189,7 @@ Player // SELECT * FROM players
```
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.0/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM players WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -3590,9 +3658,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.0/Structs/SQLRequest.html): a Request built from raw SQL
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/2.0/Structs/AnyRequest.html): a type-erased Request
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/2.0/Structs/AnyTypedRequest.html): a type-erased TypedRequest
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.4/Structs/SQLRequest.html): a Request built from raw SQL
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/2.4/Structs/AnyRequest.html): a type-erased Request
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/2.4/Structs/AnyTypedRequest.html): a type-erased TypedRequest
Use the `asRequest(of:)` method to define the type fetched by the request:
@@ -4022,7 +4090,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.0/Structs/StatementArguments.html):
FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -4235,7 +4303,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.0/Structs/StatementArguments.html):
FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -4295,13 +4363,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.
@@ -4555,6 +4659,7 @@ do {
>
> :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.
[FetchedRecordsController](#fetchedrecordscontroller) and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) are based on the TransactionObserver protocol.
See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd), which shows a transaction observer that notifies of modified database tables with NSNotificationCenter.
@@ -4657,7 +4762,7 @@ dbQueue.inDatabase { db in
#### Support for SQLite Pre-Update Hooks
A [custom SQLite build](Documentation/CustomSQLiteBuilds.md) can activate [SQLite "preupdate hooks"](http://www.sqlite.org/sessions/c3ref/preupdate_count.html). In this case, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
A [custom SQLite build](Documentation/CustomSQLiteBuilds.md) can activate [SQLite "preupdate hooks"](https://sqlite.org/c3ref/preupdate_count.html). In this case, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
```swift
protocol TransactionObserverType : class {
@@ -4797,6 +4902,8 @@ controller.trackChanges { controller in
}
```
> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information.
Callbacks have the fetched record controller itself as an argument: use it in order to avoid memory leaks:
```swift
@@ -4969,7 +5076,9 @@ controller.trackChanges(
})
```
See [GRDBDemoiOS](DemoApps/GRDBDemoiOS/GRDBDemoiOS) for an sample app that uses FetchedRecordsController.
> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information.
See [GRDBDemoiOS](DemoApps/GRDBDemoiOS/GRDBDemoiOS) for an sample app that uses FetchedRecordsController to animate a table view.
> :point_up: **Note**: our sample code above uses `unowned` references to the table view controller. This is a safe pattern as long as the table view controller owns the fetched records controller, and is deallocated from the main thread (this is usually the case). In other situations, prefer weak references.
@@ -5021,11 +5130,11 @@ Alternatively, perform a manual installation of GRDB and SQLCipher:
```sh
cd [GRDB directory]
git checkout v2.0.2
git checkout v2.4.2
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.
@@ -5128,7 +5237,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.0/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.4/Structs/StatementArguments.html) to your SQL queries:
```swift
// Good
@@ -5357,7 +5466,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
@@ -5365,6 +5474,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.
@@ -5489,24 +5600,25 @@ For example, to explicitely use [complete](https://developer.apple.com/reference
```swift
// Paths
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let directoryPath = (documentsPath as NSString).appendingPathComponent("database")
let databasePath = (directoryPath as NSString).appendingPathComponent("db.sqlite")
let fileManager = FileManager.default
let directoryURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
// Create directory if needed
let fm = FileManager.default
var isDirectory: ObjCBool = false
if !fm.fileExists(atPath: directoryPath, isDirectory: &isDirectory) {
try fm.createDirectory(atPath: directoryPath, withIntermediateDirectories: false)
if !fileManager.fileExists(atPath: directoryURL.path, isDirectory: &isDirectory) {
try fileManager.createDirectory(atPath: directoryURL.path, withIntermediateDirectories: false)
} else if !isDirectory.boolValue {
throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteFileExistsError, userInfo: nil)
}
// Enable data protection
try fm.setAttributes([.protectionKey : FileProtectionType.complete], ofItemAtPath: directoryPath)
try fileManager.setAttributes([.protectionKey : FileProtectionType.complete], ofItemAtPath: directoryURL.path)
// Open database
let dbQueue = try DatabaseQueue(path: databasePath)
let dbQueue = try DatabaseQueue(path: databaseURL.path)
```
When a database is protected, an application that runs in the background on a locked device won't be able to read or write from it. Instead, it will get [DatabaseError](#error-handling) with code [`SQLITE_IOERR`](https://www.sqlite.org/rescode.html#ioerr) (10) "disk I/O error", or [`SQLITE_AUTH`](https://www.sqlite.org/rescode.html#auth) (23) "not authorized".
@@ -5706,7 +5818,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.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.0/Protocols/DatabaseWriter.html) protocols.
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/DatabaseWriter.html) protocols.
These protocols provide a unified API that lets you write safe concurrent code that targets both classes.
@@ -5714,7 +5826,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.0/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.
@@ -5801,7 +5912,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.0/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.4/Structs/Configuration.html)
- [Ask questions](https://github.com/groue/GRDB.swift/issues)
@@ -6040,18 +6151,27 @@ for player in players {
FAQ
===
- [How do I close a database connection?](#how-do-i-close-a-database-connection)
- [How do I create a database in my application?](#how-do-i-create-a-database-in-my-application)
- [How do I open a database stored as a resource of my application?](#how-do-i-open-a-database-stored-as-a-resource-of-my-application)
- [How do I close a database connection?](#how-do-i-close-a-database-connection)
- [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql)
- [Generic parameter 'T' could not be inferred](#generic-parameter-t-could-not-be-inferred)
- [SQLite error 10 "disk I/O error", SQLite error 23 "not authorized"](#sqlite-error-10-disk-io-error-sqlite-error-23-not-authorized)
- [What Are Experimental Features?](#what-are-experimental-features)
### How do I close a database connection?
Database connections are managed by [database queues](#database-queues) and [pools](#database-pools). A connection is closed when its database queue or pool is deallocated, and all usages of this connection are completed.
### How do I create a database in my application?
Database accesses that run in background threads postpone the closing of connections.
This question assumes that your application has to create a new database from scratch. If your app has to open an existing database that is embedded inside your application as a resource, see [How do I open a database stored as a resource of my application?](#how-do-i-open-a-database-stored-as-a-resource-of-my-application) instead.
The database has to be stored in a valid place where it can be created and modified. For example, in the [Application Support directory](https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html):
```swift
let databaseURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
let dbQueue = try DatabaseQueue(path: databaseURL.path)
```
### How do I open a database stored as a resource of my application?
@@ -6065,20 +6185,66 @@ let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite")!
let dbQueue = try DatabaseQueue(path: dbPath, configuration: configuration)
```
If the application should modify the database, you need to copy it to a place where it can be modified. For example, in the Documents folder. Only then, open a [connection](#database-connections):
If the application should modify the database, you need to copy it to a place where it can be modified. For example, in the [Application Support directory](https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html). Only then, open a [connection](#database-connections):
```swift
let fm = FileManager.default
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let dbPath = (documentsPath as NSString).appendingPathComponent("db.sqlite")
if !fm.fileExists(atPath: dbPath) {
let fileManager = FileManager.default
let dbPath = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
.path
if !fileManager.fileExists(atPath: dbPath) {
let dbResourcePath = Bundle.main.path(forResource: "db", ofType: "sqlite")!
try fm.copyItem(atPath: dbResourcePath, toPath: dbPath)
try fileManager.copyItem(atPath: dbResourcePath, toPath: dbPath)
}
let dbQueue = try DatabaseQueue(path: dbPath)
```
### How do I close a database connection?
Database connections are managed by [database queues](#database-queues) and [pools](#database-pools). A connection is closed when its database queue or pool is deallocated, and all usages of this connection are completed.
Database accesses that run in background threads postpone the closing of connections.
### How do I print a request as SQL?
When you want to debug a request that does not deliver the expected results, you may want to print the SQL that is actually executed.
Use the `asSQLRequest` method:
```swift
try dbQueue.inDatabase { db in
let request = Wine
.filter(Column("origin") == "Burgundy")
.order(Column("price")
let sqlRequest = try request.asSQLRequest(db)
print(sqlRequest.sql)
// Prints SELECT * FROM wines WHERE origin = ? ORDER BY price
print(sqlRequest.arguments)
// Prints ["Burgundy"]
}
```
Another option is to setup a tracing function that will print out all SQL requests executed by your application. You provide the trace function when you connect to the database:
```swift
var config = Configuration()
config.trace = { print("SQL: \($0)") } // Prints all SQL statements
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
try dbQueue.inDatabase { db in
let wines = Wine
.filter(Column("origin") == "Burgundy")
.order(Column("price")
.fetchAll(db)
// Prints SELECT * FROM wines WHERE origin = 'Burgundy' ORDER BY price
}
```
### Generic parameter 'T' could not be inferred
You may get this error when using DatabaseQueue.inDatabase, DatabasePool.read, or DatabasePool.write:
@@ -6146,6 +6312,6 @@ Sample Code
**Thanks**
- [Pierlis](http://pierlis.com), where we write great software.
- [Vladimir Babin](https://github.com/Chiliec), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [David Hart](https://github.com/hartbit), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy) [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB.
- [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [David Hart](https://github.com/hartbit), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy) [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB.
- [@aymerick](https://github.com/aymerick) and [Mathieu "Kali" Poumeyrol](https://github.com/kali) because SQL.
- [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency.
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.0.2</string>
<string>2.4.2</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+5 -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
@@ -13,14 +11,14 @@
- [ ] 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
GRDB 2.0
GRDB 3.0
- [ ] Document Record.updateChanges(_:)
- [ ] WIP on diff algorithms in RxGRDB needs access to MutablePersistable.databaseDictionary. The problem is that one should not need a writing protocol just to read. So consider introducing a new DatabaseEncodable protocol above MutablePersistable. It does not grant any writing methods. But it has encode(to:) and databaseDictionary.
- [ ] 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:
@@ -62,14 +60,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:
@@ -97,3 +87,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)
+6 -6
View File
@@ -14,7 +14,7 @@
567374481B4D46600089DE44 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567374461B4D46600089DE44 /* LaunchScreen.storyboard */; };
568E2B991CACE4ED00426E7B /* SimplePersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E2B981CACE4ED00426E7B /* SimplePersonsViewController.swift */; };
56AEC9D91CAA985700452D96 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D21CAA985700452D96 /* AppDelegate.swift */; };
56AEC9DA1CAA985700452D96 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D31CAA985700452D96 /* Database.swift */; };
56AEC9DA1CAA985700452D96 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D31CAA985700452D96 /* AppDatabase.swift */; };
56AEC9DB1CAA985700452D96 /* DemoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D41CAA985700452D96 /* DemoViewController.swift */; };
56AEC9DD1CAA985700452D96 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D61CAA985700452D96 /* Person.swift */; };
56AEC9DE1CAA985700452D96 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D71CAA985700452D96 /* PersonEditionViewController.swift */; };
@@ -44,7 +44,7 @@
567374491B4D46600089DE44 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
568E2B981CACE4ED00426E7B /* SimplePersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimplePersonsViewController.swift; sourceTree = "<group>"; };
56AEC9D21CAA985700452D96 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
56AEC9D31CAA985700452D96 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
56AEC9D31CAA985700452D96 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
56AEC9D41CAA985700452D96 /* DemoViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DemoViewController.swift; sourceTree = "<group>"; };
56AEC9D61CAA985700452D96 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = "<group>"; };
56AEC9D71CAA985700452D96 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = "<group>"; };
@@ -85,7 +85,7 @@
children = (
56AEC9D21CAA985700452D96 /* AppDelegate.swift */,
567374441B4D46600089DE44 /* Assets.xcassets */,
56AEC9D31CAA985700452D96 /* Database.swift */,
56AEC9D31CAA985700452D96 /* AppDatabase.swift */,
56AEC9D41CAA985700452D96 /* DemoViewController.swift */,
567374491B4D46600089DE44 /* Info.plist */,
567374461B4D46600089DE44 /* LaunchScreen.storyboard */,
@@ -193,7 +193,7 @@
56AEC9DD1CAA985700452D96 /* Person.swift in Sources */,
56AEC9DF1CAA985700452D96 /* PersonsViewController.swift in Sources */,
56AEC9DB1CAA985700452D96 /* DemoViewController.swift in Sources */,
56AEC9DA1CAA985700452D96 /* Database.swift in Sources */,
56AEC9DA1CAA985700452D96 /* AppDatabase.swift in Sources */,
568E2B991CACE4ED00426E7B /* SimplePersonsViewController.swift in Sources */,
56AEC9DE1CAA985700452D96 /* PersonEditionViewController.swift in Sources */,
56AEC9D91CAA985700452D96 /* AppDelegate.swift in Sources */,
@@ -263,7 +263,7 @@
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
SWIFT_VERSION = 4.0;
};
name = Debug;
};
@@ -300,7 +300,7 @@
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_VERSION = 3.0;
SWIFT_VERSION = 4.0;
VALIDATE_PRODUCT = YES;
};
name = Release;
@@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "567374371B4D46600089DE44"
BuildableName = "iOS.app"
BlueprintName = "iOS"
ReferencedContainer = "container:iOS.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "567374371B4D46600089DE44"
BuildableName = "iOS.app"
BlueprintName = "iOS"
ReferencedContainer = "container:iOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
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">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "567374371B4D46600089DE44"
BuildableName = "iOS.app"
BlueprintName = "iOS"
ReferencedContainer = "container:iOS.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "567374371B4D46600089DE44"
BuildableName = "iOS.app"
BlueprintName = "iOS"
ReferencedContainer = "container:iOS.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -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"
@@ -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,23 +60,39 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
}
}
XCTAssertNotNil(deallocationWitness)
XCTAssertEqual(transactionCount, 0)
try db.inTransaction { .commit }
XCTAssertEqual(transactionCount, 1)
try db.execute(startSQL)
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 { .commit }
XCTAssertEqual(transactionCount, 1)
try db.inTransaction {
try db.execute("DROP TABLE IF EXISTS t; CREATE TABLE t(a); ")
return .commit
}
switch expectedCompletion {
case .commit:
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
case .rollback:
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
}
}
}
func testDatabaseAfterNextTransactionCommitWithRollback() 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()
@@ -54,14 +104,27 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
}
}
XCTAssertNotNil(deallocationWitness)
XCTAssertEqual(transactionCount, 0)
try db.inTransaction { .rollback }
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 { .commit }
XCTAssertEqual(transactionCount, 0)
try db.inTransaction {
try db.execute("DROP TABLE IF EXISTS t; CREATE TABLE t(a); ")
return .commit
}
switch expectedCompletion {
case .commit:
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
case .rollback:
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
}
}
}
}
@@ -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)")
}
+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")
+1 -1
View File
@@ -120,7 +120,7 @@ class FTS3TableBuilderTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS3()) { t in
t.tokenizer = .unicode61(tokenCharacters: Set(".-".characters))
t.tokenizer = .unicode61(tokenCharacters: Set(".-"))
}
assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts3(tokenize=unicode61 \"tokenchars=-.\")")
}
+1 -1
View File
@@ -143,7 +143,7 @@ class FTS3TokenizerTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS3()) { t in
t.tokenizer = .unicode61(tokenCharacters: Set(".-".characters))
t.tokenizer = .unicode61(tokenCharacters: Set(".-"))
}
XCTAssertTrue(match(db, "2016-10-04.txt", "2016-10-04.txt"))
+60 -1
View File
@@ -120,7 +120,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS4()) { t in
t.tokenizer = .unicode61(tokenCharacters: Set(".-".characters))
t.tokenizer = .unicode61(tokenCharacters: Set(".-"))
}
assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4(tokenize=unicode61 \"tokenchars=-.\")")
}
@@ -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")
}
}
}
}
+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")
}
@@ -615,7 +615,7 @@ class FetchedRecordsControllerTests: GRDBTestCase {
for step in steps {
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, step.word.characters.enumerated().map { Person(id: Int64($0), name: String($1)) })
try synchronizePersons(db, step.word.enumerated().map { Person(id: Int64($0), name: String($1)) })
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
+18 -13
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 { }
@@ -119,15 +129,10 @@ class GRDBTestCase: XCTestCase {
XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)")
}
func assert(_ record: MutablePersistable, isEncodedIn row: Row) {
let recordContent = AnySequence({ PersistenceContainer(record).makeIterator() })
for (column, value) in recordContent {
if let dbValue: DatabaseValue = row[column] {
XCTAssertEqual(dbValue, value?.databaseValue ?? .null)
} else {
XCTFail("Missing column \(column) in fetched row")
}
}
func assert(_ record: MutablePersistable, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) {
let recordDict = record.databaseDictionary
let rowDict = Dictionary(row, uniquingKeysWith: { (left, _) in left })
XCTAssertEqual(recordDict, rowDict, file: file, line: line)
}
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
@@ -27,8 +27,9 @@ extension MutablePersistableEncodableTests {
}
var value = Struct(value: "foo")
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo"])
try value.insert(db)
let string = try String.fetchOne(db, "SELECT value FROM t1")!
XCTAssertEqual(string, "foo")
}
@@ -56,8 +57,9 @@ extension MutablePersistableEncodableTests {
}
var value = Struct(value: "foo")
try value.insert(db)
assert(value, isEncodedIn: ["someColumn": "foo (Encodable)"])
try value.insert(db)
let string = try String.fetchOne(db, "SELECT someColumn FROM t1")!
XCTAssertEqual(string, "foo (Encodable)")
}
@@ -80,8 +82,9 @@ extension MutablePersistableEncodableTests {
}
var value = Struct(value: "foo")
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo (MutablePersistable)"])
try value.insert(db)
let string = try String.fetchOne(db, "SELECT value FROM t1")!
XCTAssertEqual(string, "foo (MutablePersistable)")
}
@@ -109,8 +112,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(int64: 123, optionalInt64: 456)
try value.insert(db)
assert(value, isEncodedIn: ["int64": 123, "optionalInt64": 456])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["int64": 123, "optionalInt64": 456])
return .rollback
@@ -118,8 +122,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(int64: 123, optionalInt64: nil)
try value.insert(db)
assert(value, isEncodedIn: ["int64": 123, "optionalInt64": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["int64": 123, "optionalInt64": nil])
return .rollback
@@ -152,8 +157,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(string: "foo"), optionalValue: Value(string: "bar"))
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": "bar"])
return .rollback
@@ -161,8 +167,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(string: "foo"), optionalValue: nil)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": nil])
return .rollback
@@ -204,8 +211,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(nestedValue: NestedValue(string: "foo")), optionalValue: Value(nestedValue: NestedValue(string: "bar")))
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": "bar"])
return .rollback
@@ -213,8 +221,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(nestedValue: NestedValue(string: "foo")), optionalValue: nil)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": nil])
return .rollback
@@ -247,8 +256,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: .foo, optionalValue: .bar)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": "bar"])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": "bar"])
return .rollback
@@ -256,8 +266,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: .foo, optionalValue: nil)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo", "optionalValue": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo", "optionalValue": nil])
return .rollback
@@ -308,8 +319,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(string: "foo"), optionalValue: Value(string: "bar"))
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo (DatabaseValueConvertible)", "optionalValue": "bar (DatabaseValueConvertible)"])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo (DatabaseValueConvertible)", "optionalValue": "bar (DatabaseValueConvertible)"])
return .rollback
@@ -317,8 +329,9 @@ extension MutablePersistableEncodableTests {
try dbQueue.inTransaction { db in
var value = Struct(value: Value(string: "foo"), optionalValue: nil)
try value.insert(db)
assert(value, isEncodedIn: ["value": "foo (DatabaseValueConvertible)", "optionalValue": nil])
try value.insert(db)
let row = try Row.fetchOne(db, "SELECT * FROM t1")!
XCTAssertEqual(row, ["value": "foo (DatabaseValueConvertible)", "optionalValue": nil])
return .rollback
@@ -370,8 +383,9 @@ extension MutablePersistableEncodableTests {
}
let value = StructWithURL(url: URL(string: "https://github.com")!)
try value.insert(db)
assert(value, isEncodedIn: ["url": value.url])
try value.insert(db)
let dbValue = try DatabaseValue.fetchOne(db, "SELECT url FROM t1")!
XCTAssert(dbValue.storage.value is String)
let fetchedURL = URL.fromDatabaseValue(dbValue)!
@@ -392,8 +406,9 @@ extension MutablePersistableEncodableTests {
}
let value = StructWithUUID(uuid: UUID())
try value.insert(db)
assert(value, isEncodedIn: ["uuid": value.uuid])
try value.insert(db)
let dbValue = try DatabaseValue.fetchOne(db, "SELECT uuid FROM t1")!
XCTAssert(dbValue.storage.value is Data)
let fetchedUUID = UUID.fromDatabaseValue(dbValue)!
+15
View File
@@ -50,4 +50,19 @@ class SQLRequestTests: GRDBTestCase {
XCTAssertTrue(statement1 === statement2)
}
}
func testAsSQLRequest() throws {
struct CustomRequest: Request {
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try SQLRequest("SELECT ?, ?", arguments: [1, "foo"]).prepare(db)
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = CustomRequest()
let sqlRequest = try request.asSQLRequest(db)
XCTAssertEqual(sqlRequest.sql, "SELECT ?, ?")
XCTAssertEqual(sqlRequest.arguments, [1, "foo"])
}
}
}
+11 -11
View File
@@ -10,9 +10,9 @@ import XCTest
class SchedulingWatchdogTests: GRDBTestCase {
func testSchedulingWatchdog() throws {
let dbQueue1 = try makeDatabaseQueue(filename: "db1")
let dbQueue2 = try makeDatabaseQueue(filename: "db2")
let dbQueue3 = try makeDatabaseQueue(filename: "db3")
let dbQueue1 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue()
let dbQueue3 = try makeDatabaseQueue()
var db1: Database! = nil
var db2: Database! = nil
@@ -51,8 +51,8 @@ class SchedulingWatchdogTests: GRDBTestCase {
}
func testDatabaseQueueFromDatabaseQueue() throws {
let dbQueue1 = try makeDatabaseQueue(filename: "db1")
let dbQueue2 = try makeDatabaseQueue(filename: "db2")
let dbQueue1 = try makeDatabaseQueue()
let dbQueue2 = try makeDatabaseQueue()
try dbQueue1.inDatabase { db1 in
try db1.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db1.execute("INSERT INTO items (id) VALUES (NULL)")
@@ -71,8 +71,8 @@ class SchedulingWatchdogTests: GRDBTestCase {
}
func testDatabaseQueueFromDatabasePool() throws {
let dbPool1 = try makeDatabasePool(filename: "db1")
let dbQueue2 = try makeDatabaseQueue(filename: "db2")
let dbPool1 = try makeDatabasePool()
let dbQueue2 = try makeDatabaseQueue()
try dbPool1.write { db1 in
try db1.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db1.execute("INSERT INTO items (id) VALUES (NULL)")
@@ -91,8 +91,8 @@ class SchedulingWatchdogTests: GRDBTestCase {
}
func testDatabasePoolFromDatabaseQueue() throws {
let dbQueue1 = try makeDatabaseQueue(filename: "db1")
let dbPool2 = try makeDatabasePool(filename: "db2")
let dbQueue1 = try makeDatabaseQueue()
let dbPool2 = try makeDatabasePool()
try dbQueue1.inDatabase { db1 in
try db1.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db1.execute("INSERT INTO items (id) VALUES (NULL)")
@@ -111,8 +111,8 @@ class SchedulingWatchdogTests: GRDBTestCase {
}
func testDatabasePoolFromDatabasePool() throws {
let dbPool1 = try makeDatabasePool(filename: "db1")
let dbPool2 = try makeDatabasePool(filename: "db2")
let dbPool1 = try makeDatabasePool()
let dbPool2 = try makeDatabasePool()
try dbPool1.write { db1 in
try db1.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db1.execute("INSERT INTO items (id) VALUES (NULL)")
+6 -4
View File
@@ -462,14 +462,16 @@ class TableDefinitionTests: GRDBTestCase {
t.add(column: "b", .text)
t.add(column: "c", .integer).notNull().defaults(to: 1)
t.add(column: "d", .text).references("alt")
t.add(column: "e")
}
assertEqualSQL(sqlQueries[sqlQueries.count - 3], "ALTER TABLE \"test\" ADD COLUMN \"b\" TEXT")
assertEqualSQL(sqlQueries[sqlQueries.count - 2], "ALTER TABLE \"test\" ADD COLUMN \"c\" INTEGER NOT NULL DEFAULT 1")
assertEqualSQL(sqlQueries[sqlQueries.count - 1], "ALTER TABLE \"test\" ADD COLUMN \"d\" TEXT REFERENCES \"alt\"(\"rowid\")")
assertEqualSQL(sqlQueries[sqlQueries.count - 4], "ALTER TABLE \"test\" ADD COLUMN \"b\" TEXT")
assertEqualSQL(sqlQueries[sqlQueries.count - 3], "ALTER TABLE \"test\" ADD COLUMN \"c\" INTEGER NOT NULL DEFAULT 1")
assertEqualSQL(sqlQueries[sqlQueries.count - 2], "ALTER TABLE \"test\" ADD COLUMN \"d\" TEXT REFERENCES \"alt\"(\"rowid\")")
assertEqualSQL(sqlQueries[sqlQueries.count - 1], "ALTER TABLE \"test\" ADD COLUMN \"e\"")
}
}
func testDropTable() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,333 @@
import XCTest
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
class TruncateOptimizationTests: GRDBTestCase {
// https://www.sqlite.org/c3ref/update_hook.html
//
// > In the current implementation, the update hook is not invoked [...]
// > when rows are deleted using the truncate optimization.
//
// https://www.sqlite.org/lang_delete.html#truncateopt
//
// > When the WHERE is omitted from a DELETE statement and the table
// > being deleted has no triggers, SQLite uses an optimization to erase
// > the entire table content without having to visit each row of the
// > table individually.
//
// We will thus test that the truncate optimization does not prevent
// transaction observers from observing individual deletions.
//
// But that's not enough: preventing the truncate optimization requires GRDB
// to fiddle with sqlite3_set_authorizer. When badly done, this can prevent
// DROP TABLE statements from dropping tables. SQLite3 authorizers are
// invoked during both compilation and execution of SQL statements. We will
// thus test that DROP TABLE statements perform as expected when compilation
// and execution are grouped, and when they are performed separately.
class DeletionObserver : TransactionObserver {
private var notify: ([String: Int]) -> Void
private var deletionEvents: [String: Int] = [:]
// Notifies table names with the number of deleted rows
init(_ notify: @escaping ([String: Int]) -> Void) {
self.notify = notify
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return true
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
func databaseDidChange(with event: DatabaseEvent) {
if case .delete = event.kind {
deletionEvents[event.tableName, default: 0] += 1
}
}
func databaseWillCommit() throws { }
func databaseDidCommit(_ db: Database) {
if !deletionEvents.isEmpty {
notify(deletionEvents)
}
deletionEvents = [:]
}
func databaseDidRollback(_ db: Database) {
deletionEvents = [:]
}
}
func testExecuteDelete() throws {
let dbQueue = try makeDatabaseQueue()
var deletionEvents: [[String: Int]] = []
let observer = DeletionObserver { deletionEvents.append($0) }
dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
try db.execute("INSERT INTO t VALUES (NULL)")
deletionEvents = []
try db.execute("DELETE FROM t")
XCTAssertEqual(deletionEvents.count, 1)
XCTAssertEqual(deletionEvents[0], ["t": 2])
try db.execute("INSERT INTO t VALUES (NULL)")
deletionEvents = []
try db.execute("DELETE FROM t")
XCTAssertEqual(deletionEvents.count, 1)
XCTAssertEqual(deletionEvents[0], ["t": 1])
}
}
func testExecuteDeleteWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
var deletionEvents: [[String: Int]] = []
let observer = DeletionObserver { deletionEvents.append($0) }
dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
let deleteStatement = try db.makeUpdateStatement("DELETE FROM t")
try db.execute("INSERT INTO t VALUES (NULL)")
try db.execute("INSERT INTO t VALUES (NULL)")
deletionEvents = []
try deleteStatement.execute()
XCTAssertEqual(deletionEvents.count, 1)
XCTAssertEqual(deletionEvents[0], ["t": 2])
try db.execute("INSERT INTO t VALUES (NULL)")
deletionEvents = []
try deleteStatement.execute()
XCTAssertEqual(deletionEvents.count, 1)
XCTAssertEqual(deletionEvents[0], ["t": 1])
}
}
func testDropTable() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
try XCTAssertTrue(db.tableExists("t"))
try db.execute("DROP TABLE t") // compile + execute
try XCTAssertFalse(db.tableExists("t"))
}
}
func testDropTableWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
try XCTAssertTrue(db.tableExists("t"))
let dropStatement = try db.makeUpdateStatement("DROP TABLE t") // compile...
try dropStatement.execute() // ... then execute
try XCTAssertFalse(db.tableExists("t"))
}
}
func testDropTemporaryTable() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TEMPORARY TABLE t(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
try XCTAssertTrue(db.tableExists("t"))
try db.execute("DROP TABLE t") // compile + execute
try XCTAssertFalse(db.tableExists("t"))
}
}
func testDropTemporaryTableWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TEMPORARY TABLE t(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
try XCTAssertTrue(db.tableExists("t"))
let dropStatement = try db.makeUpdateStatement("DROP TABLE t") // compile...
try dropStatement.execute() // ... then execute
try XCTAssertFalse(db.tableExists("t"))
}
}
func testDropVirtualTable() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE VIRTUAL TABLE t USING fts3(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
try XCTAssertTrue(db.tableExists("t"))
try db.execute("DROP TABLE t") // compile + execute
try XCTAssertFalse(db.tableExists("t"))
}
}
func testDropVirtualTableWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE VIRTUAL TABLE t USING fts3(a)")
try db.execute("INSERT INTO t VALUES (NULL)")
try XCTAssertTrue(db.tableExists("t"))
let dropStatement = try db.makeUpdateStatement("DROP TABLE t") // compile...
try dropStatement.execute() // ... then execute
try XCTAssertFalse(db.tableExists("t"))
}
}
func testDropView() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("CREATE VIEW v AS SELECT * FROM t")
try db.execute("INSERT INTO t VALUES (NULL)")
try XCTAssertTrue(db.viewExists("v"))
try db.execute("DROP VIEW v") // compile + execute
try XCTAssertFalse(db.viewExists("v"))
}
}
func testDropViewWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("CREATE VIEW v AS SELECT * FROM t")
try db.execute("INSERT INTO t VALUES (NULL)")
try XCTAssertTrue(db.viewExists("v"))
let dropStatement = try db.makeUpdateStatement("DROP VIEW v") // compile...
try dropStatement.execute() // ... then execute
try XCTAssertFalse(db.viewExists("v"))
}
}
func testDropTemporaryView() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("CREATE TEMPORARY VIEW v AS SELECT * FROM t")
try db.execute("INSERT INTO t VALUES (NULL)")
try XCTAssertTrue(db.viewExists("v"))
try db.execute("DROP VIEW v") // compile + execute
try XCTAssertFalse(db.viewExists("v"))
}
}
func testDropTemporaryViewWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("CREATE TEMPORARY VIEW v AS SELECT * FROM t")
try db.execute("INSERT INTO t VALUES (NULL)")
try XCTAssertTrue(db.viewExists("v"))
let dropStatement = try db.makeUpdateStatement("DROP VIEW v") // compile...
try dropStatement.execute() // ... then execute
try XCTAssertFalse(db.viewExists("v"))
}
}
func testDropIndex() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("CREATE INDEX i ON t(a)")
try XCTAssertFalse(db.indexes(on: "t").isEmpty)
try db.execute("DROP INDEX i") // compile + execute
try XCTAssertTrue(db.indexes(on: "t").isEmpty)
}
}
func testDropIndexViewWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("CREATE INDEX i ON t(a)")
try db.execute("INSERT INTO t VALUES (1)")
try XCTAssertFalse(db.indexes(on: "t").isEmpty)
let dropStatement = try db.makeUpdateStatement("DROP INDEX i") // compile...
try dropStatement.execute() // ... then execute
try XCTAssertTrue(db.indexes(on: "t").isEmpty)
}
}
func testDropTemporaryIndex() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TEMPORARY TABLE t(a)")
try db.execute("CREATE INDEX i ON t(a)")
try XCTAssertFalse(db.indexes(on: "t").isEmpty)
try db.execute("DROP INDEX i") // compile + execute
try XCTAssertTrue(db.indexes(on: "t").isEmpty)
}
}
func testDropTemporaryIndexViewWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TEMPORARY TABLE t(a)")
try db.execute("CREATE INDEX i ON t(a)")
try db.execute("INSERT INTO t VALUES (1)")
try XCTAssertFalse(db.indexes(on: "t").isEmpty)
let dropStatement = try db.makeUpdateStatement("DROP INDEX i") // compile...
try dropStatement.execute() // ... then execute
try XCTAssertTrue(db.indexes(on: "t").isEmpty)
}
}
func testDropTrigger() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END")
try XCTAssertTrue(db.triggerExists("r"))
try db.execute("DROP TRIGGER r") // compile + execute
try XCTAssertFalse(db.triggerExists("r"))
}
}
func testDropTriggerWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END")
try XCTAssertTrue(db.triggerExists("r"))
let dropStatement = try db.makeUpdateStatement("DROP TRIGGER r") // compile...
try dropStatement.execute() // ... then execute
try XCTAssertFalse(db.triggerExists("r"))
}
}
func testDropTemporaryTrigger() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END")
try XCTAssertTrue(db.triggerExists("r"))
try db.execute("DROP TRIGGER r") // compile + execute
try XCTAssertFalse(db.triggerExists("r"))
}
}
func testDropTemporaryTriggerWithPreparedStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE t(a)")
try db.execute("CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END")
try XCTAssertTrue(db.triggerExists("r"))
let dropStatement = try db.makeUpdateStatement("DROP TRIGGER r") // compile...
try dropStatement.execute() // ... then execute
try XCTAssertFalse(db.triggerExists("r"))
}
}
}
+32 -17
View File
@@ -28,7 +28,7 @@ class UpdateStatementTests : GRDBTestCase {
try dbQueue.inTransaction { db in
try db.makeUpdateStatement("INSERT INTO persons (name) VALUES ('Arthur');").execute()
try db.makeUpdateStatement("INSERT INTO persons (name) VALUES ('Barbara')\n \t").execute()
try db.makeUpdateStatement("INSERT INTO persons (name) VALUES ('Craig');").execute()
try db.makeUpdateStatement("INSERT INTO persons (name) VALUES ('Craig'); ; ;").execute()
try db.makeUpdateStatement("INSERT INTO persons (name) VALUES ('Daniel');\n \t").execute()
return .commit
}
@@ -182,6 +182,19 @@ class UpdateStatementTests : GRDBTestCase {
XCTAssertEqual(index, 3 + 3)
}
func testExecuteNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("")
try db.execute(" ")
try db.execute(";")
try db.execute(";;")
try db.execute(" \n;\t; ")
try db.execute("-- comment")
try db.execute("-- comment\\n; -----ignored")
}
}
func testExecuteMultipleStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -209,6 +222,24 @@ class UpdateStatementTests : GRDBTestCase {
}
}
func testExecuteMultipleStatementWithPlentyOfSemicolonsAndWhiteSpaceAndComments() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("""
;;
CREATE TABLE wines ( -- create a table
name TEXT, -- the name
color INT);
;\t;
-- create another table
CREATE TABLE books (name TEXT, age INT); \
\t; ;
""")
XCTAssertTrue(try db.tableExists("wines"))
XCTAssertTrue(try db.tableExists("books"))
}
}
func testExecuteMultipleStatementWithNamedArguments() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inTransaction { db in
@@ -307,20 +338,4 @@ class UpdateStatementTests : GRDBTestCase {
}
}
}
func testDropTablePreparedStatement() throws {
// In v2.0.1...
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
XCTAssertFalse(try db.tableExists("t"))
try db.execute("CREATE TABLE t(a)")
XCTAssertTrue(try db.tableExists("t"))
try db.execute("DROP TABLE t") // ... this would drop the table
XCTAssertFalse(try db.tableExists("t"))
try db.execute("CREATE TABLE t(a)")
XCTAssertTrue(try db.tableExists("t"))
try db.makeUpdateStatement("DROP TABLE t").execute() // ... but this would not. WTF??? Hence this regression test.
XCTAssertFalse(try db.tableExists("t"))
}
}
}
@@ -41,7 +41,7 @@ class FetchNamedValuesTests: XCTestCase {
#if GRDB_COMPARE
func testFMDB() {
let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")!
let dbQueue = FMDatabaseQueue(path: databasePath)
let dbQueue = FMDatabaseQueue(path: databasePath)!
measure {
var count = 0
@@ -83,7 +83,7 @@ class FetchPositionalValuesTests: XCTestCase {
#if GRDB_COMPARE
func testFMDB() {
let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")!
let dbQueue = FMDatabaseQueue(path: databasePath)
let dbQueue = FMDatabaseQueue(path: databasePath)!
measure {
var count = 0
@@ -86,7 +86,7 @@ class FetchRecordStructTests: XCTestCase {
// Here we test the loading of an array of Records.
let databasePath = Bundle(for: type(of: self)).path(forResource: "PerformanceTests", ofType: "sqlite")!
let dbQueue = FMDatabaseQueue(path: databasePath)
let dbQueue = FMDatabaseQueue(path: databasePath)!
measure {
var items = [ItemStruct]()
@@ -57,7 +57,7 @@ class InsertNamedValuesTests: XCTestCase {
measure {
_ = try? FileManager.default.removeItem(atPath: databasePath)
let dbQueue = FMDatabaseQueue(path: databasePath)
let dbQueue = FMDatabaseQueue(path: databasePath)!
dbQueue.inDatabase { db in
db.executeStatements("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)")
}
@@ -102,7 +102,7 @@ class InsertPositionalValuesTests: XCTestCase {
measure {
_ = try? FileManager.default.removeItem(atPath: databasePath)
let dbQueue = FMDatabaseQueue(path: databasePath)
let dbQueue = FMDatabaseQueue(path: databasePath)!
dbQueue.inDatabase { db in
db.executeStatements("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)")
}
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env ruby
gem 'json'
require 'json'
require 'date'
require 'rexml/document'
# Extract CFBundleShortVersionString from a plist file
def info_plist_version(path)
REXML::Document.new(File.read(path))
.root
.elements["//key[text()='CFBundleShortVersionString']"]
.next_element
.text
end
def formatted_sample(samples, test, lib)
sample = samples["#{test}Tests"]["test#{lib}"]
return '¹' unless sample # n/a
'%.2f' % sample
end
def formatted_samples(samples, test)
libs = %w{GRDB SQLite FMDB SQLiteSwift CoreData Realm}
libs.map { |lib| formatted_sample(samples, test, lib) || '¹' }
end
samples = JSON.parse(STDIN.read)
grdb_version = info_plist_version('Support/Info.plist')
fmdb_version = info_plist_version('Tests/Performance/fmdb/src/fmdb/Info.plist')
sqlite_swift_version = info_plist_version('Tests/Performance/SQLite.swift/Sources/SQLite/Info.plist')
realm_version = info_plist_version('Tests/Performance/Realm/build/osx/Realm.framework/Versions/A/Resources/Info.plist')
puts <<-REPORT
# Comparing the Performances of Swift SQLite libraries
*Last updated #{Date.today.strftime('%B %-d, %Y')}*
Below are performance benchmarks made on for [GRDB #{grdb_version}](https://github.com/groue/GRDB.swift), [FMDB #{fmdb_version}](https://github.com/ccgus/fmdb), and [SQLite.swift #{sqlite_swift_version}](https://github.com/stephencelis/SQLite.swift). They are compared to Core Data, [Realm #{realm_version}](https://realm.io) and the raw use of the SQLite C API from Swift.
This report was generated on a MacBook Pro (15-inch, Late 2016), with Xcode 9.2, by running the following command:
```sh
make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb
```
All tests use the default settings of each library. For each library, we:
- Build and consume database rows with raw SQL and column indexes (aiming at the best performance)
- Build and consume database rows with column names (sacrificing performance for maintainability)
- Build and consume records values to and from database rows (aiming at the shortest code from database to records)
- Build and consume records values to and from database rows, with [change tracking](https://github.com/groue/GRDB.swift#changes-tracking) (records know if they have unsaved changes)
As a bottom line, the raw SQLite C API is used as efficiently as possible, without any error checking.
| | GRDB | Raw SQLite | FMDB | SQLite.swift | Core Data | Realm |
|:-------------------------------- | ----:| ----------:| ----:| ------------:| ---------:| -----:|
| **Column indexes** | | | | | | |
| Fetch | #{formatted_samples(samples, 'FetchPositionalValues').join(" | ")} |
| Insert | #{formatted_samples(samples, 'InsertPositionalValues').join(" | ")} |
| **Column names** | | | | | | |
| Fetch | #{formatted_samples(samples, 'FetchNamedValues').join(" | ")} |
| Insert | #{formatted_samples(samples, 'InsertNamedValues').join(" | ")} |
| **Records** | | | | | | |
| Fetch | #{formatted_samples(samples, 'FetchRecordStruct').join(" | ")} |
| Insert | #{formatted_samples(samples, 'InsertRecordStruct').join(" | ")} |
| **Records with change tracking** | | | | | | |
| Fetch | #{formatted_samples(samples, 'FetchRecordClass').join(" | ")} |
| Insert | #{formatted_samples(samples, 'InsertRecordClass').join(" | ")} |
¹ Not applicable
- **Column indexes**:
- **Fetch** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/FetchPositionalValuesTests.swift))
This test fetches 100000 rows of 10 ints and extracts each int given its position in the row.
It uses FMDB's `-[FMResultSet longForColumnIndex:]`, GRDB's `Row.value(atIndex:)`, and the low-level SQL API of SQLite.swift.
- **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/InsertPositionalValuesTests.swift))
This test inserts 20000 rows of 10 ints, by setting query arguments given their position.
It uses FMDB's `-[FMDatabase executeUpdate:withArgumentsInArray:]` with statement caching, GRDB's `UpdateStatement.execute(arguments:Array)`, and the low-level SQL API of SQLite.swift.
- **Column names**:
- **Fetch** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/FetchNamedValuesTests.swift))
This test fetches 100000 rows of 10 ints and extracts each int given its column name.
It uses FMDB's `-[FMResultSet longForColumn:]`, GRDB's `Row.value(named:)`, and the high-level query builder of SQLite.swift.
- **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/InsertNamedValuesTests.swift))
This test inserts 20000 rows of 10 ints, by setting query arguments given their argument name.
It uses FMDB's `-[FMDatabase executeUpdate:withParameterDictionary:]` with statement caching, GRDB's `UpdateStatement.execute(arguments:Dictionary)`, and the high-level query builder of SQLite.swift.
- **Records**:
- **Fetch** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/FetchRecordStructTests.swift))
This test fetches an array of 100000 record objects initiated from rows of 10 ints.
It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [RowConvertible](https://github.com/groue/GRDB.swift#rowconvertible-protocol) protocol, and the values returned by the high-level query builder of SQLite.swift.
- **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/InsertRecordStructTests.swift))
This tests inserts 20000 records with the persistence method provided by GRDB's [Persistable](https://github.com/groue/GRDB.swift#persistable-protocol) protocol.
- **Records with change tracking**:
- **Fetch** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/FetchRecordClassTests.swift))
This test fetches an array of 100000 record objects initiated from rows of 10 ints.
It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [Record](https://github.com/groue/GRDB.swift#record-class) class.
- **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/InsertRecordClassTests.swift))
This tests inserts 20000 records with the persistence method provided by GRDB's [Record](https://github.com/groue/GRDB.swift#record-class) class.
REPORT
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env ruby
gem 'json'
require 'json'
tests = {}
STDIN.each do |line|
if line =~ /\.([^ ]*) ([^ ]*)\]' measured \[Time, seconds\] average: ([\d.]+)/
class_name = $1
test_name = $2
time = $3
tests[class_name] ||= {}
tests[class_name][test_name] = time.to_f
end
end
puts tests.to_json
-10
View File
@@ -1,10 +0,0 @@
#/bin/sh
#
# Outputs the compilation time of all methods.
# To get the 20 slowest methods, run ./slow_methods.sh | head -20
set -e
PROJECT=GRDB.xcodeproj
TARGET=GRDBiOS
OTHER_SWIFT_FLAGS='-Xfrontend -debug-time-function-bodies' xcodebuild -project $PROJECT -target $TARGET 2>&1 clean build | grep '^[0-9][0-9.]*.*\t' | sort -nr