Compare commits

...
756 Commits
Author SHA1 Message Date
Gwendal Roué d265e2d77b v3.6.2 2019-01-05 15:40:05 +01:00
Gwendal Roué ac40b63262 Merge pull request #464 from groue/feature/updatesChanges
Make updateChanges(_:with:) available to PersistableRecord structs
2019-01-05 14:47:35 +01:00
Gwendal Roué bac9d8e425 CHANGELOG.md 2019-01-05 14:46:38 +01:00
Gwendal Roué bf0c9b5c27 Move non-mutating updateChanges(_:with:) from PersistableRecord to PersistableRecord & AnyObject. 2019-01-05 12:35:28 +01:00
Gwendal Roué f70d04c76a Failing test for updateChanges(_:with:) for PersistableRecord struct
The problem is that the code does not compile :'(
2019-01-05 12:30:48 +01:00
Gwendal Roué 85aa899c7b Fix #462 2019-01-02 17:49:36 +01:00
Gwendal Roué 19fa05aecc Update TODO.md 2018-12-13 16:46:13 +01:00
Gwendal Roué 9c4a8fb0b2 Fix typo 2018-12-09 11:35:22 +01:00
Gwendal Roué e19f02b77e v3.6.1 2018-12-09 11:18:41 +01:00
Gwendal Roué b34030fc39 Merge pull request #458 from groue/feature/FixValueObserverOverRetain
Fix ValueObservation duration - code & doc
2018-12-09 10:37:51 +01:00
Gwendal Roué 40a5fb1195 Observer deallocation needs better tests 2018-12-09 06:17:36 +01:00
Gwendal Roué d9dd880d6d Fix flaky test 2018-12-09 05:45:14 +01:00
Gwendal Roué c51b0ba862 Fix documentation about ValueObservation.extent, and add a note in remove(transactionObserver:) documentation. 2018-12-08 17:32:18 +01:00
Gwendal Roué 197f922e7e Fix failing tests for over-retained ValueObserver 2018-12-08 17:11:53 +01:00
Gwendal Roué 25f6bd9673 Failing tests for over-retained ValueObserver 2018-12-08 17:11:30 +01:00
Gwendal Roué 909821f4e5 Add a link to Codable records 2018-12-08 14:57:20 +01:00
Gwendal Roué b211dc55c4 Put associations in the feature list
... and use the "relation" keyword: people familiar with other toolkits may search for this word https://forums.swift.org/t/new-release-grdb-3-6-0/18660/4
2018-12-08 14:36:45 +01:00
Gwendal Roué 863a762eca Wording 2018-12-08 12:23:41 +01:00
Gwendal Roué bb01da7635 Mention ValueObservation iin WhyAdoptGRDB 2018-12-08 11:32:26 +01:00
Gwendal Roué 558cdacb5b Fix typo 2018-12-08 07:50:41 +01:00
Gwendal Roué eff7dbd798 CHANGELOG 2018-12-08 07:18:22 +01:00
Gwendal Roué 1d3935baaf Merge pull request #457 from diatoming/patch-2
Typo in AssociationsBasics.md
2018-12-08 05:40:39 +01:00
diatoming b40e4e58e1 Typo in AssociationsBasics.md 2018-12-08 07:08:20 +08:00
Gwendal Roué 36d3607565 http://github.com/groue/GRDBDemo is no longer 2018-12-07 20:56:04 +01:00
Gwendal Roué d55807e2a2 Realm 3.12.0, Swift 4.2.1 2018-12-07 20:55:12 +01:00
Gwendal Roué 6447eeca17 v3.6.0 2018-12-07 18:58:30 +01:00
Gwendal Roué 1fea9c06e8 Merge branch 'development' 2018-12-07 18:30:07 +01:00
Gwendal Roué 11d3dd9538 CHANGELOG 2018-12-07 18:22:01 +01:00
Gwendal Roué f6f236512b Documentation 2018-12-07 18:08:53 +01:00
Gwendal Roué 343816ed7b Documentation 2018-12-07 18:04:16 +01:00
Gwendal Roué 59a65bf81e PULL_REQUEST_TEMPLATE 2018-12-07 17:57:50 +01:00
Gwendal Roué a5b06b5cb0 Merge branch 'master' into development 2018-12-07 17:55:00 +01:00
Gwendal Roué 802575c505 Merge pull request #456 from diatoming/patch-1
fix typo in AssociationsBasics.md
2018-12-07 13:13:04 +01:00
diatoming c433a130e5 Update AssociationsBasics.md
just fix typo
2018-12-07 19:56:28 +08:00
Gwendal Roué ca4a867803 Remove picture that breaks anchor linking 2018-12-07 08:43:59 +01:00
Gwendal Roué 37ac126d26 Documentation 2018-12-07 08:42:28 +01:00
Gwendal Roué 5badd62515 Documentation 2018-12-07 08:41:17 +01:00
Gwendal Roué 37983b8581 Documentation 2018-12-07 08:36:11 +01:00
Gwendal Roué 815a3697da Documentation 2018-12-07 08:20:18 +01:00
Gwendal Roué 32acfb2cf4 Merge pull request #455 from groue/feature/DatabaseRegionObserver
DatabaseRegionObservation
2018-12-07 08:07:28 +01:00
Gwendal Roué 9fd802b3ea Documentation 2018-12-06 18:54:09 +01:00
Gwendal Roué 21d243fc33 Documentation 2018-12-06 18:51:45 +01:00
Gwendal Roué 97936c3fad Documentation 2018-12-06 18:46:57 +01:00
Gwendal Roué 03934041c2 Fix DatabaseRegion doc layout 2018-12-06 18:41:43 +01:00
Gwendal Roué 862563fdaa Remove obsolete test 2018-12-06 16:42:20 +01:00
Gwendal Roué 73935dfa9d CHANGELOG 2018-12-06 14:02:10 +01:00
Gwendal Roué 9a3e6f0b97 CHANGELOG 2018-12-06 13:58:47 +01:00
Gwendal Roué bc5899543f Documentation 2018-12-06 13:55:08 +01:00
Gwendal Roué fd79a53a96 Documentation 2018-12-06 13:34:02 +01:00
Gwendal Roué 194624212e Move db observation documentations around 2018-12-06 13:33:17 +01:00
Gwendal Roué 1472385242 Documentation 2018-12-06 08:55:31 +01:00
Gwendal Roué 78bb086f69 Documentation 2018-12-06 08:43:44 +01:00
Gwendal Roué e3681fdde5 DatabaseRegionObservationTests 2018-12-06 08:28:43 +01:00
Gwendal Roué 6ec4556c2c DatabaseRegionObservation 2018-12-06 07:49:41 +01:00
Gwendal Roué 1e72731c07 Distinguish distinctUntilChanged from distinctUntilDatabaseChanged 2018-12-06 07:04:40 +01:00
Gwendal Roué 82329c899e Hide DatabaseWriter.remove(transactionObserver:) from Jazzy 2018-12-05 19:27:04 +01:00
Gwendal Roué 8ab6e67f07 Hide DatabaseWriter.add(observation:onError:onChange:) from Jazzy 2018-12-05 19:23:06 +01:00
Gwendal Roué 643bbc7076 Merge pull request #454 from groue/feature/distinctUntilChanged
ValueObservation.distinctUntilChanged
2018-12-05 12:06:42 +01:00
Gwendal Roué 61f2544afe Remove a breaking change introduced by #446 2018-12-05 08:47:55 +01:00
Gwendal Roué 546289bc88 CHANGELOG 2018-12-05 08:29:49 +01:00
Gwendal Roué d3d5b1d24c CHANGELOG 2018-12-05 08:28:08 +01:00
Gwendal Roué dd59186887 Documentation 2018-12-05 08:24:12 +01:00
Gwendal Roué 88d7c58522 TODO: remove some magic in GRDB 4 2018-12-05 08:02:18 +01:00
Gwendal Roué c711ca1e8f ValueObservation.distinctUntilChanged() 2018-12-05 07:58:03 +01:00
Gwendal Roué 56d49dd385 Cleanup 2018-12-02 10:12:21 +01:00
Gwendal Roué 7b97d75a80 Merge pull request #452 from groue/feature/MapReducer
ValueObservation.mapReducer
2018-12-02 07:56:50 +01:00
Gwendal Roué a8d9f2d82b CHANGELOG 2018-12-02 01:11:58 +01:00
Gwendal Roué c7d28de386 CHANGELOG 2018-12-02 01:10:13 +01:00
Gwendal Roué ce61d27a9e CHANGELOG 2018-12-02 01:02:14 +01:00
Gwendal Roué b8e3994858 ValueObservation.mapReducer
and expose more precise value reducers
2018-12-02 00:01:21 +01:00
Gwendal Roué 7c6c615969 Merge pull request #451 from groue/feature/CompactMap
ValueObservation.compactMap
2018-12-01 21:03:34 +01:00
Gwendal Roué 8c543f5078 Fix failing tests 2018-12-01 19:07:58 +01:00
Gwendal Roué 3884141fc2 map/compactMap fail preserving ValueObservation configuration 2018-12-01 19:06:16 +01:00
Gwendal Roué 2c3776d372 Fix typo 2018-12-01 18:59:01 +01:00
Gwendal Roué c1d8dcb105 Link to ValueObservation from GoodPracticesForDesigningRecordTypes 2018-12-01 17:17:54 +01:00
Gwendal Roué c89540683f README 2018-12-01 17:11:56 +01:00
Gwendal Roué 3687e11958 README 2018-12-01 17:10:17 +01:00
Gwendal Roué 90c588a9f5 README 2018-12-01 17:06:10 +01:00
Gwendal Roué 838d9204ab CHANGELOG 2018-12-01 17:02:30 +01:00
Gwendal Roué 2488007b9c README 2018-12-01 17:02:25 +01:00
Gwendal Roué 5b3412e9f7 ValueObservation.compactMap 2018-12-01 16:35:19 +01:00
Gwendal Roué f07eee3ca7 DispatchQueue creation cleanup 2018-12-01 16:22:05 +01:00
Gwendal Roué 769b247da9 Merge pull request #449 from groue/feature/fixEmptyContainersJSONEncoding
Fix JSON encoding of empty containers
2018-11-28 12:24:14 +01:00
Gwendal Roué ef54efcb75 Cleanup 2018-11-28 09:11:36 +01:00
Gwendal Roué f41112c071 Documentation 2018-11-28 08:46:48 +01:00
Gwendal Roué e8ad816de5 CHANGELOG 2018-11-28 08:41:30 +01:00
Gwendal Roué 32f1a7ae0f Fix JSON encoding of empty arrays and dictionaries 2018-11-28 08:34:32 +01:00
Gwendal Roué 3dcae6d409 Forgot that reducer factory closure throws 2018-11-25 18:35:05 +01:00
Gwendal Roué 550c016a98 Merge pull request #446 from groue/feature/ValueReducerFactory
ValueObservation: delayed reducer creation
2018-11-25 18:24:35 +01:00
Gwendal Roué e092e8b3ec CHANGELOG 2018-11-25 15:42:34 +01:00
Gwendal Roué 1b53bf9ea2 Documentation 2018-11-25 15:27:26 +01:00
Gwendal Roué 3f001ba04d ValueObservation now accept a reducer factory 2018-11-25 15:18:03 +01:00
Gwendal Roué 87c4775421 ValueObservation creates a reducer when its starts 2018-11-25 14:26:04 +01:00
Gwendal Roué 2e3f2f9d61 Tests for reducer queue labels 2018-11-25 09:35:17 +01:00
Gwendal Roué 798b727d7f Reducer queue honors qos and targetQueue configuration 2018-11-25 09:35:04 +01:00
Gwendal Roué 54361617fe Remove headers 2018-11-25 09:33:55 +01:00
Gwendal Roué 417b830b61 CHANGELOG menu 2018-11-25 07:51:08 +01:00
Gwendal Roué b757a44a77 CHANGELOG menu 2018-11-25 07:47:57 +01:00
Gwendal Roué 6b78be51e2 CHANGELOG 2018-11-24 23:22:12 +01:00
Gwendal Roué 466140e699 Merge pull request #445 from groue/feature/qos
Quality of service and target dispatch queue
2018-11-24 23:18:57 +01:00
Gwendal Roué 4e1eea5743 Run run qos and targetQueue tests on Xcode 9.3, iOS 9.0
We lack dispatchPrecondition(condition:)
2018-11-24 21:46:50 +01:00
Gwendal Roué 267b4f958d Remove useless availability check 2018-11-24 21:22:47 +01:00
Gwendal Roué 9c71061629 Tests for QoS 2018-11-24 21:14:35 +01:00
Gwendal Roué 40ba0a7e8f CHANGELOG 2018-11-24 20:57:43 +01:00
Gwendal Roué bf6a101338 dispatchPrecondition(condition:) iOS availability 2018-11-24 20:56:36 +01:00
Gwendal Roué 736db6a546 Confiiguration.qos and targetQueue 2018-11-24 20:48:17 +01:00
Gwendal Roué 6a10ad0e11 Merge pull request #444 from groue/feature/ValueObservationCombine
Combine Value Observations
2018-11-24 19:39:51 +01:00
Gwendal Roué a521c89962 Documentation 2018-11-24 19:39:15 +01:00
Gwendal Roué b155ab742a Documentation 2018-11-24 19:38:24 +01:00
Gwendal Roué 4376e7519f Documentation 2018-11-24 14:55:15 +01:00
Gwendal Roué 42f13a621a Documentation 2018-11-24 14:53:23 +01:00
Gwendal Roué 8a9ccccf93 Documentation 2018-11-24 14:47:34 +01:00
Gwendal Roué e3a8bfda6f Documentation 2018-11-24 14:37:36 +01:00
Gwendal Roué a5c291e7a8 CHANGELOG 2018-11-24 14:35:27 +01:00
Gwendal Roué 71b75ee265 Documentation 2018-11-24 14:27:41 +01:00
Gwendal Roué 3f1db5aa10 Cleanup 2018-11-24 14:22:04 +01:00
Gwendal Roué 5ff519afcb Documentation 2018-11-24 13:50:36 +01:00
Gwendal Roué 41d814b540 Tests for ValueObservation combine 2018-11-24 12:57:24 +01:00
Gwendal Roué 326ef19fe9 ValueObservation combination 2018-11-24 11:38:47 +01:00
Gwendal Roué 796644edda Fix test
Concurrency is hard
2018-11-23 07:41:31 +01:00
Gwendal Roué 03b51ee899 Second failed test :-( 2018-11-22 09:34:10 +01:00
Gwendal Roué a2af4fb99a Merge pull request #443 from groue/feature/updateChanges
In place record update
2018-11-22 08:16:09 +01:00
Gwendal Roué e95119130c Documentation tweaks 2018-11-22 08:14:00 +01:00
Gwendal Roué 9735d8b74e Record Comparison documentation 2018-11-21 23:08:53 +01:00
Gwendal Roué f4c0eaa912 updateChanges(_:with:) documentation 2018-11-21 23:03:30 +01:00
Gwendal Roué d6e7d74a12 Cleanup 2018-11-21 22:27:33 +01:00
Gwendal Roué 771c85581c Fix documentation typo 2018-11-21 22:13:07 +01:00
Gwendal Roué 1baca23500 CHANGELOG 2018-11-21 22:12:52 +01:00
Gwendal Roué cc2a2a3545 Non-mutating version of updateChanges 2018-11-21 22:09:41 +01:00
Gwendal Roué 72a2408fce CHANGELOG 2018-11-21 22:08:05 +01:00
Gwendal Roué 0cd1ca11ef TODO 2018-11-21 21:48:34 +01:00
Gwendal Roué c04e6ad86d Tests for updateChanges(_:with:) 2018-11-21 21:48:24 +01:00
Gwendal Roué 3e67a1a021 Why use fileprivate when private is enough? 2018-11-21 20:33:21 +01:00
Gwendal Roué a3e62d8734 Factor updateChanges 2018-11-21 20:28:22 +01:00
Gwendal Roué f5bfb9df95 MutablePersistableRecord.updateChanges(_:with:) 2018-11-21 08:37:51 +01:00
Gwendal Roué d45ed56b64 Fix documentation typo 2018-11-19 09:01:26 +01:00
Gwendal Roué 59175a6b4d DatabasePool: block reader until concurrent fetch has been executed 2018-11-18 17:18:29 +01:00
Gwendal Roué f4e77c7700 Fix Swift 4.1 "expression was too complex to be solved in reasonable time" error 2018-11-18 17:05:10 +01:00
Gwendal Roué cbc3467e2d Database.beginSnapshotIsolation() 2018-11-18 16:49:51 +01:00
Gwendal Roué 65cc0bb2b3 Cache frequently used statements 2018-11-18 16:49:14 +01:00
Gwendal Roué 7e548aee13 Cleanup SchemaInfo 2018-11-18 15:47:11 +01:00
Gwendal Roué 8d18b06e5d Merge pull request #442 from groue/feature/reindex
Reindex
2018-11-17 22:12:34 +01:00
Gwendal Roué 55c8d350b8 CHANGELOG 2018-11-17 19:17:25 +01:00
Gwendal Roué 064f1005e5 CHANGELOG 2018-11-17 19:12:20 +01:00
Gwendal Roué 53adad16e5 Tests for Database.reindex(collation:) 2018-11-17 18:56:38 +01:00
Gwendal Roué 466a1ad4d5 Database.reindex(collation:) 2018-11-17 18:56:29 +01:00
Gwendal Roué f80f59cc38 Tweaks to demo app 2018-11-17 18:41:46 +01:00
Gwendal Roué ead2b13362 Optimize value observation for views that feed from a single table
By removing views from the observed database region, we allow the "single-table observation optimization" to kick in.

Thank you @foxware00 for revealing this opportunity in #441 :-)
2018-11-17 16:29:31 +01:00
Gwendal Roué 0ea9a1ce0d Use SchemaInfo more 2018-11-17 15:59:09 +01:00
Gwendal Roué 3b7801efff Cache full database schema 2018-11-17 15:38:55 +01:00
Gwendal Roué 5efbbe9f0c Typo 2018-11-17 14:13:58 +01:00
Gwendal Roué d868b7e1ce Test ValueObservation with database queue and pool 2018-11-17 14:12:03 +01:00
Gwendal Roué 60358ba0c0 CHANGELOG 2018-11-17 13:43:03 +01:00
Gwendal Roué b6eb5ab399 ValueObservation: tests for region arrays 2018-11-17 13:26:14 +01:00
Gwendal Roué b9ab74cb1d ValueObservation: support region arrays (address #441) 2018-11-17 13:25:55 +01:00
Gwendal Roué d3fd838c6c DatabaseRegion cleanup and documentation
Goal: improve understanding of observation performance.
Context: https://github.com/groue/GRDB.swift/issues/441
2018-11-17 12:46:01 +01:00
Gwendal Roué 1108ba4bf2 DatabaseError gets a default message, derived from its resultCode 2018-11-16 09:07:52 +01:00
Gwendal Roué 49de0e0f49 Call sqlite3_close() even if opening failed
Thanks to https://github.com/feistydog/FeistyDB/commit/6859f622797480656f8897c2db5e620e6a98c858
2018-11-16 08:48:25 +01:00
Gwendal Roué d56b62a65f Flag ValueReducer as experimental 2018-11-10 12:31:35 +01:00
Gwendal Roué c28a4d4061 Remove public initializers of utility value reducers 2018-11-10 12:29:31 +01:00
Gwendal Roué 3971b43894 Cleanup 2018-11-05 09:08:14 +01:00
Gwendal Roué 9fc5c2680b Typo 2018-11-05 09:08:01 +01:00
Gwendal Roué 0f8156afed Cleanup demo app 2018-11-04 03:50:19 +01:00
Gwendal Roué da3f14c29a Typo 2018-11-03 16:39:36 +01:00
Gwendal Roué dbacf3acf0 Documentation 2018-11-02 18:04:48 +01:00
Gwendal Roué 961138b09b v3.5.0 2018-11-02 17:01:39 +01:00
Gwendal Roué 6c6e46b8d6 Merge branch 'development' 2018-11-02 16:55:53 +01:00
Gwendal Roué 0cbf259ed1 Merge pull request #435 from groue/feature/ValueObservation
Improved support for values observation
2018-11-02 16:47:22 +01:00
Gwendal Roué 07bf5882fe Adding more reactive engines is no longer hard 2018-11-02 16:28:06 +01:00
Gwendal Roué b3c7fec676 Documentation 2018-11-02 13:56:52 +01:00
Gwendal Roué 296a1d5b12 CHANGELOG 2018-11-02 13:18:27 +01:00
Gwendal Roué 8c5e3df546 Documentation 2018-11-02 13:04:22 +01:00
Gwendal Roué 50213c925f Documentation 2018-11-02 13:00:42 +01:00
Gwendal Roué a1a5165bd2 Documentation 2018-11-02 12:48:48 +01:00
Gwendal Roué 7d9e87088d Rename ValueObservation.isReadOnly to requiresWriteAccess 2018-11-02 12:31:26 +01:00
Gwendal Roué c300cf2a38 Documentation 2018-11-02 12:15:04 +01:00
Gwendal Roué c48d2e484a Documentation 2018-11-02 12:10:49 +01:00
Gwendal Roué 2bc8f33249 Cleanup 2018-11-02 11:49:03 +01:00
Gwendal Roué 257fc8b66a Cleanup 2018-11-02 08:35:16 +01:00
Gwendal Roué bc274a603c Documentation 2018-11-02 08:35:04 +01:00
Gwendal Roué ab7970d470 Documentation 2018-11-01 22:58:20 +01:00
Gwendal Roué 087a899f13 Rename ValueObservation.tracking(withUniquing:fetch) to ValueObservation.tracking(_:fetchDistinct) 2018-11-01 22:18:58 +01:00
Gwendal Roué 842eaf0816 ValueObservation: perform uniquing by default 2018-11-01 21:46:59 +01:00
Gwendal Roué f7b79e05f6 Attempt at addressing https://github.com/groue/GRDB.swift/issues/430 2018-11-01 16:59:39 +01:00
Gwendal Roué 1867ee91de Documentation 2018-11-01 13:38:54 +01:00
Gwendal Roué d53412d404 Documentation 2018-11-01 13:22:02 +01:00
Gwendal Roué 74ca85e52c More links to the demo app 2018-11-01 13:16:04 +01:00
Gwendal Roué 51942046b9 Avoid the "No output has been received in the last 10m0s" error on Travis 2018-11-01 13:10:52 +01:00
Gwendal Roué 38e1cc9a27 Use ValueObservation is demo application 2018-11-01 12:58:17 +01:00
Gwendal Roué 7e8ebed7a8 Documentation 2018-10-31 19:39:44 +01:00
Gwendal Roué eb95562b73 Documentation 2018-10-31 19:37:35 +01:00
Gwendal Roué 44af4e62a6 Documentation 2018-10-31 19:35:49 +01:00
Gwendal Roué 30363b4a5b Tests for ValueObservation.map 2018-10-31 19:02:47 +01:00
Gwendal Roué bb02d9d857 ValueObservation.map 2018-10-31 12:07:08 +01:00
Gwendal Roué 9babbcbcb3 README: foster ValueObservation 2018-10-31 08:59:50 +01:00
Gwendal Roué 04de6193c0 Documentation 2018-10-31 07:37:05 +01:00
Gwendal Roué 6fa72ebea1 Documentation 2018-10-30 13:44:05 +01:00
Gwendal Roué 0e51a0ff65 Documentation 2018-10-30 13:40:32 +01:00
Gwendal Roué a276a49a26 CHANGELOG 2018-10-30 13:37:58 +01:00
Gwendal Roué 741f0b2a43 CHANGELOG 2018-10-30 13:37:05 +01:00
Gwendal Roué 3d21773496 CHANGELOG 2018-10-30 13:33:24 +01:00
Gwendal Roué cca716e1ab Cleanup 2018-10-30 08:49:36 +01:00
Gwendal Roué 8e13cb4e6c Cleanup 2018-10-30 07:46:41 +01:00
Gwendal Roué c4d328783f Documentation 2018-10-30 07:24:27 +01:00
Gwendal Roué 22b5990669 Documentation 2018-10-29 23:04:00 +01:00
Gwendal Roué d3838d1d73 ValueObservation error handling 2018-10-29 21:13:14 +01:00
Gwendal Roué cdd7579104 Documentation 2018-10-29 19:40:37 +01:00
Gwendal Roué 4e3b7c14a9 Documentation 2018-10-29 19:39:44 +01:00
Gwendal Roué b4b824c360 dbQueue.start(observation) -> observation.start(in: dbQueue) 2018-10-29 19:31:04 +01:00
Gwendal Roué 6f86cbf0c4 Documentation 2018-10-29 18:48:16 +01:00
Gwendal Roué f68b1cd2c3 Documentation 2018-10-29 18:44:48 +01:00
Gwendal Roué 53f98a7bf6 Documentation 2018-10-29 18:42:04 +01:00
Gwendal Roué 77de519fcc More tests for read/write observations 2018-10-29 18:40:12 +01:00
Gwendal Roué 739c325079 Documentation 2018-10-29 18:34:11 +01:00
Gwendal Roué 10650704b5 Documentation (todo: document error handling) 2018-10-29 18:32:54 +01:00
Gwendal Roué 735394669d Documentation 2018-10-29 18:28:10 +01:00
Gwendal Roué 4e40d755f4 Documentation 2018-10-29 18:26:27 +01:00
Gwendal Roué e5f43e341b ValueScheduling.unsafe guarantees that initial value is notified on the dispatch queue which starts the observation 2018-10-29 18:23:38 +01:00
Gwendal Roué 72c5769e8b ValueScheduling.unsafe 2018-10-29 13:59:02 +01:00
Gwendal Roué 669b9c4e91 Test for the ValueReducer documented in README 2018-10-29 13:31:42 +01:00
Gwendal Roué a489959780 Typo 2018-10-29 13:10:04 +01:00
Gwendal Roué 1985b9129a Fix SPM build 2018-10-29 13:09:56 +01:00
Gwendal Roué f7712473aa Move Sequence.allSatisfy where it is used: tests 2018-10-29 12:27:39 +01:00
Gwendal Roué f582683f20 Move remove(transactionObserver:) to DatabaseReader 2018-10-29 12:26:12 +01:00
Gwendal Roué a4b35729df Documentation 2018-10-29 12:22:16 +01:00
Gwendal Roué 191607fc13 Documentation 2018-10-29 09:18:29 +01:00
Gwendal Roué 5a540e8850 Documentation 2018-10-29 09:16:42 +01:00
Gwendal Roué f59dba711c Try with "tracking" 2018-10-29 09:15:18 +01:00
Gwendal Roué 93326307fa Documentation 2018-10-29 09:00:15 +01:00
Gwendal Roué 8d6ec6297a Backport Sequence.allSatisfy in Swift 4.1 2018-10-29 08:52:59 +01:00
Gwendal Roué 1d47853abe Documentation 2018-10-29 08:47:51 +01:00
Gwendal Roué 38e4027599 Documentation 2018-10-29 08:41:22 +01:00
Gwendal Roué 29b54dd37d Documentation 2018-10-29 08:17:35 +01:00
Gwendal Roué 03d2bc43ac Documentation 2018-10-29 08:07:28 +01:00
Gwendal Roué 22ed0fb1a1 Documentation 2018-10-29 08:00:39 +01:00
Gwendal Roué 489454b0d4 add(observation:observation) -> start(observation) 2018-10-29 07:19:36 +01:00
Gwendal Roué 840f8358b5 Documentation 2018-10-29 06:51:56 +01:00
Gwendal Roué 470e1534dc Documentation 2018-10-28 22:29:15 +01:00
Gwendal Roué 158177364b Documentation 2018-10-28 22:04:39 +01:00
Gwendal Roué de2823b613 ValueObservation: StatementColumnConvertible tests 2018-10-28 19:28:19 +01:00
Gwendal Roué 0d5adfe5a9 ValueObservation: FetchableRecord & DatabaseValueConvertible tests 2018-10-28 19:16:55 +01:00
Gwendal Roué 0010be4e56 ValueObservation: row tests 2018-10-28 18:40:21 +01:00
Gwendal Roué 62f6cfe6b5 ValueObservation: count tests 2018-10-28 17:41:18 +01:00
Gwendal Roué 31e6ddeac3 ValueObservation: test scheduling 2018-10-28 17:32:31 +01:00
Gwendal Roué f2c3c213cc Read-only observation is enforced. When not read-only, savepoint is enforced. 2018-10-28 17:04:36 +01:00
Gwendal Roué f303664808 Cleanup 2018-10-28 16:20:57 +01:00
Gwendal Roué 471808fa3b More ValueObseervation tests: fetch, with and without uniquing 2018-10-28 16:13:58 +01:00
Gwendal Roué cbe505f4a4 Cleanup 2018-10-28 16:13:34 +01:00
Gwendal Roué 087989fc89 More ValueObseervation tests: extent 2018-10-28 15:57:27 +01:00
Gwendal Roué a519a4ab86 Documentation 2018-10-28 15:38:01 +01:00
Gwendal Roué 627e8ec969 Fix wrong documentation 2018-10-28 15:35:25 +01:00
Gwendal Roué 2b78479a5e More ValueReducer tests: error 2018-10-28 15:32:55 +01:00
Gwendal Roué e0a9cced4a First tests for ValueObservation: focus on reducers 2018-10-28 13:27:43 +01:00
Gwendal Roué 26ba5768b2 whitespace 2018-10-28 13:26:40 +01:00
Gwendal Roué 09581c6ae0 ValueObservation factory requires a DatabaseRegionConvertible. Introduce AnyDatabaseRegionConvertible. 2018-10-28 11:45:49 +01:00
Gwendal Roué fc3aca792f Replace InitialDispatch with ValueScheduling 2018-10-28 11:28:31 +01:00
Gwendal Roué a043c4c29e QoS are hard 2018-10-27 23:01:24 +02:00
Gwendal Roué ec5451ee70 Cleanup 2018-10-27 17:18:03 +02:00
Gwendal Roué 7c4462641e ValueObservation creation is always done with a factory initializer 2018-10-27 17:16:03 +02:00
Gwendal Roué 82efe7ca23 AnyValueReducer 2018-10-27 17:06:23 +02:00
Gwendal Roué 052d2e3008 Value (string, int, etc.) observation, with uniquing 2018-10-27 16:41:42 +02:00
Gwendal Roué de227bdce1 Bake uniquing right into ValueObservation: introduce ValueReducer 2018-10-27 16:12:42 +02:00
Gwendal Roué 697b2af61d Wrap long lines 2018-10-27 05:11:19 +02:00
Gwendal Roué ff4f6f3b12 Cleanup 2018-10-27 04:59:24 +02:00
Gwendal Roué 31b688d801 ValueObservationn has a QoS 2018-10-27 04:24:17 +02:00
Gwendal Roué f694437f5b Add missing public qualifiers 2018-10-27 04:23:45 +02:00
Gwendal Roué 69853d7901 Now that user implementations of DatabaseWriter are no longer supported...
...stop pretending we have to implement concurrentRead
on top of the deprecated readFromCurrentState.

And this fixes #419 :-)
2018-10-26 16:53:30 +02:00
Gwendal Roué abe6957c85 Typo 2018-10-26 16:42:27 +02:00
Gwendal Roué 08b103f5f5 DatabaseReader and DatabaseWriter are no longer available for user types
- stop testing compatibility with user types
- document that they are no longer available for user types (readme, changelog)
2018-10-26 16:42:14 +02:00
Gwendal Roué 9c71356e3d Honor ValueObservation.readonly 2018-10-26 09:10:26 +02:00
Gwendal Roué 2341523c41 API cleanup 2018-10-26 08:50:59 +02:00
Gwendal Roué 0df4815086 Move ValueObservation support to DatabaseReader 2018-10-25 20:39:04 +02:00
Gwendal Roué fe0f238f32 Cleanup 2018-10-25 08:49:57 +02:00
Gwendal Roué fda04a105d ValueObservation: extract callbacks 2018-10-25 08:39:52 +02:00
Gwendal Roué e5d97c15ad Looking for a good API 2018-10-25 08:05:55 +02:00
Gwendal Roué ce95ff7278 Move towards observation from reader 2018-10-24 19:17:11 +02:00
Gwendal Roué 33927e7f4d FetchResultsObserver 2018-10-23 13:24:46 +02:00
Gwendal Roué 6a4d9fb8fc Merge pull request #431 from KyleLeneau/codeable-json-sync-playground
Working on a Codable JSON sync example
2018-10-17 19:14:49 +02:00
Kyle LeNeau cf33d78f49 Working on a Codable JSON sync example 2018-10-14 12:49:37 -07:00
Gwendal Roué 0d89aa911b Documentation 2018-10-09 08:35:17 +02:00
Gwendal Roué d521a99d87 Typo fix 2018-10-09 08:10:56 +02:00
Gwendal Roué a848d864ce Documentation 2018-10-08 21:59:04 +02:00
Gwendal Roué 759c1088a1 v3.4.0 2018-10-08 21:37:58 +02:00
Gwendal Roué 2d004a1a26 Merge branch 'development' 2018-10-08 21:22:10 +02:00
Gwendal Roué 35e1de495e Merge pull request #428 from groue/feature/SQLite-3.25.2
Upgrade custom SQLite builds to version 3.25.2
2018-10-08 21:19:51 +02:00
Gwendal Roué 697709c82f thank you note 2018-10-08 19:19:45 +02:00
Gwendal Roué 9ad476235d CHANGELOG 2018-10-08 19:17:02 +02:00
Gwendal Roué dadc5c3c58 Fix a test for syntax error that fails with SQLite 3.25.2 2018-10-08 19:16:54 +02:00
Gwendal Roué 3be3a51cdc Fix a compiler warning 2018-10-08 19:13:12 +02:00
Gwendal Roué 7bdbfb77dd Upgrade SQLite version in documentation 2018-10-08 19:11:24 +02:00
Gwendal Roué 8e0c01ef70 SQLite 3.25.2 2018-10-08 19:03:41 +02:00
Gwendal Roué 1c5cecf568 Merge pull request #423 from groue/feature/annotation
Association Aggregates
2018-10-08 13:59:14 +02:00
Gwendal Roué 9330468f92 Documentation 2018-10-08 09:10:48 +02:00
Gwendal Roué fcbea047cc Documentation 2018-10-08 09:08:37 +02:00
Gwendal Roué 619b73ea76 Documentation 2018-10-08 09:04:14 +02:00
Gwendal Roué 597d745e37 Documentation 2018-10-08 09:02:53 +02:00
Gwendal Roué 52ffb4a02c Documentation 2018-10-08 08:59:56 +02:00
Gwendal Roué c007c04afb Documentation 2018-10-08 08:58:21 +02:00
Gwendal Roué 4b92968912 Documentation 2018-10-08 08:56:36 +02:00
Gwendal Roué 2938a95270 Inline documentation 2018-10-08 08:24:14 +02:00
Gwendal Roué 5b2e9cdaa5 Fix link 2018-10-07 20:01:39 +02:00
Gwendal Roué 5736cd2740 CHANGELOG 2018-10-07 19:59:35 +02:00
Gwendal Roué 6b05617d8d Documentation 2018-10-07 19:10:37 +02:00
Gwendal Roué 58470fa959 Documentation 2018-10-07 18:50:50 +02:00
Gwendal Roué 43c04268ee Documentation 2018-10-07 18:47:21 +02:00
Gwendal Roué 3ba8d7ae60 Documentation 2018-10-07 18:45:17 +02:00
Gwendal Roué 97c22cde40 Documentation 2018-10-07 18:26:10 +02:00
Gwendal Roué 8a983274af Documentation 2018-10-07 18:25:33 +02:00
Gwendal Roué 445ec18d6e Documentation 2018-10-07 18:20:22 +02:00
Gwendal Roué a441b1d24d Documentation 2018-10-07 18:18:51 +02:00
Gwendal Roué 23743680d2 Documentation 2018-10-07 18:11:52 +02:00
Gwendal Roué afaabfe872 Documentation 2018-10-07 18:09:53 +02:00
Gwendal Roué 53114ea491 Documentation 2018-10-07 18:05:41 +02:00
Gwendal Roué 12745b2882 Documentation 2018-10-07 18:03:38 +02:00
Gwendal Roué 19291e2501 Documentation 2018-10-07 17:55:49 +02:00
Gwendal Roué 3890d2659f Documentation 2018-10-07 17:51:51 +02:00
Gwendal Roué 68a8592bcd Documentation 2018-10-07 17:42:55 +02:00
Gwendal Roué 445187c276 Documentation 2018-10-07 17:37:55 +02:00
Gwendal Roué 55707e67d4 Documentation 2018-10-07 17:31:58 +02:00
Gwendal Roué 82435db722 Documentation 2018-10-07 17:29:59 +02:00
Gwendal Roué a47a0c9d2d Typo 2018-10-07 17:17:41 +02:00
Gwendal Roué 5a24726cf1 Documentation 2018-10-07 17:08:24 +02:00
Gwendal Roué 7ecacaaccc Documentation 2018-10-07 16:34:49 +02:00
Gwendal Roué 704da35576 aliased(CodingKey), annotated(with: aggregate, ...), count and isEmpty are now properties 2018-10-07 16:20:13 +02:00
Gwendal Roué 2774aaf292 aggregate alias cleanup 2018-10-07 15:40:38 +02:00
Gwendal Roué 8ffeb28b02 Tests for association aggregate operators 2018-10-07 15:20:24 +02:00
Gwendal Roué 5f92209c59 AssociationAggregates: logic, arithmetic, and comparison operators 2018-10-07 12:22:48 +02:00
Gwendal Roué 4f8e97a07c AssociationAggregate is now generic on its anchor type only 2018-10-07 12:08:25 +02:00
Gwendal Roué 39bc140dc8 Rename Annotation to AssociationAggregate 2018-10-07 11:39:46 +02:00
Gwendal Roué 0838d5903e Documentation 2018-10-06 15:46:47 +02:00
Gwendal Roué a0cd603c61 Nicer SQL generation for isEmpty annotation 2018-10-06 14:50:08 +02:00
Gwendal Roué 3ef8083043 testAnnotationWithJoiningMethodAndTableAliasAndSQLSnippet 2018-10-06 14:29:48 +02:00
Gwendal Roué 35ed13c940 Test for annotations in HAVING clauses 2018-10-06 14:15:35 +02:00
Gwendal Roué 1da41c7fe5 TODO 2018-10-05 18:50:34 +02:00
Gwendal Roué 01069ee998 fix typo 2018-10-05 18:50:34 +02:00
Gwendal Roué ebbf858da4 Documentation 2018-10-05 18:50:34 +02:00
Gwendal Roué 047a95f2c9 Improve sample code 2018-10-05 18:50:34 +02:00
Gwendal Roué 7508811e40 Fix typo 2018-10-05 18:50:34 +02:00
Gwendal Roué 2ae8e236c0 Aggregates are no longer a missing association feature :-) 2018-10-05 18:50:34 +02:00
Gwendal Roué a13903e7a1 Documentation 2018-10-05 18:50:34 +02:00
Gwendal Roué c25bc1d5fa Documentation 2018-10-05 18:50:34 +02:00
Gwendal Roué d004372b63 More cleanup 2018-10-05 18:50:34 +02:00
Gwendal Roué 789248e369 minor 2018-10-05 18:50:34 +02:00
Gwendal Roué 3404cc574b CHANGELOG 2018-10-05 18:50:34 +02:00
Gwendal Roué 2ca049c2e4 Cleanup 2018-10-05 18:50:34 +02:00
Gwendal Roué 89054c8165 typo 2018-10-05 18:50:34 +02:00
Gwendal Roué 24e8ee2d00 Stabilize annotation aliases, and allow aggregate any expression 2018-10-05 18:50:34 +02:00
Gwendal Roué f69c79bc1a typo 2018-10-05 18:50:34 +02:00
Gwendal Roué 82765aba1d typo 2018-10-05 18:50:34 +02:00
Gwendal Roué bcc177ff7d typo 2018-10-05 18:50:34 +02:00
Gwendal Roué 3bfef630f9 typo 2018-10-05 18:50:34 +02:00
Gwendal Roué 6a6d58da6c typo 2018-10-05 18:50:34 +02:00
Gwendal Roué 6e7065de36 Annotation documentation 2018-10-05 18:50:34 +02:00
Gwendal Roué f60152ed2e Add Inflections.swift to GRDBWatchOS 2018-10-05 18:50:34 +02:00
Gwendal Roué f6b0c0cc65 Rename test 2018-10-05 18:50:34 +02:00
Gwendal Roué c16b2bcb57 The count annotation has to be distinct 2018-10-05 18:50:34 +02:00
Gwendal Roué 5d70ef93c8 Test that filter(key:), orderByPrimaryKey(), and groupByPrimaryKey() capture the table name 2018-10-05 18:50:34 +02:00
Gwendal Roué 68d76eca01 Annotations: avg, min, max, sum 2018-10-05 18:50:33 +02:00
Gwendal Roué 83453e1b11 Make private a test helper class 2018-10-05 18:50:33 +02:00
Gwendal Roué 903694d095 First annotation: HasManyAssociaton.count 2018-10-05 18:50:33 +02:00
Gwendal Roué 168d2850ab Introduce groupByPrimaryKey() 2018-10-05 18:50:33 +02:00
Gwendal Roué fc692bdb8a Merge pull request #427 from groue/feature/cursor-reset
Have cursors reset SQLite statements in deinit
2018-10-05 12:23:08 +02:00
Gwendal Roué d963e688be CHANGELOG 2018-10-05 08:24:34 +02:00
Gwendal Roué 6157ab0583 Have cursors reset their statement when they are deinitialized
This is the real fix for #424. GRDB used to keep unfinished SQLite statements around. Now cursors properly reset their statement when they are done. We no longer have to clear the statement cache before a backup.
2018-10-05 08:13:23 +02:00
Gwendal Roué ad61c72988 Remove two invalid tests that use cursor outside of their protected dispatch queue 2018-10-05 08:04:37 +02:00
Gwendal Roué dd4b651938 Merge pull request #425 from groue/feature/robust-backup
Fix "destination database is in use " error during database backup
2018-10-04 15:59:43 +02:00
Gwendal Roué 7cd50872cf Merge branch 'master' into development 2018-10-04 13:40:43 +02:00
Gwendal Roué fc5e92954b SQLCipher, too, can't erase a database if there are cached prepared statements. 2018-10-04 13:34:35 +02:00
Gwendal Roué 6c7ac25fb8 Remove Carthage from suggested contributions (#408 and #262 have helped a lot) 2018-10-04 13:20:51 +02:00
Gwendal Roué 86cff20f99 New suggested contribution: "Records: Splitting Database Encoding from Ability to Write in the Database" 2018-10-04 13:14:29 +02:00
Gwendal Roué 7a628bf23f Add minimal failing test for #424 2018-10-04 08:35:02 +02:00
Gwendal Roué 9e8d08f579 CHANGELOG 2018-10-04 07:59:50 +02:00
Gwendal Roué 8c3606fe4b Fix failing test for #424 2018-10-04 07:58:36 +02:00
Gwendal Roué 01c9e9e1e1 Failing test for #424 2018-10-03 13:55:55 +02:00
Gwendal Roué ff28c02f21 Merge branch 'master' into development 2018-10-03 13:00:02 +02:00
Gwendal Roué 1426c7fd38 New suggested contribution: Custom FTS5 Auxiliary Functions 2018-10-03 12:57:21 +02:00
Gwendal Roué 366460bc62 Merge pull request #422 from groue/feature/AssociationMerge
Refining Association Requests
2018-09-30 16:39:33 +02:00
Gwendal Roué 16c62999fa More merging tests (and fix a bug with ordering) 2018-09-30 15:10:54 +02:00
Gwendal Roué 2cd3a7e0c9 High-level test for association request refining
Here we test the sample code in AssociationBasics.md
2018-09-30 14:51:52 +02:00
Gwendal Roué 9958e7b96c Documentation and cleanup 2018-09-30 13:57:31 +02:00
Gwendal Roué 8319c70315 CHANGELOG 2018-09-30 13:32:44 +02:00
Gwendal Roué 45ff5f2fa1 One less known issue with associations :-) 2018-09-30 13:23:35 +02:00
Gwendal Roué df51d2887a Documentation tweaks 2018-09-30 13:22:05 +02:00
Gwendal Roué 9c37237f7b New "Refining Association Requests" documentation chapter 2018-09-30 13:16:57 +02:00
Gwendal Roué 6ecb7a40d0 associations are not merged when they don't have the same key 2018-09-30 06:48:20 +02:00
Gwendal Roué 52ec6c6cd2 Merge associations: 2018-09-30 06:35:15 +02:00
Gwendal Roué ba11d7be66 Merge associations: SQL tests 2018-09-30 05:46:44 +02:00
Gwendal Roué 4c58fd5111 Merge associations: scope tests WIP 2018-09-29 20:28:28 +02:00
Gwendal Roué 4bde81db4f Merge associations: scope tests WIP 2018-09-29 15:18:53 +02:00
Gwendal Roué 37a9999b35 Merge associations: including wins over joining 2018-09-29 14:37:53 +02:00
Gwendal Roué 33b40637a8 Merge associations 2018-09-29 14:16:56 +02:00
Gwendal Roué e7fd075936 Early detection of association key conflict 2018-09-29 12:40:11 +02:00
Gwendal Roué cc4a9fa2e2 Demo screenshot fixes 2018-09-23 15:48:41 +02:00
Gwendal Roué 56f3bdc390 Demo screenshot fixes 2018-09-23 15:48:08 +02:00
Gwendal Roué ba5537692f Demo screenshot fixes 2018-09-23 15:47:18 +02:00
Gwendal Roué 5595046341 Fix documentation 2018-09-23 12:39:21 +02:00
Gwendal Roué ad844f6ba5 Merge branch 'development' 2018-09-23 10:41:13 +02:00
Gwendal Roué baf8dbc881 v3.3.1 2018-09-23 10:39:55 +02:00
Gwendal Roué ad672395de Fix screenshot 2018-09-23 10:18:28 +02:00
Gwendal Roué 923fab769f final tweaks 2018-09-23 09:59:29 +02:00
Gwendal Roué 4e3dc03422 inner links 2018-09-23 07:09:37 +02:00
Gwendal Roué d96212ca59 CHANGELOG 2018-09-22 20:46:13 +02:00
Gwendal Roué d16022a33a README 2018-09-22 20:38:27 +02:00
Gwendal Roué 5cb22125aa README 2018-09-22 20:35:14 +02:00
Gwendal Roué 6ee77df2dd Layout 2018-09-22 20:31:03 +02:00
Gwendal Roué ea54b06e28 Layout 2018-09-22 20:30:27 +02:00
Gwendal Roué 6b33c08b26 Demo app README 2018-09-22 15:01:22 +02:00
Gwendal Roué cb16bf549f Demo app README 2018-09-22 14:57:22 +02:00
Gwendal Roué 9a8b60a8a7 PlayerEditionViewController saves in the database 2018-09-22 14:55:32 +02:00
Gwendal Roué dec965d610 Demo app README 2018-09-22 14:06:00 +02:00
Gwendal Roué adf3e65971 Demo app README 2018-09-22 14:01:45 +02:00
Gwendal Roué c437e4a2ef Demo app README 2018-09-22 13:47:38 +02:00
Gwendal Roué 4dd9d2e1fe Demo app README.md 2018-09-22 13:46:37 +02:00
Gwendal Roué 185c3cbbf9 Update documentation inner links 2018-09-22 13:41:46 +02:00
Gwendal Roué ffbf4d2c87 Layout 2018-09-22 13:34:41 +02:00
Gwendal Roué 464cd0db7d Layout 2018-09-22 13:32:53 +02:00
Gwendal Roué e2e00f9b40 Layout 2018-09-22 13:30:16 +02:00
Gwendal Roué 2c2c75b0f4 Layout 2018-09-22 13:29:47 +02:00
Gwendal Roué 8ef7547c8e Promote demo app in main README.md 2018-09-22 13:21:11 +02:00
Gwendal Roué d82daaa398 CHANGELOG 2018-09-22 13:00:34 +02:00
Gwendal Roué a5a8b2ac40 Fix failing test for custom FTS5 tokenizer in DatabasePool
Tokenizer are now added to new reader connections.
2018-09-22 13:00:34 +02:00
Gwendal Roué bdcbee37f4 Failing test for custom FTS5 tokenizer in DatabasePool 2018-09-22 13:00:34 +02:00
Gwendal Roué 70508f5daa Split long line 2018-09-22 12:59:50 +02:00
Gwendal Roué 3c44180c47 PlayerEditionViewController UI tweaks 2018-09-22 12:54:25 +02:00
Gwendal Roué 3d179acc00 Demo app code cleanup
- Make Player columns private
- Simplify view controllers relationships
2018-09-22 12:32:55 +02:00
Gwendal Roué dd9ca2317c More SQL generation ideas 2018-09-20 08:22:34 +02:00
Gwendal Roué c71d4903a0 Merge branch 'release/v3.3.0' 2018-09-16 18:55:43 +02:00
Gwendal Roué d118a775ac Bump SQLCipher/src 2018-09-16 18:52:37 +02:00
Gwendal Roué e92c0c9aed Hide SQLSpecificExpressible from jazzy documentation 2018-09-16 13:39:11 +02:00
Gwendal Roué b826789349 Workaround https://github.com/realm/jazzy/issues/970 2018-09-16 13:35:56 +02:00
Gwendal Roué a09099bb02 v3.3.0 2018-09-16 12:58:36 +02:00
Gwendal Roué 914781cd7f Thank you @KyleLeneau 2018-09-16 12:16:52 +02:00
Gwendal Roué de84b084ec Merge pull request #408 from KyleLeneau/fix-carthage-tests
Getting carthage tests to pass
2018-09-16 12:11:39 +02:00
Gwendal Roué 2b6e69404e FetchedRecordsController in usage section 2018-09-16 12:09:47 +02:00
Kyle LeNeau aaca651a2e Getting Carthage tests to pass 2018-09-14 01:34:38 +09:00
Gwendal Roué 138289b646 Documentation improvement 2018-09-13 09:07:12 +02:00
Gwendal Roué d4157db4b1 CHANGELOG 2018-09-13 09:02:14 +02:00
Gwendal Roué 3bf32564a4 Merge pull request #409 from groue/feature/concurrentRead
DatabaseWriter.concurrentRead
2018-09-13 08:56:38 +02:00
Gwendal Roué 7186cd98c8 (more diff algorithms) 2018-09-13 07:31:35 +02:00
Gwendal Roué b9a878bb20 Cleanup 2018-09-11 08:56:29 +02:00
Gwendal Roué 8c479a863a Documentation 2018-09-09 20:00:03 +02:00
Gwendal Roué 58a48b73ae concurrentRead documentation 2018-09-09 19:55:07 +02:00
Gwendal Roué 2e6ed9d8f9 TODO 2018-09-09 16:03:00 +02:00
Gwendal Roué df406341c1 CHANGELOG.md 2018-09-09 16:00:53 +02:00
Gwendal Roué 41629ec9aa Future.wait() must be called only once 2018-09-09 16:00:01 +02:00
Gwendal Roué 47b42f38e3 CHANGELOG.md 2018-09-09 15:46:36 +02:00
Gwendal Roué 21209fb107 CHANGELOG.md 2018-09-09 13:46:13 +02:00
Gwendal Roué 106812c02c Fix SPM 2018-09-09 13:42:35 +02:00
Gwendal Roué da58e228c0 Document Future 2018-09-09 13:18:15 +02:00
Gwendal Roué 9bfe893908 DatabaseWriter.concurrentRead replaces readFromCurrentState 2018-09-09 13:12:35 +02:00
Gwendal Roué 03a781075e Cleanup 2018-09-06 08:50:56 +02:00
Gwendal Roué 60afc9ee06 Tweak existence checks for tables, views and triggers 2018-09-06 08:31:27 +02:00
Gwendal Roué 22165984c3 Cursor.isEmpty() 2018-09-06 08:29:57 +02:00
Gwendal Roué eebb013d06 Merge branch 'master' into development 2018-09-05 14:16:39 +02:00
Gwendal Roué 0e0ebdb2d6 Fix podspec 2018-09-05 14:09:01 +02:00
Gwendal Roué be15f89e28 Merge tag 'v3.3.0-beta1' into development
v3.3.0-beta1
2018-09-05 13:55:48 +02:00
Gwendal Roué 5d2f063c93 Merge branch 'release/v3.3.0-beta1' 2018-09-05 13:55:47 +02:00
Gwendal Roué e49c190288 Fix release date 2018-09-05 13:52:00 +02:00
Gwendal Roué d3ddf1c1bc Prepare merge on master 2018-09-05 13:36:31 +02:00
Gwendal Roué 04fc14d557 Compatibility: restore SWIFT_VERSION to 4.0 for embeddable projects 2018-09-05 13:09:27 +02:00
Gwendal Roué 603115c9a4 Tests/CocoaPods: use Swift 4.2 2018-09-05 13:04:47 +02:00
Gwendal Roué 6b60fbe50e Tests/CocoaPods/GRDBiOS: use Swift 4.2 2018-09-05 13:04:47 +02:00
Gwendal Roué 2a43869e45 Prepare v3.3.0-beta1 2018-09-05 13:04:47 +02:00
Gwendal Roué bd52dbcec0 Migrate projects to SWIFT_VERSION = 4.2 2018-09-05 13:04:47 +02:00
Gwendal Roué c9dace3089 Spot a flacky test 2018-09-05 13:04:47 +02:00
Gwendal Roué 9184cbe324 Welcome @SD10 in the thank you notice 2018-09-04 13:16:14 +02:00
Gwendal Roué 2216573acb Prefer pseudonyms 2018-09-04 13:15:20 +02:00
Gwendal Roué 2b331e3c03 Merge pull request #407 from SD10/development
Add Code of Conduct
2018-09-04 13:10:05 +02:00
Gwendal Roué 875e7779c3 More CloudKit 2018-09-04 08:54:20 +02:00
Gwendal Roué 743a56e0e4 More CloudKit 2018-09-04 08:47:20 +02:00
Gwendal Roué 6e1ef92a38 More CloudKit 2018-09-04 08:43:49 +02:00
Gwendal Roué e3ca4e42a3 CloudKit context 2018-09-04 08:24:39 +02:00
Steven Deutsch 6db4c38c74 Fix develop -> development branch name 2018-09-01 11:12:20 -05:00
Steven Deutsch 8a16f0ba42 Add CODE_OF_CONDUCT 2018-09-01 11:03:34 -05:00
Gwendal Roué 81cd30bb38 CONTRIBUTING.md 2018-09-01 16:38:35 +02:00
Gwendal Roué d26145e59e CONTRIBUTING.md 2018-09-01 16:37:37 +02:00
Gwendal Roué 2b664d5485 CONTRIBUTING.md 2018-09-01 16:06:50 +02:00
Gwendal Roué 27f8103e79 CONTRIBUTING.md 2018-09-01 15:55:44 +02:00
Gwendal Roué a5c2c618e4 CONTRIBUTING.md 2018-09-01 15:55:26 +02:00
Gwendal Roué 9d4a083193 CONTRIBUTING.md 2018-09-01 15:52:04 +02:00
Gwendal Roué 9d00f63358 CONTRIBUTING.md 2018-09-01 15:47:16 +02:00
Gwendal Roué 0ae85eed24 CONTRIBUTING.md 2018-09-01 15:43:25 +02:00
Gwendal Roué 41050094af CONTRIBUTING.md 2018-09-01 15:41:06 +02:00
Gwendal Roué 7d339edd6e CONTRIBUTING.md 2018-09-01 15:26:43 +02:00
Gwendal Roué 23d7d3f8ed CONTRIBUTING.md 2018-09-01 15:17:34 +02:00
Gwendal Roué 7bd9703540 CONTRIBUTING.md 2018-09-01 15:16:37 +02:00
Gwendal Roué 8a6e7b70ef CONTRIBUTING.md 2018-09-01 15:12:55 +02:00
Gwendal Roué 5a8c3cdafc CONTRIBUTING.md 2018-09-01 15:09:15 +02:00
Gwendal Roué 16a1cecc57 CONTRIBUTING.md 2018-09-01 15:02:05 +02:00
Gwendal Roué e367d55940 CONTRIBUTING.md 2018-09-01 14:46:07 +02:00
Gwendal Roué b45b6cd0cf CONTRIBUTING.md 2018-09-01 14:40:28 +02:00
Gwendal Roué c2535d19e9 CONTRIBUTING.md 2018-09-01 14:37:30 +02:00
Gwendal Roué fa4ca12903 CONTRIBUTING.md 2018-09-01 14:17:27 +02:00
Gwendal Roué c5444fa99d Merge pull request #396 from groue/swift4.2
Support for Xcode 10 and Swift 4.2
2018-08-31 08:24:53 +02:00
Gwendal Roué 468eaf8642 CHANGELOG 2018-08-31 08:17:50 +02:00
Gwendal Roué d9d0f62f71 Travis: please test Swift 4.0, 4.2, and Xcode 9.3, 9.4, and 10. 2018-08-30 16:34:30 +02:00
Gwendal Roué 8b4eb55568 Use Cocoapods pre-release (1.6.0 beta) 2018-08-30 16:34:30 +02:00
Gwendal Roué 132ba89427 Adapt SQLCipher to the new build system 2018-08-30 16:34:30 +02:00
Gwendal Roué 1c26b7748e SQLCipher: Define ARCHS to $ARCHS_STANDARD for all sdks
This prevents Xcode 10 beta from outputting errors when it meets the i386 architecture.
2018-08-30 16:34:30 +02:00
Gwendal Roué 3354b22cd0 Travis: run tests with Xcode 10 2018-08-30 16:34:30 +02:00
Gwendal Roué e5cd3a8994 SE-0206 2018-08-30 16:34:30 +02:00
Gwendal Roué 1c09a3d31f New MIN_SWIFT_VERSION and MAX_SWIFT_VERSION makefile variables
This allows us to test GRDB with Swift 4.2, but also with the Swift 4.2 compiler in 4.0 compatibility mode.
2018-08-30 16:34:30 +02:00
Gwendal Roué 83c257822b FTS5: Swift / OS version checks extravaganza
With a big thank you to @hartbit for providing a ready-made solution
2018-08-30 16:34:30 +02:00
Gwendal Roué e82c92a002 Allow experiments with OTHER_SWIFT_FLAGS 2018-08-30 16:34:30 +02:00
Gwendal Roué d58586a18e Enable FTS5 on iOS 12
Thanks to @jrose-apple for the nice tip that avoids code duplication
2018-08-30 16:34:30 +02:00
Gwendal Roué 066889e0d7 Upgrade swiftlyfalling/SQLiteLib 2018-08-30 16:34:30 +02:00
Gwendal Roué ff595eeaef Compile with both Swift 4.1 and Swift 4.2 2018-08-30 16:34:30 +02:00
Gwendal Roué 80956ee2c7 Makefile: support for Xcode 10.0 2018-08-30 16:34:30 +02:00
Gwendal Roué 95ef76e839 More DatabaseRegion documentation 2018-08-30 13:32:53 +02:00
Gwendal Roué bcdf9d8c58 Internal documentation link 2018-08-30 13:03:13 +02:00
Gwendal Roué c44a1518cc Improve DatabaseRegion documentation 2018-08-30 13:02:17 +02:00
Gwendal Roué 8056a0e3c9 Vocabulary 2018-08-30 10:37:51 +02:00
Gwendal Roué 47275d0bf0 Internal documentation link 2018-08-30 10:35:12 +02:00
Gwendal Roué af8e17c753 Document that observation works well with SQL triggers 2018-08-30 10:33:31 +02:00
Gwendal Roué 6b6f80b818 Internal documentation link 2018-08-30 10:27:26 +02:00
Gwendal Roué eaf25161a5 Fic typo 2018-08-30 10:22:15 +02:00
Gwendal Roué 870d6e6966 More DatabaseRegion documentation 2018-08-30 10:21:25 +02:00
Gwendal Roué cd2697e34b CHANGELOG 2018-08-30 10:16:04 +02:00
Gwendal Roué 2083c3b41c Fix typo 2018-08-30 10:14:19 +02:00
Gwendal Roué d65d547b23 DatabaseRegion documentation 2018-08-30 10:13:01 +02:00
Gwendal Roué 0593832d10 Document interaction between DatabaseRegion and transaction observers (2) 2018-08-30 09:00:21 +02:00
Gwendal Roué 056db7ff6f Document interaction between DatabaseRegion and transaction observers 2018-08-30 08:46:58 +02:00
Gwendal Roué 3c01f0f1c0 TODO 2018-08-27 17:30:44 +02:00
Gwendal Roué 05dc1a5bea Fix typo 2018-08-27 15:53:33 +02:00
Gwendal Roué 2174beb396 Review DatabaseValueConversionErrorTests 2018-08-26 15:14:43 +02:00
Gwendal Roué d9989fc442 FetchableRecord+Decodable: fix a few corner cases 2018-08-26 15:14:20 +02:00
Gwendal Roué 566f42e8d0 Remove useless conversion contexts 2018-08-26 14:07:36 +02:00
Gwendal Roué f159927724 SE-0075 2018-08-26 12:07:19 +02:00
Gwendal Roué 21b8690e07 TODO 2018-08-26 10:42:01 +02:00
Gwendal Roué bb91a7ca0b Fix typo 2018-08-26 10:41:36 +02:00
Gwendal Roué 5819419f3b Minor documentation update 2018-08-25 17:30:40 +02:00
Gwendal Roué 2c59f838aa Fix typo 2018-08-25 17:00:56 +02:00
Gwendal Roué cbbc12adc0 Enhance introduction to records 2018-08-25 17:00:10 +02:00
Gwendal Roué d4d0aed3ae Simplify jazzy documentation 2018-08-25 16:04:50 +02:00
Gwendal Roué 588d7ac4ca Enhance Transactions documentation 2018-08-25 15:43:22 +02:00
Gwendal Roué ab98081e7b Don't initialize PersistenceContainer inside RecordEncoder 2018-08-25 15:32:57 +02:00
Gwendal Roué a8a3ec8259 Enhance Swift Enums documentation 2018-08-25 15:31:59 +02:00
Gwendal Roué 4fcc1f81d5 Update "Differences between Database Queues and Pools" chapter 2018-08-25 14:17:46 +02:00
Gwendal Roué 4572e493e6 Update "Differences between Database Queues and Pools" chapter 2018-08-25 13:43:58 +02:00
Gwendal Roué 1928c84b80 Update "Differences between Database Queues and Pools" chapter 2018-08-25 13:17:01 +02:00
Gwendal Roué b4d99dc738 Update "Differences between Database Queues and Pools" chapter 2018-08-25 13:07:33 +02:00
Gwendal Roué 8abf815045 Enhance readFromCurrentState and snapshots documentation 2018-08-25 12:22:40 +02:00
Gwendal Roué 7610eebb3f Enhance Codable Record documentatoin 2018-08-25 12:19:16 +02:00
Gwendal Roué c43800f40d Enhance Date documentation 2018-08-25 12:16:16 +02:00
Gwendal Roué a511772562 Enhance Values documentation 2018-08-25 12:11:39 +02:00
Gwendal Roué e916f577f1 Enhance Row documentation 2018-08-25 12:10:07 +02:00
Gwendal Roué da14fd2f87 Enhance DatabaseValue documentation 2018-08-25 11:50:07 +02:00
Gwendal Roué 052e615de0 Enhance Row documentation 2018-08-25 11:48:08 +02:00
Gwendal Roué 5a2f713775 Enhance Cursor documentation 2018-08-25 11:46:41 +02:00
Gwendal Roué ae66563654 Documentation + test for mixed arguments 2018-08-23 14:52:59 +02:00
Gwendal Roué 26df5aa516 Documentation 2018-08-23 14:32:30 +02:00
Gwendal Roué d3a9667f10 Cleanup 2018-08-22 13:04:24 +02:00
Gwendal Roué adf5695c20 Move StatementCache to Database+Statements.swift 2018-08-22 12:56:12 +02:00
Gwendal Roué aa8cb60fad SQLCipher has learned SQLITE_PREPARE_PERSISTENT 2018-08-22 12:52:13 +02:00
Gwendal Roué 65d99879a8 SQLCipher has learned SQLITE_PREPARE_PERSISTENT 2018-08-22 12:50:07 +02:00
Gwendal Roué b14f1b9fdc SQLCipher has learned sqlite3_prepare_v3 2018-08-22 08:53:01 +02:00
Gwendal Roué 46511e507e Avoid code duplication in Database.setupTrace
Also, use sqlite3_trace_v2 with SQLCipher
2018-08-22 08:35:54 +02:00
Gwendal Roué 8f5eee0130 Avoid code duplication in Database.closeConnection 2018-08-22 08:01:26 +02:00
Gwendal Roué 7f8d59b7b1 Merge pull request #403 from groue/feature/decoding-strategies
Codable records: customize date and uuid format
2018-08-21 19:40:20 +02:00
Gwendal Roué 0932e92fb4 Documentation 2018-08-21 19:39:34 +02:00
Gwendal Roué 5a8381b282 Add missing attribution 2018-08-21 14:39:46 +02:00
Gwendal Roué 8493984949 Fix Typo 2018-08-21 14:32:43 +02:00
Gwendal Roué a386fb6580 Documentation 2018-08-21 08:17:57 +02:00
Gwendal Roué baee699591 CHANGELOG 2018-08-21 06:58:18 +02:00
Gwendal Roué ad11affd21 ISO8601: don't let user customize the formatter 2018-08-20 23:43:04 +02:00
Gwendal Roué 209b3d0d37 Fix SPM and -O builds 2018-08-20 23:32:38 +02:00
Gwendal Roué edca38470e Documentation 2018-08-20 22:24:26 +02:00
Gwendal Roué e9b76bb196 Tests for DatabaseUUIDEncodingStrategy 2018-08-20 22:16:29 +02:00
Gwendal Roué f70e9b3e39 Introduce DatabaseUUIDEncodingStrategy 2018-08-20 21:14:51 +02:00
Gwendal Roué 13f3e5ec0d Remove useless conversions from Int to Int32 2018-08-20 21:14:32 +02:00
Gwendal Roué fb209d8805 Decode UUID and NSUUID from both blobs and strings 2018-08-20 21:13:58 +02:00
Gwendal Roué c6b1872291 Documentation 2018-08-20 19:40:23 +02:00
Gwendal Roué 8fa405452d Documentation 2018-08-20 19:38:11 +02:00
Gwendal Roué 34c7b0b40c Documentation 2018-08-20 19:32:59 +02:00
Gwendal Roué f583ef0d2a Documentation 2018-08-20 19:30:59 +02:00
Gwendal Roué e438d580b4 Don't close doors 2018-08-20 09:02:15 +02:00
Gwendal Roué 2c9a4b6968 Enhance "Record Customization Options" chapter 2018-08-20 09:00:35 +02:00
Gwendal Roué ba984427a4 Sort "Record Customization Options" by expected popularity 2018-08-20 08:58:17 +02:00
Gwendal Roué 1e34128213 Sort "Record Customization Options" by expected popularity 2018-08-20 08:57:35 +02:00
Gwendal Roué 319ac27b15 Extend "Record Customization Options" chapter 2018-08-20 08:56:02 +02:00
Gwendal Roué 8ea13dc5fd Quiet 2018-08-20 08:52:51 +02:00
Gwendal Roué ad6f1f4a37 Fix inner link 2018-08-20 08:51:48 +02:00
Gwendal Roué 063fe70766 More fostering of Codable records 2018-08-20 08:50:13 +02:00
Gwendal Roué 1c9ce6781b Enhance "JSON Columns" chapter 2018-08-20 08:30:57 +02:00
Gwendal Roué 81e777a323 Enhance "Use CodingKeys as Columns" chapter 2018-08-20 08:14:51 +02:00
Gwendal Roué b7273e0a7e Documentation 2018-08-20 08:05:20 +02:00
Gwendal Roué bb90ea0259 Improve explanation why the sortedKeys JSON option is recommended 2018-08-19 22:40:51 +02:00
Gwendal Roué f925d7e3d4 Fix SPM 2018-08-19 22:21:03 +02:00
Gwendal Roué bbf7eb0b73 Make tests platform-independent 2018-08-19 22:15:19 +02:00
Gwendal Roué 140c590c49 DatabaseDateEncodingStrategy tests 2018-08-19 21:54:50 +02:00
Gwendal Roué ff306c21e2 DatabaseDateEncodingStrategy 2018-08-19 21:54:41 +02:00
Gwendal Roué d1892c649c Documentation 2018-08-19 21:41:47 +02:00
Gwendal Roué f5d0e4db12 Cleanup & documentation 2018-08-19 20:28:47 +02:00
Gwendal Roué fc914470f5 DatabaseDateDecodingStrategy tests 2018-08-19 19:51:09 +02:00
Gwendal Roué d03b76b7e7 DatabaseDateDecodingStrategy 2018-08-19 19:50:35 +02:00
Gwendal Roué d45afb921a Merge pull request #401 from groue/feature/selectAs
Query Interface: set the selection and the fetched type in a single method call
2018-08-19 15:54:42 +02:00
Gwendal Roué e1f80494a8 CHANGELOG.md 2018-08-19 13:52:42 +02:00
Gwendal Roué 982dee5b77 Documentation improvements 2018-08-19 13:31:48 +02:00
Gwendal Roué 9815b310b6 TODO.md 2018-08-19 13:03:00 +02:00
Gwendal Roué 7bb0718bae Documentation for select(..., as:) 2018-08-19 13:02:45 +02:00
Gwendal Roué da60a5004e Tests for select(..., as:) 2018-08-19 12:30:02 +02:00
Gwendal Roué 8af33c4fc9 Introduce select(..., as:)
Record.select(..., as: Value.self) is equivalent to Record.select(...).asRequest(of: Value.self).

It somewhat improves the readability of some requests:

Player.select(max(Column("score")), as: Int.self)
2018-08-19 12:25:27 +02:00
Gwendal Roué 1fba575c18 Merge pull request #399 from groue/feature/codableUserInfo
Codable support: customize the `userInfo` context dictionary, and the format of JSON columns
2018-08-19 07:31:44 +02:00
Gwendal Roué 1e25debefc Done 2018-08-19 07:31:09 +02:00
Gwendal Roué 97d77e871b internal documentation 2018-08-18 20:54:40 +02:00
Gwendal Roué 7cb58cfffc Major cleanup of FetchableRecord+Decodable 2018-08-18 20:27:07 +02:00
Gwendal Roué 950940dedf Major cleanup of MutablePersistableRecord+Encodable 2018-08-18 19:02:16 +02:00
Gwendal Roué c32af15fdd Fix sample code 2018-08-18 16:10:47 +02:00
Gwendal Roué 3d285dfc81 Fix sample code 2018-08-18 16:09:44 +02:00
Gwendal Roué 76d3ac42ff More taste of DAO 2018-08-18 16:07:52 +02:00
Gwendal Roué e9b7a67c73 Fix JSON column tests so that they don't run when .sortedKeys option is not available 2018-08-18 15:54:01 +02:00
Gwendal Roué ba7cd4f61d Cleanup 2018-08-18 15:54:01 +02:00
Gwendal Roué 7a3321a5ed Add missing Foundation import 2018-08-18 15:54:01 +02:00
Gwendal Roué 5cb9d19b1e Cleanup README 2018-08-18 15:54:01 +02:00
Gwendal Roué 9e3da1a1a9 CHANGELOG 2018-08-18 15:54:01 +02:00
Gwendal Roué 35e202eb13 Documentation 2018-08-18 15:54:01 +02:00
Gwendal Roué 812975ee7d Cleanup 2018-08-18 15:54:01 +02:00
Gwendal Roué 934ee8e5f4 Remove a few obsolete debugging print statements 2018-08-18 15:54:01 +02:00
Gwendal Roué 47c424cb69 PersistableRecord: customize JSON encoding per column 2018-08-18 15:54:01 +02:00
Gwendal Roué b35fb6e315 FetchableRecord: customize JSON decoding per column 2018-08-18 15:54:01 +02:00
Gwendal Roué fdc191bbb4 Inline documentation 2018-08-18 15:54:01 +02:00
Gwendal Roué a8ec0530b1 Fix tests for iOS 2018-08-18 15:54:01 +02:00
Gwendal Roué b7b8594176 Pass tests for MutablePersistableRecord userInfo customization 2018-08-18 15:54:01 +02:00
Gwendal Roué eee433fefe Failing tests for MutablePersistableRecord userInfo customization 2018-08-18 15:54:01 +02:00
Gwendal Roué 513a5a3fb7 More FetchableRecord userInfo customization tests 2018-08-18 15:54:01 +02:00
Gwendal Roué 1a3638c0ef FetchableRecord can customize Decoder userInfo 2018-08-18 15:54:01 +02:00
Gwendal Roué ef123824c3 Failing tetsts for Decodable user infos 2018-08-18 15:54:01 +02:00
Gwendal Roué 2bc56255b2 TODO 2018-08-17 09:50:20 +02:00
Gwendal Roué a94711ad77 Fix a compiler warning introduced by 7be63866 2018-08-16 14:34:30 +02:00
Gwendal Roué 0ab84aff52 Enhance Codable Records documentation chapter 2018-08-16 14:24:07 +02:00
Gwendal Roué e415db248a Minor documentation tweak 2018-08-16 13:45:05 +02:00
Gwendal Roué c3a15bc2fc The benefits of having CodingKeys adopt ColumnExpression 2018-08-16 13:23:47 +02:00
Gwendal Roué 7a18b7c948 Test for CodingKey as ColumnExpression 2018-08-16 12:31:26 +02:00
Gwendal Roué df1f9b92a1 TODO.md 2018-08-16 11:00:35 +02:00
Gwendal Roué 4110f890da Minor documentation tweak 2018-08-16 09:02:05 +02:00
Gwendal Roué 44061f0d31 Improve Codable support visibility 2018-08-16 08:59:18 +02:00
Gwendal Roué 7be6386689 Fix DatabaseQueue.write and unsafeReentrantRead throws/rethrows qualifier. 2018-08-16 08:27:05 +02:00
Gwendal Roué 4d7d5e8429 Minor documentation tweak 2018-08-16 08:14:32 +02:00
Gwendal Roué b933917f34 Minor documentation tweak 2018-08-16 08:12:41 +02:00
Gwendal Roué d7f7a57129 Hide implementation details 2018-08-16 06:42:31 +02:00
Gwendal Roué d5008283d4 Minor documentation tweak 2018-08-15 23:18:36 +02:00
Gwendal Roué e51f27403d Minor documentation tweak 2018-08-15 23:05:09 +02:00
Gwendal Roué e5b2710151 Minor documentation tweaks 2018-08-15 22:58:49 +02:00
Gwendal Roué bdca768900 Improve Cursor documentation 2018-08-15 22:31:43 +02:00
Gwendal Roué b9b7ab2902 Rewrite Database queue and pool introducttions 2018-08-15 21:57:46 +02:00
Gwendal Roué 30bc15afb6 Merge pull request #397 from rotacloud/rotacloud
JSON encoding and decoding of codable record properties
2018-08-15 21:07:44 +02:00
Gwendal Roué 7ea15dcce2 Welcome @valexa and @gusrota to the thank you notice 2018-08-15 19:44:47 +02:00
Gwendal Roué 44b998c08f CHANGELOG.md 2018-08-15 19:38:03 +02:00
Gwendal Roué 2b8c8389fe Fix typo 2018-08-15 19:01:11 +02:00
Gwendal Roué dfb9421bd7 Documentation for JSON support 2018-08-15 18:53:10 +02:00
Gwendal Roué 02db2a8dc6 Tests for JSON data strategy 2018-08-15 18:40:24 +02:00
Gwendal Roué 9bb4ff86f1 Tests for JSON date strategy 2018-08-15 18:35:06 +02:00
Gwendal Roué 2eb0955420 JSON encoding: choose strategies
Data: .base64
Date: .millisecondsSince1970
NonConformingFloat: .throw
2018-08-15 18:34:47 +02:00
Gwendal Roué 659db4fdd9 Safer default implementation for RowImpl.copiedRow(_:) 2018-08-15 17:33:05 +02:00
Gwendal Roué d00421abe0 Restore SPM: add missing Foundation import 2018-08-15 17:17:08 +02:00
Gwendal Roué 4d343e893e More tests for Data -> String conversion: play with JPEG :-) 2018-08-15 17:09:15 +02:00
Gwendal Roué eba21d3371 Oh men of little faith! 2018-08-15 16:55:12 +02:00
Gwendal Roué b47f5864ac Even better feedback for conversion errors from StatementColumnConvertible 2018-08-15 16:49:07 +02:00
Gwendal Roué e8dacb31cc Tests for failed value conversions 2018-08-15 16:22:27 +02:00
Gwendal Roué 0b77d0d745 Better feedback for conversion errors from StatementColumnConvertible 2018-08-15 16:10:51 +02:00
Gwendal Roué de4f57c2aa Test decoding of non-UTF8 data 2018-08-15 16:09:45 +02:00
Gwendal Roué 2d6140a805 Refactor value conversion tests 2018-08-15 15:17:54 +02:00
Vlad Alexa b2234b46a2 5f41c57c addition 2018-08-15 14:04:14 +01:00
Gwendal Roué 358225b462 Cleanup, documentation, and preserve coding paths 2018-08-15 13:41:53 +02:00
Gwendal Roué 820673b78b PersistableRecord+Encodable: make it as robust as FetchableRecord+Decodable 2018-08-15 13:23:58 +02:00
Gwendal Roué 1c66ad4aad Restore GRDB/Core/Support/Foundation/Data.swift
because Data belongs to Foundation, not to the Standard Library.

Remove `import Foundation` from StandardLibrary.swift
2018-08-15 12:05:16 +02:00
Vlad Alexa 5f41c57c45 amended the documentation and tests to include Dictionary support to Codable types 2018-08-15 10:21:55 +01:00
Gwendal Roué 0cdc7d81d4 Just some cleanup, nothing new 2018-08-15 11:10:11 +02:00
Gwendal Roué 942b32e5d5 RowSingleValueDecodingContainer performance improvements
We switch from column indexing to integer indexing, which is far more efficient. And we can use the improved value decoding methods from #384.
2018-08-15 10:40:14 +02:00
Gwendal Roué aa8bc0fae3 Don't let JSONDecodingRequiredError go
JSON decoding: when row doesn't contain any Data, we don't want to expose a JSONDecodingRequiredError error to the user. We switch to a detailed conversion error instead (see #384).
2018-08-15 10:24:28 +02:00
Gwendal Roué 275098084d Introduce JSONDecodingRequiredError
We used to check for a standard DecodingError.typeMismatch error with specific message before switching to JSON decoding.

There was a small risk that such an error would not be generated by GRDB. In this case, we'd erroneously switch to JSON decoding instead of throwing the error.

So let's recognize the specific need for JSON decoding with a specific error instead: JSONDecodingRequiredError.
2018-08-15 10:12:28 +02:00
Gwendal Roué 05fda18a56 Introduce RowSingleValueDecoder
This allows complex decodable types to fail decoding from a row column, so that we switch to JSON decoding.
2018-08-15 09:55:45 +02:00
Gwendal Roué 4b7f17dbfa Merge remote-tracking branch 'origin/development' into rotacloud 2018-08-15 05:12:28 +02:00
Angus Muller c52b59f1bc Switching to JSON encoding for nested containers. 2018-08-14 16:01:05 +01:00
Vlad Alexa 76f5adf944 moved the extension to Swift.Data to follow the extension to Swift.String in the StandardLibrary.swift,
added case .blob(let data): return String(data: data, encoding: .utf8) to String.fromDatabaseValue
fixed tests
2018-08-14 15:04:07 +01:00
Vlad Alexa d81475adc4 6262d10 continued 2018-08-14 13:06:26 +01:00
Angus Muller a08974ffa4 Added tests for arrays 2018-08-14 11:20:02 +01:00
Angus Muller 8c06e7bff5 Detached rows string to data and tests 2018-08-14 11:16:47 +01:00
Vlad Alexa 7f16e357d0 extended Codable documentation and added test for the example used in the documentation 2018-08-14 10:39:31 +01:00
Vlad Alexa 6262d10794 added catch 2018-08-14 09:25:44 +01:00
Gwendal Roué d9dd293d7f A really difficult cleanup process 2018-08-14 08:33:06 +02:00
Gwendal Roué e49e2db571 Optimize decoding of StatementColumnConvertible values in Decodable records
This is the real final touch for #384, after all
2018-08-13 21:17:52 +02:00
Gwendal Roué 7da5ff95a0 Makefile: fix rule for Realm 2018-08-13 07:51:13 +02:00
Gwendal Roué 8eee52dad5 Merge pull request #384 from groue/conversionDebugInfo
Improve database value decoding diagnostics
2018-08-13 07:45:32 +02:00
Gwendal Roué 9bc68cd10e The final touch 2018-08-12 15:12:46 +02:00
Gwendal Roué e415a93d7e Performance tests for Codable records 2018-08-12 14:10:38 +02:00
Gwendal Roué 46bba98f0f Fix versions in performance report 2018-08-12 13:43:39 +02:00
Gwendal Roué 6a21e97a12 Profile struct decoding 2018-08-12 13:43:16 +02:00
Gwendal Roué 1ae8e39dab Perform performance tests against SQLite.swift 0.11.5 2018-08-12 12:46:51 +02:00
Gwendal Roué b99b14eb4d Perform performance tests against FMDB 2.7 2018-08-12 12:45:02 +02:00
Gwendal Roué 5579dd651a Perform performance tests against Realm 3.7.6 2018-08-12 12:42:58 +02:00
Gwendal Roué 66541922a4 More cleanup 2018-08-12 12:27:47 +02:00
Gwendal Roué 80fe7f87b1 More cleanup 2018-08-12 11:39:48 +02:00
Gwendal Roué bf5420de26 More cleanup 2018-08-12 10:20:10 +02:00
Gwendal Roué ef10e2e8ed General cleanup:
- rename ValueConversionDebuggingInfo to ValueConversionContext
- allow missing value conversion context (when decoding a raw DatabaseValue)
- rename ColumnCursor to FastDatabaseValueCursor
- rename NullableColumnCursor to FastNullableDatabaseValueCursor
2018-08-11 19:45:58 +02:00
Gwendal Roué 1dcb42c540 wip: debug info for no such column errors 2018-08-11 13:03:11 +02:00
Gwendal Roué 897fd32725 Cleanup 2018-08-11 12:58:04 +02:00
Gwendal Roué e46902c845 wip: debug info for no such column errors 2018-08-11 07:16:55 +02:00
Gwendal Roué d836fffd08 wpi: debug info for no such column errors 2018-08-10 08:52:32 +02:00
Gwendal Roué c480e07f08 Increase single-value containers testing 2018-08-10 05:21:33 +02:00
Gwendal Roué 9f2058f6d9 Fix DatabaseValueConvertible implementation for Decodable types that need a single-value container 2018-08-10 05:01:30 +02:00
Gwendal Roué 7d4ebce70a TODO conversion error message for adapted rows 2018-08-10 04:52:59 +02:00
Gwendal Roué cbda1f9211 Fix DatabaseValueConvertible implementation for Decodable types that need a single-value container
They used to crash on decoding errors
2018-08-10 04:52:23 +02:00
Gwendal Roué cef5d25228 Test conversion error messages 2018-08-09 19:19:22 +02:00
Gwendal Roué 220ce379e1 Test conversion error messages 2018-08-09 14:00:33 +02:00
Vlad Alexa 2826472c19 sorted encoder outputFormatting for ios11+ etcl 2018-08-09 09:46:45 +01:00
Gwendal Roué bcc45dc076 no more throwing conversion methods, and refactor ValueConversionDebuggingInfo 2018-08-09 08:51:50 +02:00
Vlad Alexa 7def60c3c0 fixed checking for nested codable 2018-08-08 14:35:05 +01:00
Vlad Alexa 74aae3dd59 implemented requested changes 2018-08-08 11:41:26 +01:00
Gwendal Roué 89d5bd7945 Restore SQLCipher/src to v3.4.2 2018-08-07 19:44:38 +02:00
Vlad Alexa feeedcb92d Added nested Codable support by flattening into/from JSON 2018-08-07 15:29:16 +01:00
Gwendal Roué 78a6f7251b Spot a few Demeter law violations 2018-08-06 13:40:37 +02:00
Gwendal Roué b307e907cb CHANGELOG 2018-08-06 13:40:37 +02:00
Gwendal Roué 9f2ba7245b fix SPM build 2018-08-06 13:40:05 +02:00
Gwendal Roué e9e1fa85c6 Cleanup 2018-08-06 13:40:05 +02:00
Gwendal Roué f8de01779c Cleanup 2018-08-06 13:40:05 +02:00
Gwendal Roué 84c53ef6b9 improve value conversion diagnostics more 2018-08-06 13:40:05 +02:00
Gwendal Roué a8f6ed6d61 improve value conversion diagnostics more 2018-08-06 13:40:05 +02:00
Gwendal Roué 1c811a61ca improve value conversion diagnostics 2018-08-06 13:40:05 +02:00
Gwendal Roué 566dae0574 Merge pull request #393 from groue/SQLCipher-3.4.2
Upgrade SQLCipher to 3.4.2, enable FTS5 on GRDBCipher and new pod GRDBPlus
2018-08-06 13:32:57 +02:00
Gwendal Roué f0ec9925d2 Add @Marus to the thank you notice 2018-08-06 08:40:37 +02:00
Gwendal Roué 481dc79c85 CHANGELOG: documentation diff 2018-08-06 08:32:16 +02:00
Gwendal Roué 0b1a24184b Upgrade release process for GRDBPlus pod 2018-08-06 08:19:58 +02:00
Gwendal Roué b473d07b3c Fix typo 2018-08-06 08:19:37 +02:00
Gwendal Roué 5538977911 Improve doc about FTS5 support 2018-08-06 08:07:31 +02:00
Gwendal Roué 9815b0b480 CHANGELOG 2018-08-05 14:47:26 +02:00
Gwendal Roué 9ed01719b7 Update SQLCipher version in README.md 2018-08-05 14:41:52 +02:00
Gwendal Roué 0e40b6bda2 Document how to activate FTS5
and address #373
2018-08-05 14:37:02 +02:00
Gwendal Roué dd18323a36 New pod: GRDBPlus
This is a workaround for https://github.com/CocoaPods/CocoaPods/issues/7333
2018-08-05 14:25:58 +02:00
Gwendal Roué 06e5dc5dfd Further split CocoaPods lint tasks
(still hoping that this fixes Travis timeout)
2018-08-04 13:24:03 +02:00
Gwendal Roué b916bca1f6 Split test_CocoaPodsLint Makefile target
... in order to avoid Travis CI timeouts
2018-08-04 07:19:06 +02:00
Gwendal Roué 4186d2e5c4 Fix test_install_GRDBFTS5_CocoaPods 2018-08-03 13:28:10 +02:00
Gwendal Roué 33a5decfdc Fix GRDB.swift podspec 2018-08-03 13:27:15 +02:00
Gwendal Roué 2c35ca5ac7 Rename GRDB/FTS5 podspec to GRDB/3.19.3, and comment out target requirements that CocoaPods does not support; 2018-08-03 08:24:25 +02:00
Gwendal Roué 4d2e230633 Makefile: test FTS5 support on iOS 11.4+ and macOS 10.13+ 2018-08-03 08:24:25 +02:00
Gwendal Roué 66d7f37643 https://github.com/CocoaPods/CocoaPods/issues/7333 😭 2018-08-03 08:24:25 +02:00
Gwendal Roué fd00cd613e New Makefile target test_install_GRDBFTS5_CocoaPods that tests GRDB/FTS5 subspec 2018-08-03 08:24:25 +02:00
Gwendal Roué c5c4508bfe New GRDB.swift/FTS5 subspec 2018-08-03 08:24:25 +02:00
Gwendal Roué d21a9b90b2 Enable FTS5 for SQLite < 3.20.0 (sqlite3_prepare_v3 and sqlite3_bind_pointer) 2018-08-03 08:24:25 +02:00
Gwendal Roué 0eeb72a89b Ignore CocoaPods tests workspaces 2018-08-03 08:24:25 +02:00
Gwendal Roué 1cd211bd89 New Makefile target test_install_GRDBCipher_CocoaPods 2018-08-03 08:24:25 +02:00
Gwendal Roué 1d04376493 New Tests/CocoaPods/GRDBCipherMacOS app that checks GRDBCipher integration + FTS5 2018-08-03 08:24:25 +02:00
Gwendal Roué fa396a2d86 New Makefile target test_install_GRDB_CocoaPods 2018-08-03 08:24:25 +02:00
Gwendal Roué 06150b5e58 Make Tests/CocoaPods/GRDBiOS buildable again 2018-08-03 08:24:25 +02:00
Marcel Ball 4f0b5eb7b9 Enable FTS5 extension for GRDBCipher builds
- Enable
- Add -DSQLITE_ENABLE_FTS5 to the CFLAGS for SQLCipher (SQLCipher/src/sqlcipher.xcconfig) (via submodule update)
- Add -D SQLITE_ENABLE_FTS5 to swift flags for GRDBCipher (SQLCipher/GRDBCipher.xcconfig)
- Add -D SQLITE_ENABLE_FTS5 to the GRDBCipher Testing Projects
- Updated message in EncryptionTests - SQLCipher changed the message “file is encrypted or is not a database” back to just “file is not a database” in 3.4.2 - seems like an odd choice on their part but is behaving as expected.
2018-08-03 08:24:25 +02:00
Gwendal Roué 79fd17faec Upgrade SQLCipher to 3.4.2 + FTS5 2018-08-03 08:24:25 +02:00
Gwendal Roué 59da551b66 Merge branch 'master' into development 2018-08-02 16:46:10 +02:00
Gwendal Roué 89d95f6a7c Merge pull request #390 from kluufger/patch-2
fix small typo in readme
2018-07-19 14:30:42 +02:00
kluufger 1db18b818a player -> country 2018-07-19 11:39:01 +00:00
kluufger 37be51ec37 player -> country x2 2018-07-19 11:22:33 +00:00
kluufger 6fb5bb8ffd player -> country 2018-07-19 10:57:14 +00:00
Gwendal Roué d82b539942 Merge pull request #387 from kluufger/patch-1
Fix some typos in AssociationsBasics guide
2018-07-19 12:56:41 +02:00
kluufger dc8406d732 fix small type in readme 2018-07-19 10:08:59 +00:00
kluufger 328d1fcd30 Fix some typos in AssociationsBasics guide
Not sure about some of them, though.
2018-07-19 08:09:10 +00:00
Gwendal Roué d4590ff91f Fix DatabaseWriter.readFromCurrentState documentation 2018-07-13 09:45:59 +02:00
Gwendal Roué 5bcc95ce87 Update TODO.md 2018-07-11 18:11:42 +02:00
227 changed files with 24767 additions and 4093 deletions

No files matched your search

+5 -10
View File
@@ -1,18 +1,13 @@
<!-- Please describe your pull request here. -->
### One more thing…
### Pull Request Checklist
<!--
When relevant, please check as many checkboxes in this list as possible.
Documentation makes sure that you are not the only one who knows about the changes. Tests make sure your changes will be supported in the future.
Write documentation and tests if you can, because if nobody else has the time to do it, the pull request will simply be rejected.
Ask for help and guidance when needed.
Please verify that your pull request checks those boxes:
-->
- [ ] This pull request is submitted against the `develop` branch.
- [ ] This pull request is submitted against the `development` branch.
- [ ] Inline documentation has been updated.
- [ ] README.md or another dedicated guide has been updated.
- [ ] Changes are tested, for all flavors of GRDB, GRDBCipher, and GRDBCustomSQLite.
- [ ] Updated CHANGELOG.md
- [ ] CHANGELOG.md has been updated.
+1
View File
@@ -103,6 +103,7 @@ SQLiteCustom/GRDBCustomSQLite-USER.xcconfig
# CocoaPods test
Podfile.lock
Pods
Tests/CocoaPods/*/*.xcworkspace
# SPM
.build
+125 -42
View File
@@ -1,5 +1,5 @@
# The OS X Build Environment
# https://docs.travis-ci.com/user/reference/osx/#Xcode-version
# https://docs.travis-ci.com/user/reference/osx/#xcode-version
language: objective-c
xcode_project: GRDB.xcodeproj
@@ -15,29 +15,45 @@ jobs:
###########################################
## Test GRDB
# Test GRDBOSX (Xcode 9.4)
# Test GRDBOSX (Xcode 10)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.4
osx_image: xcode10
env:
- TID=GRDBOSX (Xcode 9.4, macOS)
script: make test_framework_GRDBOSX
- TID=GRDBOSX (Xcode 10, Swift 4.2, macOS)
script: make test_framework_GRDBOSX_maxSwift
# Test GRDBWatchOS (Xcode 9.4)
# Test GRDBOSX (Xcode 10)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.4
osx_image: xcode10
env:
- TID=GRDBWatchOS (Xcode 9.4, watchOS)
- TID=GRDBOSX (Xcode 10, Swift 4.0, macOS)
script: make test_framework_GRDBOSX_minSwift
# Test GRDBWatchOS (Xcode 10)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=GRDBWatchOS (Xcode 10, watchOS)
script: make test_framework_GRDBWatchOS
# Test GRDBiOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=GRDBiOS (Xcode 10, Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
# Test GRDBiOS (Xcode 9.4, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.4
env:
- TID=GRDBiOS (Xcode 9.4, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget
script: make test_framework_GRDBiOS_maxTarget_maxSwift
# Test GRDBiOS (Xcode 9.3, iOS <MINIMUM VERSION>))
- stage: Test GRDB
@@ -47,25 +63,41 @@ jobs:
- TID=GRDBiOS (Xcode 9.3, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
# Test GRDB [SPM] (Xcode 9.4, macOS)
# Test GRDB [SPM] (Xcode 10, macOS)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.4
osx_image: xcode10
env:
- TID=GRDB [SPM] (Xcode 9.4, macOS)
- TID=GRDB [SPM] (Xcode 10, macOS)
script: make test_SPM
###########################################
## Test GRDB (Custom SQLite)
# Test GRDBCustomSQLiteOSX (Xcode 9.4)
# Test GRDBCustomSQLiteOSX (Xcode 10)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.4
osx_image: xcode10
env:
- TID=GRDBCustomSQLiteOSX (Xcode 9.4, macOS)
- TID=GRDBCustomSQLiteOSX (Xcode 10, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
# Test GRDBCustomSQLiteiOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=GRDBCustomSQLiteiOS (Xcode 10, Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
# Test GRDBCustomSQLiteiOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=GRDBCustomSQLiteiOS (Xcode 10, Swift 4.0, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift
# Test GRDBCustomSQLiteiOS (Xcode 9.4, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
@@ -85,14 +117,22 @@ jobs:
###########################################
## Test GRDB (SQLCipher)
# Test GRDBCipherOSX (Xcode 9.4)
# Test GRDBCipherOSX (Xcode 10)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.4
osx_image: xcode10
env:
- TID=GRDBCipherOSX (Xcode 9.4, macOS)
- TID=GRDBCipherOSX (Xcode 10, macOS)
script: make test_framework_GRDBCipherOSX
# Test GRDBCipheriOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=GRDBCipheriOS (Xcode 10, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
# Test GRDBCipheriOS (Xcode 9.4, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
@@ -112,46 +152,89 @@ jobs:
###########################################
## Test Installation Methods
# Manual Install (Xcode 9.4)
# Manual Install (Xcode 10)
- stage: Test Installation
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.4
osx_image: xcode10
env:
- TID=Manual Install (Xcode 9.4)
- TID=Manual Install (Xcode 10)
script: make test_install_manual
# Manual Install (GRDBCipher, Xcode 9.4)
# Manual Install (GRDBCipher, Xcode 10)
- stage: Test Installation
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.4
osx_image: xcode10
env:
- TID=Manual Install (GRDBCipher, Xcode 9.4)
- TID=Manual Install (GRDBCipher, Xcode 10)
script: make test_install_GRDBCipher
# Cocoapods Lint (Xcode 9.4)
# CocoaPods Lint (Xcode 10)
- stage: Test Installation
osx_image: xcode9.4
osx_image: xcode10
install:
- gem install cocoapods # Since Travis is not always on latest version
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
env:
- TID=Cocoapods (Xcode 9.4)
script: make test_CocoaPodsLint
- TID=CocoaPods Lint GRDB.swift (Xcode 10)
script: make test_CocoaPodsLint_GRDB
# SPM Install (Xcode 9.4)
# CocoaPods Lint (Xcode 10)
- stage: Test Installation
osx_image: xcode9.4
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
env:
- TID=SPM (Xcode 9.4)
- TID=CocoaPods Lint GRDBPlus (Xcode 10)
script: make test_CocoaPodsLint_GRDBPlus
# CocoaPods Lint (Xcode 10)
- stage: Test Installation
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
env:
- TID=CocoaPods Lint GRDBCipher (Xcode 10)
script: make test_CocoaPodsLint_GRDBCipher
# CocoaPods Install (Xcode 10)
- stage: Test Installation
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
env:
- TID=CocoaPods GRDB (Xcode 10)
script: make test_install_GRDB_CocoaPods
# CocoaPods Install (Xcode 10)
- stage: Test Installation
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
env:
- TID=CocoaPods GRDB+FTS5 (Xcode 10)
script: make test_install_GRDBFTS5_CocoaPods
# CocoaPods Install (Xcode 10)
- stage: Test Installation
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
env:
- TID=CocoaPods GRDBCipher (Xcode 10)
script: make test_install_GRDBCipher_CocoaPods
# SPM Install (Xcode 10)
- stage: Test Installation
osx_image: xcode10
env:
- TID=SPM (Xcode 10)
script: make test_install_SPM
## Carthage Build
## Commented out until `make test_CarthageBuild` performs *reliably*.
## See https://github.com/groue/GRDB.swift/pull/262
# - stage: Test Installation
# osx_image: xcode9.4
# before_install:
# - brew update
# - brew outdated carthage || brew upgrade carthage
# env:
# - TID=Carthages
# script: make test_CarthageBuild
- stage: Test Installation
osx_image: xcode10
before_install:
- brew update
- brew outdated carthage || brew upgrade carthage
env:
- TID=Carthages
script: make test_CarthageBuild
+518 -4
View File
@@ -1,6 +1,520 @@
Release Notes
=============
All notable changes to this project will be documented in this file.
GRDB adheres to [Semantic Versioning](https://semver.org/).
#### 3.x Releases
- `3.6.x` Releases - [3.6.0](#360) | [3.6.1](#361) | [3.6.2](#362)
- `3.5.x` Releases - [3.5.0](#350)
- `3.4.x` Releases - [3.4.0](#340)
- `3.3.x` Releases - [3.3.0](#330) | [3.3.1](#331)
- `3.3.0` Betas - [3.3.0-beta1](#330-beta1)
- `3.2.x` Releases - [3.2.0](#320)
- `3.1.x` Releases - [3.1.0](#310)
- `3.0.x` Releases - [3.0.0](#300)
#### 2.x Releases
- `2.10.x` Releases - [2.10.0](#2100)
- `2.9.x` Releases - [2.9.0](#290)
- `2.8.x` Releases - [2.8.0](#280)
- `2.7.x` Releases - [2.7.0](#270)
- `2.6.x` Releases - [2.6.0](#260) | [2.6.1](#261)
- `2.5.x` Releases - [2.5.0](#250)
- `2.4.x` Releases - [2.4.0](#240) | [2.4.1](#241) | [2.4.2](#242)
- `2.3.x` Releases - [2.3.0](#230) | [2.3.1](#231)
- `2.2.x` Releases - [2.2.0](#220)
- `2.1.x` Releases - [2.1.0](#210)
- `2.0.x` Releases - [2.0.0](#200) | [2.0.1](#201) | [2.0.2](#202) | [2.0.3](#203)
#### 1.x Releases
- `1.3.x` Releases - [1.3.0](#130)
- `1.2.x` Releases - [1.2.0](#120) | [1.2.1](#121) | [1.2.2](#122)
- `1.1.x` Releases - [1.1.0](#110)
- `1.0.x` Releases - [1.0.0](#100)
#### 0.x Releases
- [0.110.0](#01100), ...
### 3.6.2
Released January 5, 2019 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v3.6.1...v3.6.2)
### Fixed
- [#464](https://github.com/groue/GRDB.swift/pull/464): Make updateChanges(_:with:) available to PersistableRecord structs
## 3.6.1
Released December 9, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v3.6.0...v3.6.1)
### Fixed
- [#458](https://github.com/groue/GRDB.swift/pull/458): Fix ValueObservation duration - code & doc
## 3.6.0
Released December 7, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v3.5.0...v3.6.0)
This release comes with:
- A nice sugar for updating records (my personal favorite of this release):
```swift
// Does not hit the database if player is not modified
try player.update(db) {
$0.score = 1000
$0.hasAward = true
}
```
- Enhanced [ValueObservation](README.md#valueobservation), with methods such as `compactMap`, `combine`, ...
- Observation of specific transactions, with the new [DatabaseRegionObservation](README.md#databaseregionobservation).
- Various other improvements listed below.
### Fixed
- [#449](https://github.com/groue/GRDB.swift/pull/449): Fix JSON encoding of empty containers
### New
- [#442](https://github.com/groue/GRDB.swift/pull/442): Reindex
- [#443](https://github.com/groue/GRDB.swift/pull/443): In place record update
- [#445](https://github.com/groue/GRDB.swift/pull/445): Quality of service and target dispatch queue
- [#446](https://github.com/groue/GRDB.swift/pull/446): ValueObservation: delayed reducer creation
- [#444](https://github.com/groue/GRDB.swift/pull/444): Combine Value Observations
- [#451](https://github.com/groue/GRDB.swift/pull/451): ValueObservation.compactMap
- [#452](https://github.com/groue/GRDB.swift/pull/452): ValueObservation.mapReducer
- [#454](https://github.com/groue/GRDB.swift/pull/454): ValueObservation.distinctUntilChanged
- [#455](https://github.com/groue/GRDB.swift/pull/455): DatabaseRegionObservation
- ValueObservation methods which used to accept a variadic list of observed regions now also accept an array.
- ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired.
### Documentation Diff
- [Record Comparison](README.md#record-comparison): this chapter has been updated for the new `updateChanges(_:with:)` method.
- [ValueObservation](README.md#valueobservation): this chapter has been updated for the new `ValueObservation.combine`, `ValueObservation.compactMap`, and `Value.distinctUntilChanged` methods.
- [DatabaseRegionObservation](README.md#databaseregionobservation): this chapter describes the new `DatabaseRegionObservation` type.
### API diff
```diff
extension Database {
+ func reindex(collation: Database.CollationName) throws
+ func reindex(collation: DatabaseCollation) throws
}
extension MutablePersistableRecord {
+ mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool
}
extension PersistableRecord {
+ func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool
}
struct ValueObservation<Reducer> {
+ static func tracking(
+ _ regions: [DatabaseRegionConvertible],
+ reducer: @escaping (Database) throws -> Reducer)
+ -> ValueObservation
}
+extension ValueObservation where Reducer == Void {
+ static func tracking<Value>(
+ _ regions: [DatabaseRegionConvertible],
+ fetch: @escaping (Database) throws -> Value)
+ -> ValueObservation<ValueReducers.Raw<Value>>
+ static func combine<R1: ValueReducer, ...>(_ o1: ValueObservation<R1>, ...)
+ -> ValueObservation<...>
+}
+extension ValueObservation where Reducer: ValueReducer {
+ func compactMap<T>(_ transform: @escaping (Reducer.Value) -> T?)
+ -> ValueObservation<CompactMapValueReducer<Reducer, T>>
+}
+ extension ValueObservation where Reducer: ValueReducer, Reducer.Value: Equatable {
+ public func distinctUntilChanged()
+ -> ValueObservation<DistinctUntilChangedValueReducer<Reducer>>
+ }
+extension ValueObservation {
+ func mapReducer<R>(_ transform: @escaping (Database, Reducer) throws -> R)
+ -> ValueObservation<R>
+}
struct Configuration {
+ var qos: DispatchQoS
+ var targetQueue: DispatchQueue?
}
+struct DatabaseRegionObservation {
+ var extent: Database.TransactionObservationExtent
+ init(tracking regions: DatabaseRegionConvertible...)
+ init(tracking regions: [DatabaseRegionConvertible])
+ func start(in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) throws -> TransactionObserver
+}
```
## 3.5.0
Released November 2, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v3.4.0...v3.5.0)
This release comes with **[ValueObservation](README.md#valueobservation)**, a new type which tracks the results of database requests, and notifies fresh values whenever the database changes:
```swift
let observer = ValueObversation
.trackingOne(Player.filter(key: 42))
.start(in: dbQueue) { player: Player? in
print("Player has changed")
}
```
ValueObservation also aims at providing support for third-party code that needs to react to database changes. For example, [RxSwiftCommunity/RxGRDB#46](https://github.com/RxSwiftCommunity/RxGRDB/pull/46) is the pull request which implements RxGRDB, the companion library based on [RxSwift](https://github.com/ReactiveX/RxSwift), on top of ValueObservation.
### New
- [#435](https://github.com/groue/GRDB.swift/pull/435): Improved support for values observation
- It is now possible to observe database change from a [DatabaseReader](https://groue.github.io/GRDB.swift/docs/3.5/Protocols/DatabaseReader.html).
### Breaking Change
It used to be possible to define custom types that adopt the [DatabaseReader and DatabaseWriter protocols](README.md#databasewriter-and-databasereader-protocols), with a major drawback: it was impossible to add concurrency-related APIs to GRDB without breaking user code. Now all types that adopt those protocols are defined by GRDB: DatabaseQueue, DatabasePool, DatabaseSnapshot, AnyDatabaseReader, and AnyDatabaseWriter. **Expanding this set is no longer supported.**
### Documentation Diff
- [ValueObservation](README.md#valueobservation): this new chapter describes the new way to observe database values.
### API diff
```diff
protocol DatabaseReader: class {
+ func add<Reducer: ValueReducer>(
+ observation: ValueObservation<Reducer>,
+ onError: ((Error) -> Void)?,
+ onChange: @escaping (Reducer.Value) -> Void)
+ throws -> TransactionObserver
+ func remove(transactionObserver: TransactionObserver)
}
protocol DatabaseWriter: DatabaseReader {
- func remove(transactionObserver: TransactionObserver)
}
+protocol DatabaseRegionConvertible {
+ func databaseRegion(_ db: Database) throws -> DatabaseRegion
+}
+
+extension DatabaseRegion: DatabaseRegionConvertible { }
+
+struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
+ init(_ region: @escaping (Database) throws -> DatabaseRegion)
+ init(_ region: DatabaseRegionConvertible)
+}
-protocol FetchRequest { ... }
+protocol FetchRequest: DatabaseRegionConvertible { ... }
+enum ValueScheduling {
+ case mainQueue
+ case onQueue(DispatchQueue, startImmediately: Bool)
+ case unsafe(startImmediately: Bool)
+}
+protocol ValueReducer {
+ associatedtype Fetched
+ associatedtype Value
+ func fetch(_ db: Database) throws -> Fetched
+ mutating func value(_ fetched: Fetched) -> Value?
+}
+
+extension ValueReducer {
+ func map<T>(_ transform: @escaping (Value) -> T?) -> MapValueReducer<Self, T>
+}
+
+struct AnyValueReducer<Fetched, Value>: ValueReducer {
+ init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?)
+ init<Reducer: ValueReducer>(_ reducer: Reducer) where Reducer.Fetched == Fetched, Reducer.Value == Value
+}
+struct ValueObservation<Reducer> {
+ var extent: Database.TransactionObservationExtent
+ var requiresWriteAccess: Bool
+ var scheduling: ValueScheduling
+ static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) -> ValueObservation
+}
+
+extension ValueObservation where Reducer: ValueReducer {
+ func map<T>(_ transform: @escaping (Reducer.Value) -> T)
+ -> ValueObservation<MapValueReducer<Reducer, T>>
+ func start(
+ in reader: DatabaseReader,
+ onError: ((Error) -> Void)? = nil,
+ onChange: @escaping (Reducer.Value) -> Void) throws -> TransactionObserver
+}
+
+extension ValueObservation where Reducer == Void {
+ static func tracking<Value>(
+ _ regions: DatabaseRegionConvertible...,
+ fetch: @escaping (Database) throws -> Value)
+ -> ValueObservation<ValueReducers.Raw<Value>>
+
+ static func tracking<Value>(
+ _ regions: DatabaseRegionConvertible...,
+ fetchDistinct: @escaping (Database) throws -> Value)
+ -> ValueObservation<ValueReducers.Distinct<Value>>
+ where Value: Equatable
+
+ static func trackingCount<Request: FetchRequest>(_ request: Request)
+ -> ValueObservation<ValueReducers.Raw<Int>>
+ static func trackingAll<Request: FetchRequest>(_ request: Request)
+ -> ValueObservation<ValueReducers.Raw<[Request.RowDecoder]>>
+ static func trackingOne<Request: FetchRequest>(_ request: Request)
+ -> ValueObservation<ValueReducers.Raw<Request.RowDecoder?>>
+}
```
## 3.4.0
Released October 8, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v3.3.1...v3.4.0)
This release comes with **Association Aggregates**. They let you compute values out of collections of associated records, such as their count, or the maximum value of an associated record column.
### Fixed
- [#425](https://github.com/groue/GRDB.swift/pull/425): Fix "destination database is in use " error during database backup
- [#427](https://github.com/groue/GRDB.swift/pull/427): Have cursors reset SQLite statements in deinit
### New
- [#422](https://github.com/groue/GRDB.swift/pull/422): Refining Association Requests
- [#423](https://github.com/groue/GRDB.swift/pull/423): Association Aggregates
- [#428](https://github.com/groue/GRDB.swift/pull/428): Upgrade custom SQLite builds to version 3.25.2 (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib))
### Documentation Diff
- [Refining Association Requests](Documentation/AssociationsBasics.md#refining-association-requests): this new chapter describes how you can craft complex associated requests in a modular way.
- [Association Aggregates](Documentation/AssociationsBasics.md#association-aggregates): this chapter describes the main new feature of this release.
### API diff
```diff
protocol AggregatingRequest {
- func group(_ expressions: [SQLExpressible]) -> Self
+ func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self
}
+extension AggregatingRequest {
+ func group(_ expressions: [SQLExpressible]) -> Self
+}
+extension TableRequest where Self: AggregatingRequest {
+ func groupByPrimaryKey() -> Self {
+}
+struct AssociationAggregate<RowDecoder> {
+ func aliased(_ name: String) -> AssociationAggregate<RowDecoder>
+ func aliased(_ key: CodingKey) -> AssociationAggregate<RowDecoder>
+}
+extension HasManyAssociation where Origin: TableRecord, Destination: TableRecord {
+ var count: AssociationAggregate<Origin>
+ var isEmpty: AssociationAggregate<Origin>
+ func average(_ expression: SQLExpressible) -> AssociationAggregate<Origin>
+ func max(_ expression: SQLExpressible) -> AssociationAggregate<Origin>
+ func min(_ expression: SQLExpressible) -> AssociationAggregate<Origin>
+ func sum(_ expression: SQLExpressible) -> AssociationAggregate<Origin>
+}
+extension QueryInterfaceRequest {
+ func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest<RowDecoder>
+}
+extension QueryInterfaceRequest where RowDecoder: TableRecord {
+ func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> QueryInterfaceRequest<RowDecoder>
+ func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> QueryInterfaceRequest<RowDecoder>
+ func having(_ aggregate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest<RowDecoder>
+}
+extension TableRecord {
+ static func annotated(with aggregates: AssociationAggregate<Self>...) -> QueryInterfaceRequest<Self>
+ static func annotated(with aggregates: [AssociationAggregate<Self>]) -> QueryInterfaceRequest<Self>
+ static func having(_ aggregate: AssociationAggregate<Self>) -> QueryInterfaceRequest<Self>
+}
+extension SQLSpecificExpressible {
+ func aliased(_ key: CodingKey) -> SQLSelectable
+}
```
## 3.3.1
Released September 23, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v3.3.0...v3.3.1)
### Fixed
- [#414](https://github.com/groue/GRDB.swift/pull/414): Fix database pool use of FTS5 tokenizers
### Documentation Diff
- Enhanced visibility of the [Demo Application](DemoApps/GRDBDemoiOS)
## 3.3.0
Released September 16, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v3.3.0-beta1...v3.3.0)
### New
- [#409](https://github.com/groue/GRDB.swift/pull/409): DatabaseWriter.concurrentRead
### Documentation Diff
- [Advanced DatabasePool](README.md#advanced-databasepool): the chapter has been updated for the new DatabasePool.concurrentRead method.
### API diff
```diff
protocol DatabaseWriter : DatabaseReader {
+ func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T>
+ @available(*, deprecated)
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
}
+class Future<Value> {
+ func wait() throws -> Value
+}
extension Cursor {
+ func isEmpty() throws -> Bool
}
```
## 3.3.0-beta1
Released September 5, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v3.2.0...v3.3.0-beta1)
This release focuses on enhancing the relationships between [Codable records](README.md#codable-records) and the database, with JSON columns, customized date formats, and better diagnostics when things go wrong.
Other notable enhancements are:
- Support for Swift 4.2 and Xcode 10 (Xcode 9.3 is still supported).
- Support for the FTS5 full-text engine when available in the operating system (iOS 11.4+ / macOS 10.13+ / watchOS 4.3+).
### Fixed
- The `write` and `unsafeReentrantRead` DatabaseQueue methods used to have an incorrect `throws/rethrows` qualifier.
### New
- [#397](https://github.com/groue/GRDB.swift/pull/397) by [@gusrota](https://github.com/gusrota) and [@valexa](https://github.com/valexa): Codable records: JSON encoding and decoding of codable record properties
- [#399](https://github.com/groue/GRDB.swift/pull/399): Codable records: customize the `userInfo` context dictionary, and the format of JSON columns
- [#403](https://github.com/groue/GRDB.swift/pull/403): Codable records: customize date and uuid format
- [#401](https://github.com/groue/GRDB.swift/pull/401): Query Interface: set the selection and the fetched type in a single method call
- [#393](https://github.com/groue/GRDB.swift/pull/393) by [@Marus](https://github.com/Marus): Upgrade SQLCipher to 3.4.2, enable FTS5 on GRDBCipher and new pod GRDBPlus.
- [#384](https://github.com/groue/GRDB.swift/pull/384): Improve database value decoding diagnostics
- [#396](https://github.com/groue/GRDB.swift/pull/396): Support for Xcode 10 and Swift 4.2
- Cursors of optimized values (Strint, Int, Date, etc.) have been renamed: FastDatabaseValueCursor and FastNullableDatabaseValueCursor replace the deprecated ColumnCursor and NullableColumnCursor.
### Documentation Diff
- [Enabling FTS5 Support](README.md#enabling-fts5-support): Procedure for enabling FTS5 support in GRDB.
- [Codable Records](README.md#codable-records): Updated documentation for JSON columns, customized date and uuid formats, and other customization options.
- [Record Customization Options](README.md#record-customization-options): A new chapter that gathers all your customization options.
- [Fetching from Requests](README.md#fetching-from-requests): Enhanced documentation about requests that don't fetch their origin record (such as aggregates, or associated records).
- [DatabaseRegion](README.md#databaseregion): Database regions help you observe the database.
### API diff
Fixes:
```diff
class DatabaseQueue {
- func write<T>(_ block: (Database) throws -> T) rethrows -> T {
+ func write<T>(_ block: (Database) throws -> T) throws -> T {
- func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
+ func unsafeReentrantRead<T>(_ block: (Database) throws -> T) rethrows -> T {
}
```
Enhancements to Codable support:
```diff
protocol FetchableRecord {
+ static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { get }
+ static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get }
+ static func databaseJSONDecoder(for column: String) -> JSONDecoder
}
protocol MutablePersistableRecord: TableRecord {
+ static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { get }
+ static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get }
+ static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get }
+ static func databaseJSONEncoder(for column: String) -> JSONEncoder
}
```
Query Interface: set the selection and the fetched type in a single method call:
```diff
extension QueryInterfaceRequest {
+ func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
+ func select<RowDecoder>(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
+ func select<RowDecoder>(sql: String, arguments: StatementArguments? = nil, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
}
extension TableRecord {
+ static func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
+ static func select<RowDecoder>(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
+ static func select<RowDecoder>(sql: String, arguments: StatementArguments? = nil, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
}
```
Deprecations:
```diff
+final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor { }
+@available(*, deprecated, renamed: "FastDatabaseValueCursor")
+typealias ColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> = FastDatabaseValueCursor<Value>
+final class FastNullableDatabaseValueCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor { }
+@available(*, deprecated, renamed: "FastNullableDatabaseValueCursor")
+typealias NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> = FastNullableDatabaseValueCursor<Value>
```
## 3.2.0
Released July 8, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v3.1.0...v3.2.0)
@@ -964,7 +1478,7 @@ Released July 19, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare
It used to generate `= NULL` which would not behave as expected.
## 1.2
## 1.2.0
Released July 13, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v1.1...v1.2)
@@ -1063,7 +1577,7 @@ Released July 13, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare
```
## 1.1
## 1.1.0
Released July 1, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v1.0...v1.1)
@@ -1125,9 +1639,9 @@ Released July 1, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare/
```
## 1.0 :tada:
## 1.0.0
Released June 20, 2017
Released June 20, 2017 :tada:
**GRDB 1.0 comes with enhancements, and API stability.**
+50
View File
@@ -0,0 +1,50 @@
# Contributor Code of Conduct
As contributors and maintainers of this project, and in the interest of
fostering an open and welcoming community, we pledge to respect all people who
contribute through reporting issues, posting feature requests, updating
documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free
experience for everyone, regardless of level of experience, gender, gender
identity and expression, sexual orientation, disability, personal appearance,
body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery
- Personal attacks
- Trolling or insulting/derogatory comments
- Public or private harassment
- Publishing other's private information, such as physical or electronic
addresses, without explicit permission
- Other unethical or unprofessional conduct
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
By adopting this Code of Conduct, project maintainers commit themselves to
fairly and consistently applying these principles to every aspect of managing
this project. Project maintainers who do not follow or enforce the Code of
Conduct may be permanently removed from the project team.
This code of conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting a project maintainer at [gr@pierlis.com](mailto:gr@pierlis.com).
All complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. Maintainers are
obligated to maintain confidentiality with regard to the reporter of an
incident.
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.3.0, available at
[http://contributor-covenant.org/version/1/3/0/][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/3/0/
+410
View File
@@ -0,0 +1,410 @@
Contributing to GRDB
====================
**Thank you for coming!**
This guide is a set of tips and guidelines for contributing to the GitHub repository [groue/GRDB.swift](https://github.com/groue/GRDB.swift).
- [Report Bugs]
- [Ask Questions]
- [Suggest an Enhancement]
- [Submit a Pull Request]
- [Sponsoring and Professional Support]
- [Suggested Contributions]
- [Non-Goals]
### Report Bugs
Please make sure the bug is not already reported by searching existing [issues](https://github.com/groue/GRDB.swift/issues).
If you're unable to find an existing issue addressing the problem, [open a new one](https://github.com/groue/GRDB.swift/issues/new). Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.
### Ask Questions
The information you are looking for is maybe already available. Check out:
- the [FAQ](README.md#faq)
- the [general documentation](README.md#documentation)
- the [answered questions](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=label%3Aquestion+)
If not, your questions are welcome in the [GRDB forums](https://forums.swift.org/c/related-projects/grdb), or in a new [GitHub issue](https://github.com/groue/GRDB.swift/issues/new).
### Suggest an Enhancement
Your idea may already be listed in [Suggested Contributions], waiting for someone to pick it up.
If not, contact [@groue](http://twitter.com/groue) on Twitter, or [open a new issue](https://github.com/groue/GRDB.swift/issues/new).
### Submit a Pull Request
Discuss your idea first, so that your changes have a good chance of being merged in.
Submit your pull request against the `development` branch.
Pull requests that include tests for modified and new functionalities, inline documentation, and relevant updates to the main README.md are merged faster, because you won't have to wait for somebody else to complete your contribution.
### Sponsoring and Professional Support
GRDB is free. It is openly developed by its contributors, on their free time, according to their will, needs, and availability. It is not controlled by any company.
When you have specific development or support needs, and are willing to financially contribute to GRDB, please send an email to [Gwendal Roué](mailto:gr@pierlis.com) so that we can enter a regular business relationship through the [Pierlis](http://pierlis.com/) company, based in Paris, France.
## Suggested Contributions
You'll find below various ideas for enhancing and extending GRDB, in various areas. Your ideas can be added to this list: [Suggest an Enhancement].
Legend:
- :baby: **Starter Task**: get familiar with GRDB internals
- :muscle: **Hard**: there are implementation challenges
- :pencil: **Documentation**
- :fire: **Experimental**: let's invent the future!
- :bowtie: **Public API Challenge**: we'll need a very good public API
- :hammer: **Tooling**: GRDB and its environment
- :question: **Unknown Difficulty**
The ideas, in alphabetical order:
- [Associations]
- [CloudKit]
- [Concurrency]
- [Custom FTS5 Auxiliary Functions]
- [Date and Time Functions]
- [Decode NSDecimalNumber from Text Columns]
- [Documentation]
- [FetchedRecordsController Diffing Algorithm]
- [FetchedRecordsController Support for Any Request]
- [FetchedRecordsController Support for Sections]
- [Full Text Search Demo Application]
- [JSON]
- [Linux]
- [More SQL Generation]
- [Reactive Database Observation]
- [Records: Splitting Database Encoding from Ability to Write in the Database]
- [SQL Console in the Debugger]
- [SQLCipher in a Shared App Container]
- [Static Library]
- [Typed Expressions]
### Associations
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
Associations can be enhanced in several ways. See the "Known Issues" and "Future Directions" chapter of the [Associations Guide](Documentation/AssociationsBasics.md)
### CloudKit
:bowtie: Public API Challenge :question: Unknown Difficulty :fire: Experimental
Integration with [CloudKit](https://developer.apple.com/icloud/cloudkit/) is a rich, interesting, and useful topic.
It is likely that CloudKit support would exist in a separate companion library.
Starting points:
- [caiyue1993/IceCream](https://github.com/caiyue1993/IceCream)
- [mentrena/SyncKit](https://github.com/mentrena/SyncKit)
- [nofelmahmood/Seam](https://github.com/nofelmahmood/Seam)
- [Sorix/CloudCore](https://github.com/Sorix/CloudCore)
- [Synchronizing data with CloudKit](https://medium.com/@guilhermerambo/synchronizing-data-with-cloudkit-94c6246a3fda)
- WWDC CloudKit sessions, including [CloudKit Best Practices](https://developer.apple.com/videos/play/wwdc2016/231/)
### Concurrency
:bowtie: Public API Challenge :muscle: Hard :pencil: Documentation
GRDB has a strong focus on safe concurrency. Not only safe as "does not crash", but safe as "actively protects your application data". The topic is discussed in (too) many places:
- [Concurrency Guide](README.md#concurrency)
- [Why Adopt GRDB?](https://github.com/groue/GRDB.swift/blob/master/Documentation/WhyAdoptGRDB.md#strong-and-clear-multi-threading-guarantees)
- [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e)
- [Good Practices for Designing Record Types](https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md#fetch-in-time)
- [Comparison between GRDB and Core Data concurrency](https://github.com/groue/GRDB.swift/issues/405)
Despite this abundant documention, I regularly meet developers who don't think about eventual multi-threading gotchas, and don't design their application against them.
This can be explained:
- Some developers disregard potential multi-threading bugs such as data races, even if the fix is "easy". Such bugs may never happen during the development of an application. They may only impact a few users in production. It is always easier not to think about them.
- Databases are often seen as plain CRUD tools, and some developers are not familiar with topics like isolation or transactions. This is especially true for developers who have experience in a managed ORM such as Core Data or Realm, or web frameworks like Rails or Django: switching to an unmanaged relational database is not an easy task.
- Not all applications need to be multi-threaded.
And this creates improvement opportunities:
- Better documentation of GRDB concurrency
- The introduction of an "ultra-safe" concurrency mode. Maybe something that restricts all database accesses to the main thread, like [FCModel](https://github.com/marcoarment/FCModel). Maybe in a separate companion library.
### Custom FTS5 Auxiliary Functions
:question: Unknown Difficulty
The SQLite documentation provides [this description](https://www.sqlite.org/fts5.html) of FTS5 auxiliary functions:
> An application may use FTS5 auxiliary functions to retrieve extra information regarding the matched row. For example, an auxiliary function may be used to retrieve a copy of a column value for a matched row with all instances of the matched term surrounded by html <b></b> tags.
Applications can define their own [custom FTS5 auxiliary functions](https://www.sqlite.org/fts5.html#custom_auxiliary_functions) with SQLite, but GRDB does not yet provide any Swift API for that.
See issue [#421](https://github.com/groue/GRDB.swift/issues/421) for more information.
### Date and Time Functions
:baby: Starter Task
Believe it or not, no one has ever asked support for SQLite [Date And Time Functions](https://www.sqlite.org/lang_datefunc.html). There is surely room for a nice Swift API that makes them available.
For more ideas, see:
- [SQLite Core Functions](https://www.sqlite.org/lang_corefunc.html)
- [SQLite Aggregate Functions](https://www.sqlite.org/lang_aggfunc.html)
- [SQLite JSON functions](https://www.sqlite.org/json1.html) and [JSON], below.
Functions are defined in [GRDB/QueryInterface/Support/SQLFunctions.swift](https://github.com/groue/GRDB.swift/blob/master/GRDB/QueryInterface/Support/SQLFunctions.swift).
### Decode NSDecimalNumber from Text Columns
:baby: Starter Task
NSDecimalNumber currently only decodes integer and float decimal values. It would be nice if NSDecimalNumber would decode text values as well:
```swift
let number = try NSDecimalNumber.fetchOne(db, "SELECT '12.3'")!
print(number) // prints 12.3
```
NSNumber and NSDecimalNumber support is found in [GRDB/Core/Support/Foundation/NSNumber.swift](https://github.com/groue/GRDB.swift/blob/master/GRDB/Core/Support/Foundation/NSNumber.swift)
### Documentation
:baby: Starter Task :pencil: Documentation
General documentation can always be improved so that it reaches its goal: helping developers building applications.
- English: the documentation has mostly been written by [@groue](http://github.com/groue) who is not a native English speaker.
- Clarity: any chapter that is not crystal clear should be enhanced.
- Audience: documentation should talk to several populations of developers, from beginners who need positive guidance, to SQLite experts who need to build trust.
- Typos
- Inaccuracies
- etc.
Inline documentation, the one which is embedded right into the source code and is displayed by Xcode when one alt-clicks an identifier, deserves the same care.
If you are a good writer, your help will be very warmly welcomed.
### FetchedRecordsController Diffing Algorithm
:muscle: Hard
[FetchedRecordsController] uses a Levenshtein-based diffing algorithm which has a terrible algorithmic complexity. This makes this very useful class unable to deal with more than hundreds of elements.
There exists much more efficient O(n) diffing algorithms that would lift this limitation.
Starting points:
- [RxSwiftCommunity/RxDataSources](https://github.com/RxSwiftCommunity/RxDataSources)
- [ra1028/DifferenceKit](https://github.com/ra1028/DifferenceKit)
- [tonyarnold/Differ](https://github.com/tonyarnold/Differ)
- [onmyway133/DeepDiff](https://github.com/onmyway133/DeepDiff)
- [mcudich/HeckelDiff](https://github.com/mcudich/HeckelDiff)
### FetchedRecordsController Support for Any Request
:muscle: Hard
[FetchedRecordsController] is able to deal with records, but not with raw rows or values:
```swift
// Supported by FetchedRecordsController
let recordRequest = Player.all()
// Not supported by FetchedRecordsController
let stringRequest = Player.select(Column("name"), as: String.self)
let rowRequest = SQLRequest<Row>("SELECT ...")
```
This limitation does not apply to [ValueObservation] and [RxGRDB]. It would be nice if FetchedRecordsController would become just as versatile.
### FetchedRecordsController Support for Sections
:muscle: Hard
[FetchedRecordsController] mimics the API of Core Data's [NSFetchedResultsController](https://developer.apple.com/documentation/coredata/nsfetchedresultscontroller), but does not yet support table and collection view sections.
This improvement most certainly depends on a refreshing of the [FetchedRecordsController Diffing Algorithm].
### Full Text Search Demo Application
:baby: Starter Task :pencil: Documentation
There exists a GRDB demo app for the FTS5 full-text engine: [WWDCCompanion](https://github.com/groue/WWDCCompanion).
This application downloads the transcripts of WWDC sessions, and lets its user type keywords and find matching sessions, sorted by relevance.
The problem is that this demo app breaks every year :sweat_smile:
We'd need instead to index a stable corpus, in order to ease the maintenance of this demo app.
### JSON
:bowtie: Public API Challenge :baby: Starter Task
[Codable Records] are granted with automatic JSON encoding and decoding of their complex properties. But there is still room for improvements. For example, could we put the [SQLite JSON1 extension](https://www.sqlite.org/json1.html) to some good use?
### Linux
:muscle: Hard :hammer: Tooling
Swift on Linux is currently focused on the server (Vapor, Perfect, Kitura). While general server support is a [non-goal](#non-goals) of GRDB, there exists read-only servers, and Linux GUI applications, too. Linux is thus a desired platform.
### More SQL Generation
:bowtie: Public API Challenge :question: Unknown Difficulty
There are several SQLite features that GRDB could natively support:
- [ALTER TABLE ... RENAME COLUMN ... TO ...](https://www.sqlite.org/lang_altertable.html)
- [ATTACH DATABASE](https://www.sqlite.org/lang_attach.html)
- [UPSERT](https://www.sqlite.org/lang_UPSERT.html)
- [INSERT INTO ... SELECT ...](https://www.sqlite.org/lang_insert.html)
- [WITH RECURSIVE ...](https://www.sqlite.org/lang_with.html)
- [RTree](https://sqlite.org/rtree.html)
- [Windows Functions](https://www.sqlite.org/windowfunctions.html)
- [More ideas](https://www.sqlite.org/lang.html)
### Reactive Database Observation
:baby: Starter Task
We already have the [RxGRDB] companion library, which offers [RxSwift](https://github.com/ReactiveX/RxSwift) bindings.
We need more choices of reactive engines.
### Records: Splitting Database Encoding from Ability to Write in the Database
:baby: Starter Task :pencil: Documentation
Record types that know how to encode themselves in the database (converting themselves into columns and database values) currently are granted with [persistence methods] which can write in the database. Those record types all adopt the [PersistableRecord] protocol.
But encoding a record grants other features, such as [Record Comparison], or [Requesting Associated Records].
This is a problem: one should not have to grant a type with persistence methods, when one just needs read-only features.
The fix is to split database encoding from persistence methods. See [#426](https://github.com/groue/GRDB.swift/issues/426) for more information.
### SQL Console in the Debugger
:question: Unknown Difficulty :hammer: Tooling
Sometimes one needs, in lldb, a console similar to the [Command Line Shell For SQLite](https://www.sqlite.org/cli.html).
### SQLCipher in a Shared App Container
:question: Unknown Difficulty
See issue [#302](https://github.com/groue/GRDB.swift/issues/302).
### Static Library
:question: Unknown Difficulty :hammer: Tooling
It would be nice to be able to integrate GRDB as a static library.
### Typed Expressions
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
The compiler currently does not spot type mistakes in query interface requests:
```swift
Player.filter(Column("name") == "Arthur") // OK
Player.filter(Column("name") == 1) // Sure
Player.filter(Column("name") == Date()) // Legit
```
This weak typing also prevents natural-looking Swift code from producing the expected results:
```swift
// Performs arithmetic additions instead of string concatenation
Player.select(Column("firstName") + " " + Column("lastName"))
```
It would be interesting to see what typed expressions could bring to GRDB.
## Non-Goals
GRDB is a "toolkit for SQLite databases, with a focus on application development".
This definition is the reason why GRDB can provide key features such as sharp multi-threading, database observation, and first-class support for raw SQL.
Features that blur this focus are non-goals:
- Support for MySQL, PostgreSQL, or other database engines
- Support for Servers
[Ask Questions]: #ask-questions
[Associations]: #associations
[CloudKit]: #cloudkit
[Codable Records]: README.md#codable-records
[Custom FTS5 Auxiliary Functions]: #custom-fts5-auxiliary-functions
[Database Observation]: #database-observation
[Date and Time Functions]: #date-and-time-functions
[Decode NSDecimalNumber from Text Columns]: #decode-nsdecimalnumber-from-text-columns
[Documentation]: #documentation
[FetchedRecordsController]: README.md#fetchedrecordscontroller
[FetchedRecordsController Diffing Algorithm]: #fetchedrecordscontroller-diffing-algorithm
[FetchedRecordsController Support for Any Request]: #fetchedrecordscontroller-support-for-any-request
[FetchedRecordsController Support for Sections]: #fetchedrecordscontroller-support-for-sections
[Full Text Search Demo Application]: #full-text-search-demo-application
[How is the Library Organized?]: Documentation/LibraryOrganization.md
[How is the Repository Organized?]: Documentation/RepositoryOrganization.md
[JSON]: #json
[Linux]: #linux
[More SQL Generation]: #more-sql-generation
[Records: Splitting Database Encoding from Ability to Write in the Database]: #records-splitting-database-encoding-from-ability-to-write-in-the-database
[Non-Goals]: #non-goals
[Report Bugs]: #report-bugs
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[Concurrency]: #concurrency
[Static Library]: #static-library
[Sponsoring and Professional Support]: #sponsoring-and-professional-support
[SQL Console in the Debugger]: #sql-console-in-the-debugger
[SQLCipher in a Shared App Container]: #sqlcipher-in-a-shared-app-container
[Submit a Pull Request]: #submit-a-pull-request
[Suggest an Enhancement]: #suggest-an-enhancement
[Suggested Contributions]: #suggested-contributions
[Typed Expressions]: #typed-expressions
[persistence methods]: README.md#persistence-methods
[PersistableRecord]: README.md#persistablerecord-protocol
[Record Comparison]: README.md#record-comparison
[Requesting Associated Records]: Documentation/AssociationsBasics.md#requesting-associated-records
[ValueObservation]: README.md#valueobservation
@@ -705,7 +705,7 @@
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 4.0;
SWIFT_VERSION = 4.2;
};
name = Debug;
};
@@ -755,7 +755,7 @@
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 4.0;
SWIFT_VERSION = 4.2;
VALIDATE_PRODUCT = YES;
};
name = Release;
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
</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>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -8,11 +8,10 @@ struct AppDatabase {
/// Creates a fully initialized database at path
static func openDatabase(atPath path: String) throws -> DatabaseQueue {
// Connect to the database
// See https://github.com/groue/GRDB.swift/#database-connections
dbQueue = try DatabaseQueue(path: path)
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let dbQueue = try DatabaseQueue(path: path)
// Use DatabaseMigrator to define the database schema
// See https://github.com/groue/GRDB.swift/#migrations
// Define the database schema
try migrator.migrate(dbQueue)
return dbQueue
@@ -20,8 +19,7 @@ struct AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// This migrator is exposed so that migrations can be tested.
// See https://github.com/groue/GRDB.swift/#migrations
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#migrations
static var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
@@ -29,11 +27,10 @@ struct AppDatabase {
// Create a table
// See https://github.com/groue/GRDB.swift#create-tables
try db.create(table: "player") { t in
// An integer primary key auto-generates unique IDs
t.column("id", .integer).primaryKey()
t.autoIncrementedPrimaryKey("id")
// Sort player names in a localized case insensitive fashion by default
// See https://github.com/groue/GRDB.swift/#unicode
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
t.column("score", .integer).notNull()
@@ -8,7 +8,7 @@ var dbQueue: DatabaseQueue!
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
try! setupDatabase(application)
return true
}
@@ -20,7 +20,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
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
// See https://github.com/groue/GRDB.swift/blob/master/README.md#memory-management
dbQueue.setupMemoryManagement(in: application)
}
}
@@ -1,12 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14113" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14313.18" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
<capability name="Constraints to layout margins" minToolsVersion="6.0"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14283.14"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
@@ -14,7 +12,7 @@
<scene sceneID="Juk-Ad-tZ2">
<objects>
<tableViewController id="iNr-Oe-muq" customClass="PlayerEditionViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="static" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="vlV-lc-eQA">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="plain" separatorStyle="none" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="vlV-lc-eQA">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
@@ -25,11 +23,11 @@
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="2gb-gB-918" id="iyM-TJ-JB4">
<rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Name" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
<rect key="frame" x="26" y="12" width="333" height="20"/>
<rect key="frame" x="16" y="12" width="343" height="20"/>
<fontDescription key="fontDescription" type="system" pointSize="16"/>
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no" returnKeyType="next"/>
<connections>
@@ -38,7 +36,7 @@
</textField>
</subviews>
<constraints>
<constraint firstItem="m5m-Zs-j0z" firstAttribute="leading" secondItem="iyM-TJ-JB4" secondAttribute="leadingMargin" constant="10" id="9cK-nj-70V"/>
<constraint firstItem="m5m-Zs-j0z" firstAttribute="leading" secondItem="iyM-TJ-JB4" secondAttribute="leadingMargin" id="9cK-nj-70V"/>
<constraint firstAttribute="trailingMargin" secondItem="m5m-Zs-j0z" secondAttribute="trailing" id="JsE-8v-XAS"/>
<constraint firstItem="m5m-Zs-j0z" firstAttribute="centerY" secondItem="iyM-TJ-JB4" secondAttribute="centerY" id="psG-tW-QrM"/>
</constraints>
@@ -48,11 +46,11 @@
<rect key="frame" x="0.0" y="44" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="vp3-Ft-Gth" id="ccO-0O-u72">
<rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Score" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
<rect key="frame" x="26" y="12" width="333" height="20"/>
<rect key="frame" x="16" y="12" width="343" height="20"/>
<fontDescription key="fontDescription" type="system" pointSize="16"/>
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no" keyboardType="numberPad" returnKeyType="done"/>
</textField>
@@ -60,7 +58,7 @@
<constraints>
<constraint firstAttribute="trailingMargin" secondItem="rZ9-Fa-cyr" secondAttribute="trailing" id="Gso-FU-Ct1"/>
<constraint firstItem="rZ9-Fa-cyr" firstAttribute="centerY" secondItem="ccO-0O-u72" secondAttribute="centerY" id="UqA-ea-emb"/>
<constraint firstItem="rZ9-Fa-cyr" firstAttribute="leading" secondItem="ccO-0O-u72" secondAttribute="leadingMargin" constant="10" id="WrY-St-72v"/>
<constraint firstItem="rZ9-Fa-cyr" firstAttribute="leading" secondItem="ccO-0O-u72" secondAttribute="leadingMargin" id="WrY-St-72v"/>
</constraints>
</tableViewCellContentView>
</tableViewCell>
+43 -6
View File
@@ -1,28 +1,65 @@
import GRDB
struct Player: Codable, FetchableRecord, MutablePersistableRecord {
// A plain Player struct
struct Player {
// Prefer Int64 for auto-incremented database ids
var id: Int64?
var name: String
var score: Int
}
enum Columns: String, ColumnExpression {
// MARK: - Persistence
// Turn Player into a Codable Record.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Add ColumnExpression to Codable's CodingKeys so that we can use them
// as database columns.
//
// See https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
// for more information about CodingKeys.
private enum CodingKeys: String, CodingKey, ColumnExpression {
case id, name, score
}
/// Update player id after successful insertion
// Update a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
// MARK: - Database access
// Define some useful player requests.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
extension Player {
private static let names = ["Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David", "Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette", "Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl", "Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole", "Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul", "Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain", "Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann", "Zazie", "Zoé"]
static func orderedByName() -> QueryInterfaceRequest<Player> {
return Player.order(CodingKeys.name)
}
static func orderedByScore() -> QueryInterfaceRequest<Player> {
return Player.order(CodingKeys.score.desc, CodingKeys.name)
}
}
// MARK: - Player Randomization
extension Player {
private static let names = [
"Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David",
"Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette",
"Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl",
"Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole",
"Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul",
"Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain",
"Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann",
"Zazie", "Zoé"]
static func randomName() -> String {
return names[Int(arc4random_uniform(UInt32(names.count)))]
return names.randomElement()!
}
static func randomScore() -> Int {
return 10 * Int(arc4random_uniform(101))
return 10 * Int.random(in: 0...100)
}
}
@@ -1,13 +1,16 @@
import UIKit
protocol PlayerEditionViewControllerDelegate: class {
func playerEditionControllerDidComplete(_ controller: PlayerEditionViewController)
}
class PlayerEditionViewController: UITableViewController {
weak var delegate: PlayerEditionViewControllerDelegate?
enum Presentation {
/// Modal presentation: edition ends with the "Commit" segue.
case modal
/// Push presentation: edition ends when user hits the back button.
case push
}
var player: Player! { didSet { configureView() } }
var commitButtonHidden: Bool = false { didSet { configureView() } }
var presentation: Presentation! { didSet { configureView() } }
@IBOutlet fileprivate weak var cancelBarButtonItem: UIBarButtonItem!
@IBOutlet fileprivate weak var commitBarButtonItem: UIBarButtonItem!
@@ -31,13 +34,14 @@ class PlayerEditionViewController: UITableViewController {
} else {
scoreTextField.text = "\(player.score)"
}
if commitButtonHidden {
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
} else {
switch presentation! {
case .modal:
navigationItem.leftBarButtonItem = cancelBarButtonItem
navigationItem.rightBarButtonItem = commitBarButtonItem
case .push:
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
}
}
}
@@ -55,17 +59,21 @@ extension PlayerEditionViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Commit" {
applyChanges()
saveChanges()
}
}
override func willMove(toParentViewController parent: UIViewController?) {
super.willMove(toParentViewController: parent)
override func willMove(toParent parent: UIViewController?) {
super.willMove(toParent: parent)
if parent == nil {
// Self is popping from its navigation controller
applyChanges()
delegate?.playerEditionControllerDidComplete(self)
switch presentation! {
case .modal:
break
case .push:
if parent == nil {
// Self is popping from its navigation controller
saveChanges()
}
}
}
@@ -98,12 +106,16 @@ extension PlayerEditionViewController: UITextFieldDelegate {
return false
}
private func applyChanges() {
private func saveChanges() {
guard var player = self.player else {
return
}
player.name = nameTextField.text ?? ""
player.score = scoreTextField.text.flatMap { Int($0) } ?? 0
self.player = player
try! dbQueue.inDatabase { db in
try player.save(db)
}
}
}
@@ -1,94 +1,92 @@
import UIKit
import GRDB
/// PlayersViewController displays the list of players.
class PlayersViewController: UITableViewController {
enum PlayerOrdering {
private enum PlayerOrdering {
case byName
case byScore
var request: QueryInterfaceRequest<Player> {
switch self {
case .byName:
return Player.order(Player.Columns.name)
case .byScore:
return Player.order(Player.Columns.score.desc, Player.Columns.name)
}
}
}
var playersController: FetchedRecordsController<Player>!
var playerOrdering: PlayerOrdering = .byScore {
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
private var playersController: FetchedRecordsController<Player>!
private var playerCountObserver: TransactionObserver?
private var playerOrdering: PlayerOrdering = .byScore {
didSet {
try! playersController.setRequest(playerOrdering.request)
configureNavigationItem()
try! playersController.setRequest(playersRequest)
configureOrderingBarButtonItem()
}
}
private var playersRequest: QueryInterfaceRequest<Player> {
switch playerOrdering {
case .byName:
return Player.orderedByName()
case .byScore:
return Player.orderedByScore()
}
}
@IBOutlet weak var newPlayerButtonItem: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
configureToolbar()
configureNavigationItem()
configureTableView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isToolbarHidden = false
}
}
// MARK: - Navigation
extension PlayersViewController : PlayerEditionViewControllerDelegate {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Edit" {
let player = playersController.record(at: tableView.indexPathForSelectedRow!)
let controller = segue.destination as! PlayerEditionViewController
controller.title = player.name
controller.player = player
controller.delegate = self // See playerEditionControllerDidComplete
controller.commitButtonHidden = true
}
else if segue.identifier == "New" {
setEditing(false, animated: true)
let navigationController = segue.destination as! UINavigationController
let controller = navigationController.viewControllers.first as! PlayerEditionViewController
controller.title = "New Player"
controller.player = Player(id: nil, name: "", score: 0)
private func configureToolbar() {
toolbarItems = [
UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)),
]
}
private func configureNavigationItem() {
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
configureOrderingBarButtonItem()
configureTitle()
}
private func configureOrderingBarButtonItem() {
switch playerOrdering {
case .byScore:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Score ⬇︎",
style: .plain,
target: self, action: #selector(sortByName))
case .byName:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Name ⬆︎",
style: .plain,
target: self, action: #selector(sortByScore))
}
}
@IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) {
// Player creation: cancel button was tapped
}
@IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) {
// Player creation: commit button was tapped
let controller = segue.source as! PlayerEditionViewController
try! dbQueue.write { db in
try controller.player.save(db)
private func configureTitle() {
// Track changes in the number of players
playerCountObserver = try! ValueObservation
.trackingCount(playersRequest)
.start(in: dbQueue) { [unowned self] count in
switch count {
case 0: self.navigationItem.title = "No Player"
case 1: self.navigationItem.title = "1 Player"
default: self.navigationItem.title = "\(count) Players"
}
}
}
func playerEditionControllerDidComplete(_ controller: PlayerEditionViewController) {
// Player edition: user has finished editing the player
try! dbQueue.write { db in
try controller.player.save(db)
}
}
}
// MARK: - UITableViewDataSource
extension PlayersViewController {
private func configureTableView() {
playersController = try! FetchedRecordsController(dbQueue, request: playerOrdering.request)
// Track changes in the database players
playersController = try! FetchedRecordsController(dbQueue, request: playersRequest)
// Animate changes in the table view
playersController.trackChanges(
willChange: { [unowned self] _ in
self.tableView.beginUpdates()
@@ -123,9 +121,47 @@ extension PlayersViewController {
self.tableView.endUpdates()
})
// Initial fetch
try! playersController.performFetch()
}
}
// MARK: - Navigation
extension PlayersViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Edit" {
let player = playersController.record(at: tableView.indexPathForSelectedRow!)
let controller = segue.destination as! PlayerEditionViewController
controller.title = player.name
controller.player = player
controller.presentation = .push
}
else if segue.identifier == "New" {
setEditing(false, animated: true)
let navigationController = segue.destination as! UINavigationController
let controller = navigationController.viewControllers.first as! PlayerEditionViewController
controller.title = "New Player"
controller.player = Player(id: nil, name: "", score: 0)
controller.presentation = .modal
}
}
@IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) {
// Player creation cancelled
}
@IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) {
// Player creation committed
}
}
// MARK: - UITableViewDataSource
extension PlayersViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return playersController.sections.count
}
@@ -140,7 +176,7 @@ extension PlayersViewController {
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
// Delete the player
let player = playersController.record(at: indexPath)
try! dbQueue.write { db in
@@ -151,7 +187,7 @@ extension PlayersViewController {
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
let player = playersController.record(at: indexPath)
if player.name.isEmpty {
cell.textLabel?.text = "(anonymous)"
cell.textLabel?.text = "-"
} else {
cell.textLabel?.text = player.name
}
@@ -163,33 +199,6 @@ extension PlayersViewController {
// MARK: - Actions
extension PlayersViewController {
private func configureNavigationItem() {
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
switch playerOrdering {
case .byScore:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Score ⬇︎",
style: .plain,
target: self, action: #selector(sortByName))
case .byName:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Name ⬆︎",
style: .plain,
target: self, action: #selector(sortByScore))
}
}
private func configureToolbar() {
toolbarItems = [
UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)),
]
}
@IBAction func sortByName() {
setEditing(false, animated: true)
playerOrdering = .byName
@@ -231,16 +240,16 @@ extension PlayersViewController {
}
} else {
// Insert a player
if arc4random_uniform(2) == 0 {
if Bool.random() {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
// Delete a random player
if arc4random_uniform(2) == 0 {
if Bool.random() {
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
}
// Update some players
for var player in try Player.fetchAll(db) where arc4random_uniform(2) == 0 {
for var player in try Player.fetchAll(db) where Bool.random() {
player.score = Player.randomScore()
try player.update(db)
}
+32
View File
@@ -0,0 +1,32 @@
Demo Application
================
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/Images/GRDBDemoScreenshot.png" width="50%">
**This demo application shows you:**
- how to setup a database in an iOS app
- how to define a simple [Codable Record](../../README.md#codable-records)
- how to track database changes and animate a table view with [FetchedRecordsController](../../README.md#fetchedrecordscontroller).
**Files of interest:**
- [AppDelegate.swift](GRDBDemoiOS/AppDelegate.swift)
`AppDelegate` creates, on application startup, a unique instance of [DatabaseQueue](../../README.md#database-queues) available for the whole application.
- [AppDatabase.swift](GRDBDemoiOS/AppDatabase.swift)
`AppDatabase` defines the database for the whole application. It uses [DatabaseMigrator](../../README.md#migrations) in order to setup the database schema.
- [Player.swift](GRDBDemoiOS/Player.swift)
`Player` is a [Record](../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../README.md#codable-records).
- [PlayersViewController.swift](GRDBDemoiOS/PlayersViewController.swift)
`PlayersViewController` displays a list of players. It keeps its title up-to-date with [ValueObservation](../../README.md#valueobservation), and animates its table view according to database changes with [FetchedRecordsController](../../README.md#fetchedrecordscontroller).
- [PlayerEditionViewController.swift](GRDBDemoiOS/PlayerEditionViewController.swift)
`PlayerEditionViewController` can create or edit a player, and save it in the database.
+568 -35
View File
@@ -22,10 +22,16 @@ GRDB Associations
- [Sorting Associations]
- [Columns Selected by an Association]
- [Table Aliases]
- [Refining Association Requests]
- [Fetching Values from Associations]
- [The Structure of a Joined Request]
- [Decoding a Joined Request with a Decodable Record]
- [Decoding a Joined Request with FetchableRecord]
- [Association Aggregates]
- [Available Association Aggregates]
- [Annotating a Request with Aggregates]
- [Filtering a Request with Aggregates]
- [Isolation of Multiple Aggregates]
- [DerivableRequest Protocol]
- [Known Issues]
- [Future Directions]
@@ -69,7 +75,7 @@ struct BookInfo {
let books = try Book.fetchAll(db)
let bookInfos = books.map { book -> BookInfo in
let author = try Author.fetchOne(key: book.authorId)
let author = try Author.fetchOne(db, key: book.authorId)
return BookInfo(book: book, author: author)
}
```
@@ -557,8 +563,8 @@ Your help is needed. You have to instruct GRDB which foreign key to use:
```swift
struct Book: TableRecord {
// Define foreign keys
static let authorForeignKey = ForeignKey(["authorId"]))
static let translatorForeignKey = ForeignKey(["translatorId"]))
static let authorForeignKey = ForeignKey(["authorId"])
static let translatorForeignKey = ForeignKey(["translatorId"])
// Use foreign keys to define associations:
static let author = belongsTo(Person.self, using: authorForeignKey)
@@ -583,8 +589,8 @@ struct Book: TableRecord {
case id, title, authorId, translatorId
}
static let authorForeignKey = ForeignKey([Columns.authorId]))
static let translatorForeignKey = ForeignKey([Columns.translatorId]))
static let authorForeignKey = ForeignKey([Columns.authorId])
static let translatorForeignKey = ForeignKey([Columns.translatorId])
}
```
@@ -592,7 +598,7 @@ When the destination table of a foreign key does not define any primary key, you
```swift
struct Book: TableRecord {
static let authorForeignKey = ForeignKey(["authorId"], to: ["id"]))
static let authorForeignKey = ForeignKey(["authorId"], to: ["id"])
static let author = belongsTo(Person.self, using: authorForeignKey)
}
```
@@ -614,6 +620,7 @@ Fetch requests do not visit the database until you fetch values from them. This
- [Sorting Associations]
- [Columns Selected by an Association]
- [Table Aliases]
- [Refining Association Requests]
## Requesting Associated Records
@@ -647,7 +654,7 @@ struct Author: PersistableRecord {
static let books = hasMany(Book.self)
/// The request for an author's books
var books: QueryInterfaceRequest<Author> {
var books: QueryInterfaceRequest<Book> {
return request(for: Author.books)
}
}
@@ -1016,6 +1023,113 @@ let request = Book.aliased(bookAlias)
> ```
## Refining Association Requests
You can join and include an association several times in a single request. This can help you craft complex requests in a modular way.
Let's say, for example, that your application needs all books, along with their Spanish authors, sorted by author name and then by title. That's already pretty complex.
This request can be built in a single shot:
```swift
let authorAlias = TableAlias()
let request = Book
.including(required: Book.author
.filter(Column("countryCode") == "ES")
.aliased(authorAlias))
.order(authorAlias[Column("name")], Column("title"))
```
The same request can also be built in three distinct steps, as below:
```swift
// 1. include author
var request = Book.including(required: Book.author)
// 2. filter by author country
request = request.joining(required: Book.author.filter(Column("countryCode") == "ES"))
// 3. sort by author name and then title
let authorAlias = TableAlias()
request = request
.joining(optional: Book.author.aliased(authorAlias))
.order(authorAlias[Column("name")], Column("title"))
```
See how the `Book.author` has been joined or included, on each step, independently, for a different purpose. We can wrap those steps in an extension to the `QueryInterfaceRequest<Book>` type:
```swift
extension QueryInterfaceRequest where T == Book {
func filter(authorCountryCode: String) -> QueryInterfaceRequest<Book> {
let filteredAuthor = Book.author.filter(Column("countryCode") == countryCode)
return joining(required: filteredAuthor)
}
func orderedByAuthorNameAndTitle() -> QueryInterfaceRequest<Book> {
let authorAlias = TableAlias()
return joining(optional: Book.author.aliased(authorAlias))
.order(authorAlias[Column("name")], Column("title"))
}
}
```
And now our complex request looks much simpler:
```swift
let request = Book
.including(required: Book.author)
.filter(authorCountryCode: "ES")
.orderedByAuthorNameAndTitle()
```
When you join or include an association several times, with the same **[association key](#the-structure-of-a-joined-request)**, GRDB will apply the following rules:
- `including` wins over `joining`:
```swift
// Equivalent to Record.including(optional: association)
Record
.including(optional: association)
.joining(optional: association)
```
- `required` wins over `optional`:
```swift
// Equivalent to Record.including(required: association)
Record
.including(required: association)
.including(optional: association)
```
- All [filters](#filtering-associations) are applied:
```swift
// Equivalent to Record.including(required: association.filter(condition1 && condition2))
Record
.including(required: association.filter(condition1))
.including(optional: association.filter(condition1))
```
- The last [ordering](#sorting-associations) wins:
```swift
// Equivalent to Record.including(required: association.order(ordering2))
Record
.including(required: association.order(ordering1))
.including(optional: association.order(ordering2))
```
- The last [selection](#columns-selected-by-an-association) wins:
```swift
// Equivalent to Record.including(required: association.select(selection2))
Record
.including(required: association.select(selection1))
.including(optional: association.select(selection2))
```
Fetching Values from Associations
=================================
@@ -1060,7 +1174,7 @@ let bookInfos = try BookInfo.fetchAll(db, request) // [BookInfo]
## The Structure of a Joined Request
**Joined request define a tree of associated records identified by "association keys".**
**Joined request defines a tree of associated records identified by "association keys".**
Below, author and cover image are both associated to book, and country is associated to author:
@@ -1285,6 +1399,444 @@ let country: Country? = row["country"]
You can also perform custom navigation in the tree by using *row scopes*. See [Row Adapters] for more information.
## Association Aggregates
It is possible to fetch aggregated values from a **[HasMany]** association:
Counting associated records, fetching the minimum, maximum, average value of an associated record column, computing the sum of an associated record column, these are all aggregation operations.
When you need to compute aggregates **from a single record**, you use regular aggregating methods, detailed in the [Fetching Aggregated Values] chapter. For example:
```swift
let author: Author = ...
let bookCount = try author.books.fetchCount(db) // Int
let request = author.books.select(max(yearColumn))
let maxBookYear = try Int.fetchOne(db, request) // Int?
```
When you need to compute aggregates **from several record**, in a single shot, you'll use an **association aggregate**. Those are the topic of this chapter.
For example, you'll use the `isEmpty` aggregate when you want, say, to fetch all authors who wrote no book at all:
```swift
let lazyAuthors: [Author] = try Author.having(Author.books.isEmpty).fetchAll(db)
let productiveAuthors: [Author] = try Author.having(Author.books.isEmpty == false).fetchAll(db)
```
And you'll use the `count` aggregate in order to fetch all authors along with the number of books they wrote:
```swift
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookCount: Int
}
let request = Author.annotated(with: Author.books.count)
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
for info in authorInfos {
print("\(info.author.name) wrote \(info.bookCount) book(s).")
}
```
### Available Association Aggregates
**HasMany** associations let you build the following association aggregates:
- `books.count`
- `books.isEmpty`
- `books.min(column)`
- `books.max(column)`
- `books.average(column)`
- `books.sum(column)`
### Annotating a Request with Aggregates
The `annotated(with:)` method appends aggregated values to the selected columns of a request. You can append as many aggregates values as needed, from one or several associations.
In order to access those values, you fetch records that have matching properties.
For example:
```swift
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookCount: Int
var maxBookYear: Int?
}
// SELECT author.*,
// COUNT(DISTINCT book.rowid) AS bookCount,
// MAX(book.year) AS maxBookYear,
// FROM author
// LEFT JOIN book ON book.authorId = author.id
// GROUP BY author.id
let request = Author.annotated(with:
Author.books.count,
Author.books.max(Column("year")))
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
for info in authorInfos {
print(info.author.name)
print("- number of books: \(info.bookCount)")
print("- last book published on: \(info.maxBookYear)")
}
```
As seen in the above example, some aggregated values are given a **default name**, such as "bookCount" or "maxBookYear". The default name is built from the aggregating method, the **[association key](#the-structure-of-a-joined-request)**, and the aggregated column name:
| Method | Key | Column | Default name |
| --------- | --- | ------ | ------------- |
| `Author.books.isEmpty ` | `book` | - | - |
| `Author.books.count ` | `book` | - | `bookCount` |
| `Author.books.min(Column("year"))` | `book` | `year` | `minBookYear` |
| `Author.books.max(Column("year"))` | `book` | `year` | `maxBookYear` |
| `Author.books.average(Column("price"))` | `book` | `price` | `averageBookPrice` |
| `Author.books.sum(Column("awards")) ` | `book` | `awards` | `bookAwardsSum` |
You give a custom name to an aggregated value with the `aliased` method:
```swift
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var numberOfBooks: Int
}
// SELECT author.*, COUNT(DISTINCT book.rowid) AS numberOfBooks
// FROM author
// LEFT JOIN book ON book.authorId = author.id
// GROUP BY author.id
let request = Author.annotated(with: Author.books.count.aliased("numberOfBooks"))
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
The `aliased` method also accept coding keys:
```swift
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var numberOfBooks: Int
static func fetchAll(_ db: Database) throws -> [AuthorInfo] {
let request = Author.annotated(with: Author.books.count.aliased(CodingKey.numberOfBooks))
return try AuthorInfo.fetchAll(db, request)
}
}
```
Custom names help consuming complex aggregates that have no name by default:
```swift
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var workCount: Int
}
// SELECT author.*,
// (COUNT(DISTINCT book.rowid) + COUNT(DISTINCT painting.rowid)) AS workCount
// FROM author
// LEFT JOIN book ON book.authorId = author.id
// LEFT JOIN painting ON painting.authorId = author.id
// GROUP BY author.id
let aggregate = Author.books.count + Author.paintings.count
let request = Author.annotated(with: aggregate.aliased("workCount"))
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
### Filtering a Request with Aggregates
The `having(_:)` method filters a request according to an aggregated value. You can append as many aggregate conditions as needed, from one or several associations.
- Authors who did not write any book:
<details>
<summary>SQL</summary>
```sql
SELECT author.*
FROM author
LEFT JOIN book ON book.authorId = author.id
GROUP BY author.id
HAVING COUNT(DISTINCT book.rowid) = 0
```
</details>
```swift
let request = Author.having(Author.books.isEmpty)
```
- Authors who wrote at least one book:
<details>
<summary>SQL</summary>
```sql
SELECT author.*
FROM author
LEFT JOIN book ON book.authorId = author.id
GROUP BY author.id
HAVING COUNT(DISTINCT book.rowid) > 0
```
</details>
```swift
let request = Author.having(Author.books.isEmpty == false)
```
- Authors who wrote at least two books:
<details>
<summary>SQL</summary>
```sql
SELECT author.*
FROM author
LEFT JOIN book ON book.authorId = author.id
GROUP BY author.id
HAVING COUNT(DISTINCT book.rowid) >= 2
```
</details>
```swift
let request = Author.having(Author.books.count >= 2)
```
- Authors who wrote at least one book after 2010:
<details>
<summary>SQL</summary>
```sql
SELECT author.*
FROM author
LEFT JOIN book ON book.authorId = author.id
GROUP BY author.id
HAVING MAX(book.year) >= 2010
```
</details>
```swift
let request = Author.having(Author.books.max(Column("year")) >= 2010)
```
- Authors who wrote at least one book of kind "novel":
<details>
<summary>SQL</summary>
```sql
SELECT author.*
FROM author
LEFT JOIN book ON book.authorId = author.id AND book.kind = 'novel'
GROUP BY author.id
HAVING COUNT(DISTINCT book.rowid) > 0
```
</details>
```swift
let novels = Author.books.filter(Column("kind") == "novel")
let request = Author.having(novels.isEmpty == false)
```
- Authors who wrote more books than they made paintings:
<details>
<summary>SQL</summary>
```sql
SELECT author.*
FROM author
LEFT JOIN book ON book.authorId = author.id
LEFT JOIN painting ON painting.authorId = author.id
GROUP BY author.id
HAVING COUNT(DISTINCT book.rowid) > COUNT(DISTINCT painting.rowid)
```
</details>
```swift
let request = Author.having(Author.books.count > Author.paintings.count)
```
- Authors who wrote no book, but made at least one painting:
<details>
<summary>SQL</summary>
```sql
SELECT author.*
FROM author
LEFT JOIN book ON book.authorId = author.id
LEFT JOIN painting ON painting.authorId = author.id
GROUP BY author.id
HAVING ((COUNT(DISTINCT book.rowid) = 0) AND (COUNT(DISTINCT painting.rowid) > 0))
```
</details>
```swift
let request = Author.having(Author.books.isEmpty && !Author.paintings.isEmpty)
```
### Isolation of Multiple Aggregates
When you compute multiple aggregates, make sure they use as many distinct **[association keys](#the-structure-of-a-joined-request)** as there are distinct populations of associated records.
In the example below, we use compute two aggregates from the same association `Author.books`. Both aggregates are computed on the same population of associated records, and so we want them to share the same association key:
- Authors with the publishing year of their first and last book:
<details>
<summary>SQL</summary>
```sql
SELECT author.*,
MIN(book.year) AS minBookYear,
MAX(book.year) AS maxBookYea
FROM author
LEFT JOIN book ON book.authorId = author.id
GROUP BY author.id
```
</details>
```swift
struct Author: TableRecord {
static let books = hasMany(Book.self) // association key "book"
}
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var minBookYear: Int?
var maxBookYear: Int?
}
let request = Author.annotated(with:
Author.books.min(Column("year")), // association key "book"
Author.books.max(Column("year"))) // association key "book"
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
In this other example, the `Author.books` and `Author.paintings` have the distinct `book` and `painting` keys. They don't interfere, and provide the expected results:
- Authors with their number of books and paintings:
<details>
<summary>SQL</summary>
```sql
SELECT author.*,
(COUNT(DISTINCT book.rowid) + COUNT(DISTINCT painting.rowid)) AS workCount
FROM author
LEFT JOIN book ON book.authorId = author.id
LEFT JOIN painting ON painting.authorId = author.id
GROUP BY author.id
```
</details>
```swift
struct Author: TableRecord {
static let books = hasMany(Book.self) // association key "book"
static let paintings = hasMany(Painting.self) // association key "painting"
}
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var workCount: Int
}
let aggregate = Author.books.count + // association key "book"
Author.paintings.count // association key "painting"
let request = Author.annotated(with: aggregate.aliased("workCount"))
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
But in the following example, we use the same association `Author.books` twice, in order to compute aggregates on two distinct populations of associated books. We must provide explicit keys in order to make sure both aggregates are computed independently:
- Authors with their number of novels and theatre plays:
<details>
<summary>SQL</summary>
```sql
SELECT author.*,
COUNT(DISTINCT book1.rowid) AS novelCount,
COUNT(DISTINCT book2.rowid) AS theatrePlayCount
FROM author
LEFT JOIN book book1 ON book1.authorId = author.id AND book1.kind = 'novel'
LEFT JOIN book book2 ON book2.authorId = author.id AND book2.kind = 'theatrePlay'
GROUP BY author.id
```
</details>
```swift
struct Author: TableRecord {
static let books = hasMany(Book.self) // association key "book"
}
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var novelCount: Int
var theatrePlayCount: Int
}
let novelCount = Author.books
.filter(Column("kind") == "novel")
.forKey("novel") // association key "novel"
.count
let theatrePlayCount = Author.books
.filter(Column("kind") == "theatrePlay")
.forKey("theatrePlay") // association key "theatrePlay"
.count
let request = Author.annotated(with: novelCount, theatrePlayCount)
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
When one doesn't use distinct association keys for novels and theatre plays, GRDB will not count two distinct sets of associated books, and will not fetch the expected results:
<details>
<summary>SQL</summary>
```sql
SELECT author.*,
COUNT(DISTINCT book.rowid) AS novelCount,
COUNT(DISTINCT book.rowid) AS theatrePlayCount
FROM author
LEFT JOIN book ON book.authorId = author.id
AND (book.kind = 'novel' AND book.kind = 'theatrePlay')
GROUP BY author.id
```
</details>
```swift
// WRONG: not counting distinct sets of associated books
let novelCount = Author.books // association key "book"
.filter(Column("kind") == "novel")
.count
.aliased("novelCount")
let theatrePlayCount = Author.books // association key "book"
.filter(Column("kind") == "theatrePlay")
.count
.aliased("theatrePlayCount")
let request = Author.annotated(with: novelCount, theatrePlayCount)
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
## DerivableRequest Protocol
The `DerivableRequest` protocol is adopted by both [query interface requests] such as `Author.all()` and associations such as `Book.author`. It is intended for you to use as a customization point when you want to extend the built-in GRDB apis.
@@ -1333,26 +1885,6 @@ let request = Book
This code compiles, but you'll get a runtime fatal error "Not implemented: chaining a required association behind an optional association". Future versions of GRDB may allow such requests.
**You can't join two associations with the same [association key](#the-structure-of-a-joined-request) at the same level:**
```swift
// NOT IMPLEMENTED
let request = Book
.including(Book.author) // key "author"
.including(Book.author) // key "author"
```
This code compiles, but you'll get a runtime fatal error "The association key `author` is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.". Future versions of GRDB may allow such requests.
To join the same table twice, and make sure GRDB does not modify the fetched results in some future release, make sure no two associations have the same name on a given level:
```swift
// OK
let request = Book
.including(Book.author.forKey("firstAuthor"))
.including(Book.author.forKey("secondAuthor"))
```
## Future Directions
@@ -1362,12 +1894,6 @@ The APIs that have been described above do not cover the whole topic of joined r
- One can not yet express requests such as "all authors with all their books".
- A common use case of associations is aggregations, such as fetching all authors with the number of books they have written:
```swift
let request = Author.annotate(with: Author.books.count)
```
- There's no HasOneThrough and HasManyThrough association, which would allow to skip intermediate bridge records when building requests.
Those features are not present yet because they hide several very tough challenges. Come [discuss](http://twitter.com/groue) for more information, or if you wish to help turning those features into reality.
@@ -1383,7 +1909,7 @@ This documentation owns a lot to the [Active Record Associations](http://guides.
**GRDB**
Copyright (C) 2018 Gwendal Roué
Copyright (C) 2019 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:
@@ -1440,11 +1966,17 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Sorting Associations]: #sorting-associations
[Columns Selected by an Association]: #columns-selected-by-an-association
[Table Aliases]: #table-aliases
[Refining Association Requests]: #refining-association-requests
[The Structure of a Joined Request]: #the-structure-of-a-joined-request
[Decoding a Joined Request with a Decodable Record]: #decoding-a-joined-request-with-a-decodable-record
[Decoding a Hierarchical Decodable Record]: #decoding-a-hierarchical-decodable-record
[Decoding a Joined Request with FetchableRecord]: #decoding-a-joined-request-with-fetchablerecord
[Custom Requests]: ../README.md#custom-requests
[Association Aggregates]: #association-aggregates
[Available Association Aggregates]: #available-association-aggregates
[Annotating a Request with Aggregates]: #annotating-a-request-with-aggregates
[Filtering a Request with Aggregates]: #filtering-a-request-with-aggregates
[Isolation of Multiple Aggregates]: #isolation-of-multiple-aggregates
[DerivableRequest Protocol]: #derivablerequest-protocol
[Known Issues]: #known-issues
[Future Directions]: #future-directions
@@ -1453,3 +1985,4 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[TableRecord]: ../README.md#tablerecord-protocol
[association requests]: #building-requests-from-associations
[Good Practices for Designing Record Types]: GoodPracticesForDesigningRecordTypes.md
[Fetching Aggregated Values]: ../README.md#fetching-aggregated-values
+2 -2
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.24.0](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.25.2](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 v3.2.0
git checkout v3.6.2
git submodule update --init SQLiteCustom/src
````
+46 -7
View File
@@ -160,9 +160,45 @@ struct Player: FetchableRecord, TableRecord {
score = row[Columns.score]
}
}
extension Player {
static func filter(name: String) -> QueryInterfaceRequest<Player> {
return filter(Columns.name == name)
}
static var maximumScore: QueryInterfaceRequest<Int> {
return select(max(Columns.score), as: Int.self)
}
}
```
GRDB can apply additional optimizations on expressions that adopt ColumnExpression, so conform to this protocol when you define a custom column type:
When your record adopts the Codable protocol, you can use its [coding keys](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) as columns:
```swift
// GRDB 3
struct Player: Codable, FetchableRecord, PersistableRecord {
var id: Int64
var name: String
var score: Int
// Add ColumnExpression conformance
private enum CodingKeys: String, CodingKey, ColumnExpression {
case id, name, score
}
}
extension Player {
static func filter(name: String) -> QueryInterfaceRequest<Player> {
return filter(CodingKeys.name == name)
}
static var maximumScore: QueryInterfaceRequest<Int> {
return select(max(CodingKeys.score), as: Int.self)
}
}
```
GRDB can apply additional optimizations on expressions that adopt ColumnExpression, so conform to this protocol whenever you define a custom column type:
```swift
struct TypedColumn: ColumnExpression {
@@ -410,14 +446,16 @@ Now you'll write instead:
```swift
// GRDB 3
dbQueue.rx
.fetch(from: [request, ...]) { db in try fetchResult(db) }
ValueObservation
.tracking([request, ...], fetch: { db in try fetchResult(db) })
.rx
.fetch(in: dbQueue)
.subscribe(...)
```
It's just a syntactic change, without any impact on the runtime.
RxGRDB for GRDB 3 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition.
GRDB 3.6 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition.
For example:
@@ -442,8 +480,9 @@ dbQueue.rx
// GRDB 3: Track a team and its players
struct TeamInfoRequest: DatabaseRegionConvertible { ... }
let request = TeamInfoRequest(teamId: 1)
dbQueue.rx
.fetch(from: [request]) { try request.fetchOne($0) }
ValueObservation.tracking(request, fetch: { try request.fetchOne($0) })
.rx
.fetch(in: dbQueue)
.subscribe(onNext: { teamInfo: TeamInfo? in
...
})
@@ -490,5 +529,5 @@ If you have time, you may dig deeper in GRDB 3 with those updated documentation
[record protocols]: ../README.md#record-protocols-overview
[Custom requests]: ../README.md#custom-requests
[query interface]: ../README.md#the-query-interface
[DatabaseRegionConvertible]: https://github.com/groue/RxGRDB/blob/master/README.md#databaseregionconvertible-protocol
[DatabaseRegionConvertible]: https://github.com/groue/GRDB.swift#the-databaseregionconvertible-protocol
[conditional conformances]: https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md
@@ -308,11 +308,13 @@ This synchronization is not automatic with GRDB: records do not "auto-update". T
Instead, have a look at [Database Observation]:
> :bulb: **Tip**: Use [FetchedRecordsController] when a table or collection views should remained synchronized with the database, in an animated way.
> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes.
>
> :bulb: **Tip**: Use [RxGRDB] when your application needs to react to all changes in the results of a database request.
> :bulb: **Tip**: [FetchedRecordsController] performs automated tracking of database changes, and can animate the cells of a table or collection view.
>
> :bulb: **Tip**: Use [TransactionObserver], the low-level protocol for database observation, for your most advanced needs.
> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way.
>
> :bulb: **Tip**: [TransactionObserver] provides low-level database observation, for your most advanced needs.
>
> :bulb: **Tip**: Don't try to write complex methods that both modify the database and the values in memory at the same time. Instead, modify the database with plain record types, and rely on database observation for automatically refreshing values, even complex ones.
@@ -337,6 +339,7 @@ Instead, have a look at [Database Observation]:
[Concurrency Guide]: ../README.md#concurrency
[PersistableRecord]: ../README.md#persistablerecord-protocol
[Database Observation]: ../README.md#database-changes-observation
[ValueObservation]: ../README.md#valueobservation
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[TransactionObserver]: ../README.md#transactionobserver-protocol
Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

@@ -0,0 +1,173 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="489px" height="362px" viewBox="0 0 489 362" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 51.2 (57519) - http://www.bohemiancoding.com/sketch -->
<title>DatabasePoolScheduling</title>
<desc>Created with Sketch.</desc>
<defs>
<linearGradient x1="50%" y1="100%" x2="50%" y2="1.41638472e-14%" id="linearGradient-1">
<stop stop-color="#FFFFFF" stop-opacity="0.9" offset="0%"></stop>
<stop stop-color="#FFFFFF" offset="100%"></stop>
</linearGradient>
<rect id="path-2" x="0" y="0" width="120" height="88" rx="10"></rect>
<filter x="-12.1%" y="-13.1%" width="124.2%" height="133.0%" filterUnits="objectBoundingBox" id="filter-4">
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
</filter>
<rect id="path-5" x="0" y="0" width="120" height="250" rx="10"></rect>
<filter x="-12.1%" y="-4.6%" width="124.2%" height="111.6%" filterUnits="objectBoundingBox" id="filter-7">
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
</filter>
<rect id="path-8" x="0" y="0" width="120" height="94" rx="10"></rect>
<filter x="-12.1%" y="-12.2%" width="124.2%" height="130.9%" filterUnits="objectBoundingBox" id="filter-10">
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
</filter>
<rect id="path-11" x="0" y="0" width="120" height="44" rx="10"></rect>
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-13">
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
</filter>
<rect id="path-14" x="0" y="0" width="120" height="44" rx="10"></rect>
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-16">
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
</filter>
<rect id="path-17" x="0" y="0" width="120" height="44" rx="10"></rect>
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-19">
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
</filter>
</defs>
<g id="Page-3" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="DatabasePoolScheduling">
<g id="Group-2" transform="translate(44.000000, 0.000000)" stroke="#D7D7D7">
<rect id="Rectangle-2" x="0.5" y="0.5" width="444" height="361" rx="6"></rect>
<rect id="Rectangle-2-Copy" fill-opacity="0.02" fill="#000000" x="148.5" y="0.5" width="148" height="361"></rect>
</g>
<text id="Thread-1" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal" fill="#000000">
<tspan x="89.9428711" y="26">Thread 1</tspan>
</text>
<text id="Thread-2" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal" fill="#000000">
<tspan x="236.979004" y="26">Thread 2</tspan>
</text>
<text id="Thread-3" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal" fill="#000000">
<tspan x="384.818359" y="26">Thread 3</tspan>
</text>
<g id="BlueBox" transform="translate(58.000000, 44.000000)">
<g id="Group">
<mask id="mask-3" fill="white">
<use xlink:href="#path-2"></use>
</mask>
<g id="Rectangle">
<use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-2"></use>
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-2"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="89" rx="10"></rect>
</g>
<text id="Label" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="15.7509766" y="49">Read State A</tspan>
</text>
</g>
</g>
<g id="BlueBox" transform="translate(355.000000, 94.000000)">
<g id="Group">
<mask id="mask-6" fill="white">
<use xlink:href="#path-5"></use>
</mask>
<g id="Rectangle">
<use fill="black" fill-opacity="1" filter="url(#filter-7)" xlink:href="#path-5"></use>
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-5"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="251" rx="10"></rect>
</g>
<text id="Label" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="15.7509766" y="130">Read State A</tspan>
</text>
</g>
</g>
<g id="GreenBox" transform="translate(207.000000, 60.000000)">
<g id="Group">
<mask id="mask-9" fill="white">
<use xlink:href="#path-8"></use>
</mask>
<g id="Rectangle">
<use fill="black" fill-opacity="1" filter="url(#filter-10)" xlink:href="#path-8"></use>
<use fill="#366500" fill-rule="evenodd" xlink:href="#path-8"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="95" rx="10"></rect>
</g>
<text id="Label" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="14.7802734" y="52">Write State B</tspan>
</text>
</g>
</g>
<g id="GreenBox" transform="translate(58.000000, 172.000000)">
<g id="Group">
<mask id="mask-12" fill="white">
<use xlink:href="#path-11"></use>
</mask>
<g id="Rectangle">
<use fill="black" fill-opacity="1" filter="url(#filter-13)" xlink:href="#path-11"></use>
<use fill="#366500" fill-rule="evenodd" xlink:href="#path-11"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
</g>
<text id="Label" mask="url(#mask-12)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="15.9663086" y="27">Read State B</tspan>
</text>
</g>
</g>
<g id="OrangeBox" transform="translate(58.000000, 231.000000)">
<g id="Group">
<mask id="mask-15" fill="white">
<use xlink:href="#path-14"></use>
</mask>
<g id="Rectangle">
<use fill="black" fill-opacity="1" filter="url(#filter-16)" xlink:href="#path-14"></use>
<use fill="#CD7F00" fill-rule="evenodd" xlink:href="#path-14"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
</g>
<text id="Label" mask="url(#mask-15)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="14.4179688" y="27">Write State C</tspan>
</text>
</g>
</g>
<g id="OrangeBox" transform="translate(207.000000, 300.000000)">
<g id="Group">
<mask id="mask-18" fill="white">
<use xlink:href="#path-17"></use>
</mask>
<g id="Rectangle">
<use fill="black" fill-opacity="1" filter="url(#filter-19)" xlink:href="#path-17"></use>
<use fill="#CD7F00" fill-rule="evenodd" xlink:href="#path-17"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
</g>
<text id="Label" mask="url(#mask-18)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="15.6040039" y="27">Read State C</tspan>
</text>
</g>
</g>
<g id="Group-4" transform="translate(0.000000, 13.000000)" fill="#000000">
<text id="Time" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="0.501953125" y="13">Time</tspan>
</text>
<path id="Line" d="M16.5,340 L21,331 L12,331 L16.5,340 Z M16,22.5 L16,331.5 L16,332 L17,332 L17,331.5 L17,22.5 L17,22 L16,22 L16,22.5 Z" fill-rule="nonzero"></path>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

@@ -0,0 +1,150 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="489px" height="362px" viewBox="0 0 489 362" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 51.2 (57519) - http://www.bohemiancoding.com/sketch -->
<title>DatabaseQueueScheduling</title>
<desc>Created with Sketch.</desc>
<defs>
<linearGradient x1="50%" y1="100%" x2="50%" y2="1.41638472e-14%" id="linearGradient-1">
<stop stop-color="#FFFFFF" stop-opacity="0.9" offset="0%"></stop>
<stop stop-color="#FFFFFF" offset="100%"></stop>
</linearGradient>
<rect id="path-2" x="0" y="0" width="120" height="44" rx="10"></rect>
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-4">
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
</filter>
<rect id="path-5" x="0" y="0" width="120" height="44" rx="10"></rect>
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-7">
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
</filter>
<rect id="path-8" x="0" y="0" width="120" height="44" rx="10"></rect>
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-10">
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
</filter>
<rect id="path-11" x="0" y="0" width="120" height="44" rx="10"></rect>
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-13">
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
</filter>
<rect id="path-14" x="0" y="0" width="120" height="44" rx="10"></rect>
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-16">
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
</filter>
</defs>
<g id="Page-3" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="DatabaseQueueScheduling">
<g id="Group-2" transform="translate(44.000000, 0.000000)" stroke="#D7D7D7">
<rect id="Rectangle-2" x="0.5" y="0.5" width="444" height="361" rx="6"></rect>
<rect id="Rectangle-2-Copy" fill-opacity="0.02" fill="#000000" x="148.5" y="0.5" width="148" height="361"></rect>
</g>
<text id="Thread-1" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal" fill="#000000">
<tspan x="89.9428711" y="26">Thread 1</tspan>
</text>
<text id="Thread-2" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal" fill="#000000">
<tspan x="236.979004" y="26">Thread 2</tspan>
</text>
<text id="Thread-3" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal" fill="#000000">
<tspan x="384.818359" y="26">Thread 3</tspan>
</text>
<g id="Group-4" transform="translate(0.000000, 13.000000)" fill="#000000">
<text id="Time" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="0.501953125" y="13">Time</tspan>
</text>
<path id="Line" d="M16.5,340 L21,331 L12,331 L16.5,340 Z M16,22.5 L16,331.5 L16,332 L17,332 L17,331.5 L17,22.5 L17,22 L16,22 L16,22.5 Z" fill-rule="nonzero"></path>
</g>
<g id="BlueBox" transform="translate(58.000000, 44.000000)">
<g id="Group">
<mask id="mask-3" fill="white">
<use xlink:href="#path-2"></use>
</mask>
<g id="Rectangle">
<use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-2"></use>
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-2"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
</g>
<text id="Label" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="15.7509766" y="27">Read State A</tspan>
</text>
</g>
</g>
<g id="GreenBox" transform="translate(207.000000, 110.000000)">
<g id="Group">
<mask id="mask-6" fill="white">
<use xlink:href="#path-5"></use>
</mask>
<g id="Rectangle">
<use fill="black" fill-opacity="1" filter="url(#filter-7)" xlink:href="#path-5"></use>
<use fill="#366500" fill-rule="evenodd" xlink:href="#path-5"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
</g>
<text id="Label" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="14.7802734" y="27">Write State B</tspan>
</text>
</g>
</g>
<g id="GreenBox" transform="translate(355.000000, 159.000000)">
<g id="Group">
<mask id="mask-9" fill="white">
<use xlink:href="#path-8"></use>
</mask>
<g id="Rectangle">
<use fill="black" fill-opacity="1" filter="url(#filter-10)" xlink:href="#path-8"></use>
<use fill="#366500" fill-rule="evenodd" xlink:href="#path-8"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
</g>
<text id="Label" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="15.9663086" y="27">Read State B</tspan>
</text>
</g>
</g>
<g id="OrangeBox" transform="translate(355.000000, 297.000000)">
<g id="Group">
<mask id="mask-12" fill="white">
<use xlink:href="#path-11"></use>
</mask>
<g id="Rectangle">
<use fill="black" fill-opacity="1" filter="url(#filter-13)" xlink:href="#path-11"></use>
<use fill="#CD7F00" fill-rule="evenodd" xlink:href="#path-11"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
</g>
<text id="Label" mask="url(#mask-12)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="15.6040039" y="27">Read State C</tspan>
</text>
</g>
</g>
<g id="OrangeBox" transform="translate(58.000000, 231.000000)">
<g id="Group">
<mask id="mask-15" fill="white">
<use xlink:href="#path-14"></use>
</mask>
<g id="Rectangle">
<use fill="black" fill-opacity="1" filter="url(#filter-16)" xlink:href="#path-14"></use>
<use fill="#CD7F00" fill-rule="evenodd" xlink:href="#path-14"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
</g>
<text id="Label" mask="url(#mask-15)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="14.4179688" y="27">Write State C</tspan>
</text>
</g>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 285 KiB

+3
View File
@@ -0,0 +1,3 @@
fixfonts:
sed -i '' -- 's/SFUIText-Regular, SF UI Text/-apple-system,sans-serif/g' *.svg
sed -i '' -- 's/SFUIText-Semibold, SF UI Text/-apple-system,sans-serif/g' *.svg
+2 -1
View File
@@ -18,15 +18,16 @@ To release a new GRDB version:
- Documentation/CustomSQLiteBuilds.md
- GRDB.swift.podspec
- GRDBCipher.podspec
- GRDBPlus.podspec
- README.md
- Support/Info.plist
- Commit and tag
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
- Push to the master branch
- `pod trunk push --allow-warnings GRDB.swift.podspec`
- `pod trunk push --allow-warnings GRDBPlus.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):
+6 -2
View File
@@ -86,6 +86,8 @@ extension Place: PersistableRecord { ... }
try place.delete(db)
```
For your convenience, those record protocols can be derived from the [Decodable and Encodable](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) protocols of the standard library. [Codable records] are even given free support for JSON columns and other niceties.
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
@@ -113,7 +115,7 @@ let players = try Player.fetchAll(db)
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, by observing database changes and react accordingly, or in any way deemed relevant.
There are several ways to be notified of database changes. You can build on top of the low-level [TransactionObserver] protocol. Or you can use [FetchedRecordsController], which looks a lot like Core Data's NSFetchedResultsController, and is able to animate table and collection views. And don't forget [RxGRDB], a set of reactive extensions based on [RxSwift]:
There are several ways to be notified of database changes. You can build on top of the fundamental but low-level [TransactionObserver] protocol. Usually, you'll use [ValueObservation], which notifies fresh values after each database change, or [FetchedRecordsController], which animates table and collection views. And don't forget [RxGRDB], a set of reactive extensions based on [RxSwift]:
```swift
Player.all().rx
@@ -250,7 +252,7 @@ extension Player {
let players = try Player.customRequest(...).fetchAll(db)
```
Those custom requests are welcome in database observation tools like [FetchedRecordsController] and [RxGRDB]:
Those custom requests are welcome in database observation tools like [ValueObservation] and [RxGRDB]:
```swift
Player.customRequest(...).rx
@@ -273,6 +275,7 @@ Happy GRDB! :gift:
[DatabasePool]: ../README.md#database-pools
[Diesel]: http://diesel.rs
[FCModel]: https://github.com/marcoarment/FCModel
[ValueObservation]: ../README.md#valueobservation
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
[Fluent]: https://github.com/vapor/fluent
[FMDB]: http://github.com/ccgus/fmdb
@@ -290,3 +293,4 @@ Happy GRDB! :gift:
[TransactionObserver]: ../README.md#transactionobserver-protocol
[query interface]: ../README.md#the-query-interface
[associations]: AssociationsBasics.md
[Codable records]: ../README.md#codable-records
+18 -18
View File
@@ -1,20 +1,20 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '3.2.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
s.homepage = 'https://github.com/groue/GRDB.swift'
s.author = { 'Gwendal Roué' => 'gr@pierlis.com' }
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
s.module_name = 'GRDB'
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.9'
s.watchos.deployment_target = '2.0'
s.source_files = 'GRDB/**/*.swift', 'Support/*.h'
s.module_map = 'Support/module.modulemap'
s.framework = 'Foundation'
s.library = 'sqlite3'
s.name = 'GRDB.swift'
s.version = '3.6.2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
s.homepage = 'https://github.com/groue/GRDB.swift'
s.author = { 'Gwendal Roué' => 'gr@pierlis.com' }
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
s.module_name = 'GRDB'
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.9'
s.watchos.deployment_target = '2.0'
s.source_files = 'GRDB/**/*.swift', 'Support/*.h'
s.module_map = 'Support/module.modulemap'
s.framework = 'Foundation'
s.library = 'sqlite3'
end
+293 -29
View File
@@ -49,6 +49,29 @@
560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; };
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; };
560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; };
5613ED3521A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */; };
5613ED3621A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */; };
5613ED3721A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */; };
5613ED3F21A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */; };
5613ED4021A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */; };
5613ED4121A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */; };
5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; };
5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; };
5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; };
5613ED4821A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */; };
5613ED4921A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */; };
5613ED4A21A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */; };
5613ED4C21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */; };
5613ED4D21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */; };
5613ED4E21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */; };
5613ED5021A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; };
5613ED5121A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; };
5613ED5221A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; };
5613ED5421A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; };
5613ED5521A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; };
5613ED5621A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; };
5613EDA621A96A9300DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */; };
5613EDA721A96A9300DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */; };
561667051D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; };
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; };
5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; };
@@ -116,6 +139,40 @@
5634B10A1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; };
5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; };
5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; };
563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */; };
563B06AC217EF0CC00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */; };
563B06AD217EF0CC00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */; };
563B06BD2185CCD300B38F35 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */; };
563B06BE2185CCD300B38F35 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */; };
563B06C32185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */; };
563B06C42185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */; };
563B06C52185D29F00B38F35 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */; };
563B06C62185D29F00B38F35 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */; };
563B06C72185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */; };
563B06C82185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */; };
563B06CA2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */; };
563B06CB2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */; };
563B06F721861D8400B38F35 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */; };
563B06F821861D8400B38F35 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */; };
563B0705218627F800B38F35 /* ValueObservationRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */; };
563B0706218627F800B38F35 /* ValueObservationRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */; };
563B071521862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */; };
563B071621862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */; };
563B071821862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
563B071921862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; };
563EF416215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; };
563EF417215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; };
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF42C2161180D007DAACD /* AssociationAggregate.swift */; };
563EF42E2161180D007DAACD /* AssociationAggregate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF42C2161180D007DAACD /* AssociationAggregate.swift */; };
563EF42F2161180D007DAACD /* AssociationAggregate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF42C2161180D007DAACD /* AssociationAggregate.swift */; };
563EF43F216131D1007DAACD /* AssociationAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF43E216131D1007DAACD /* AssociationAggregateTests.swift */; };
563EF440216131D1007DAACD /* AssociationAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF43E216131D1007DAACD /* AssociationAggregateTests.swift */; };
563EF44A2161F179007DAACD /* Inflections.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF4492161F179007DAACD /* Inflections.swift */; };
563EF44B2161F179007DAACD /* Inflections.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF4492161F179007DAACD /* Inflections.swift */; };
563EF45321631E21007DAACD /* QueryInterfacePromiseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */; };
563EF45421631E21007DAACD /* QueryInterfacePromiseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */; };
563EF45D2163309F007DAACD /* Inflections.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF4492161F179007DAACD /* Inflections.swift */; };
56439B331F4CA1DC0066043F /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86191BA988F2001F9168 /* FMDatabase.m */; };
56439B341F4CA1DC0066043F /* InsertRecordClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86121BA9886D001F9168 /* InsertRecordClassTests.swift */; };
56439B351F4CA1DC0066043F /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 56BB861B1BA988F2001F9168 /* FMDatabaseAdditions.m */; };
@@ -140,7 +197,31 @@
56439B581F4CA5AE0066043F /* PerformanceTests.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 56BB86111BA9886D001F9168 /* PerformanceTests.sqlite */; };
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
5644DE6D20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
564CE4D621B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */; };
564CE4D721B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */; };
564CE4D821B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */; };
564CE4E621B2E06700652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */; };
564CE4E721B2E06800652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */; };
564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; };
564CE4EA21B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; };
564CE52021B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; };
564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; };
564CE52221B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; };
564CE59D21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
564CE59E21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
564CE59F21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; };
564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; };
564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; };
564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */; };
564CE5BF21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */; };
564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; };
564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; };
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
@@ -148,6 +229,8 @@
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
564FCE5E20F7E11B00202B90 /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */; };
564FCE5F20F7E11B00202B90 /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */; };
5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */; };
5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */; };
5653EAD820944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */; };
@@ -296,6 +379,10 @@
566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; };
5665F85D203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */; };
5665F85E203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */; };
5665FA142129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */; };
5665FA152129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */; };
5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */; };
5665FA342129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */; };
566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; };
566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; };
566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; };
@@ -321,6 +408,8 @@
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
56707201208A509C006AD95A /* DateParsingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071FA208A509C006AD95A /* DateParsingTests.swift */; };
567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; };
5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; };
@@ -369,6 +458,10 @@
56873BEC1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; };
56873BEF1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; };
56873BF21F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; };
5690AFD82120589A001530EA /* InsertRecordCodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */; };
5690AFD92120589A001530EA /* InsertRecordCodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */; };
5690AFDB212058CB001530EA /* FetchRecordCodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordCodableTests.swift */; };
5690AFDC212058CB001530EA /* FetchRecordCodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordCodableTests.swift */; };
5690C32A1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; };
5690C33B1D23E7D200E59934 /* FoundationDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */; };
5690C3401D23E82A00E59934 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
@@ -589,7 +682,6 @@
56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; };
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; };
56D4967C1D8130DB008276D7 /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
56D4967F1D813131008276D7 /* StatementColumnConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EE573C1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift */; };
56D496801D813131008276D7 /* StatementColumnConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */; };
56D496811D813131008276D7 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; };
56D496821D813131008276D7 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; };
@@ -665,7 +757,6 @@
56EA86951C91DFE7002BB4DF /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; };
56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; };
56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; };
56EE573E1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EE573C1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift */; };
56F0B9921B6001C600A2F135 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; };
56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; };
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
@@ -834,6 +925,14 @@
560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = "<group>"; };
560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = "<group>"; };
560FC5101CAEEDF10014AA8E /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = "<group>"; };
5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Map.swift"; sourceTree = "<group>"; };
5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Combine.swift"; sourceTree = "<group>"; };
5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = "<group>"; };
5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Row.swift"; sourceTree = "<group>"; };
5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+FetchableRecord.swift"; sourceTree = "<group>"; };
5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DatabaseValueConvertible.swift"; sourceTree = "<group>"; };
5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Count.swift"; sourceTree = "<group>"; };
5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCombineTests.swift; sourceTree = "<group>"; };
561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = "<group>"; };
5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = "<group>"; };
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
@@ -863,12 +962,37 @@
563363F81C960711000BE133 /* PerformanceRealmTests.realm */ = {isa = PBXFileReference; lastKnownFileType = file; path = PerformanceRealmTests.realm; sourceTree = "<group>"; };
5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = "<group>"; };
5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = "<group>"; };
563B06AA217EF0CC00B38F35 /* ValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = "<group>"; };
563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationReducerTests.swift; sourceTree = "<group>"; };
563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationExtentTests.swift; sourceTree = "<group>"; };
563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationSchedulingTests.swift; sourceTree = "<group>"; };
563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReadonlyTests.swift; sourceTree = "<group>"; };
563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationFetchTests.swift; sourceTree = "<group>"; };
563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCountTests.swift; sourceTree = "<group>"; };
563B0704218627F700B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = "<group>"; };
563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = "<group>"; };
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = "<group>"; };
563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
563EF42C2161180D007DAACD /* AssociationAggregate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = "<group>"; };
563EF43E216131D1007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = "<group>"; };
563EF4492161F179007DAACD /* Inflections.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inflections.swift; sourceTree = "<group>"; };
563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfacePromiseTests.swift; sourceTree = "<group>"; };
56439B501F4CA1DC0066043F /* GRDBOSXPerformanceComparisonTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceComparisonTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = "<group>"; };
564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+CompactMap.swift"; sourceTree = "<group>"; };
564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = "<group>"; };
564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = "<group>"; };
564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = "<group>"; };
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = "<group>"; };
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = "<group>"; };
564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = "<group>"; };
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = "<group>"; };
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = "<group>"; };
564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = "<group>"; };
5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainRowScopesTests.swift; sourceTree = "<group>"; };
5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = "<group>"; };
5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRowScopeSearchTests.swift; sourceTree = "<group>"; };
@@ -920,6 +1044,8 @@
566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = "<group>"; };
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = "<group>"; };
5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = "<group>"; };
5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = "<group>"; };
5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateEncodingStrategyTests.swift; sourceTree = "<group>"; };
566A84192041146100E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = "<group>"; };
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = "<group>"; };
566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = "<group>"; };
@@ -930,6 +1056,7 @@
566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = "<group>"; };
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = "<group>"; };
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = "<group>"; };
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = "<group>"; };
567071FA208A509C006AD95A /* DateParsingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateParsingTests.swift; sourceTree = "<group>"; };
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = "<group>"; };
567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = "<group>"; };
@@ -954,6 +1081,8 @@
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = "<group>"; };
5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordCodableTests.swift; sourceTree = "<group>"; };
5690AFDA212058CB001530EA /* FetchRecordCodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRecordCodableTests.swift; sourceTree = "<group>"; };
5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = "<group>"; };
5690C3361D23E7D200E59934 /* FoundationDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateTests.swift; sourceTree = "<group>"; };
5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = "<group>"; };
@@ -1036,8 +1165,8 @@
56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = "<group>"; };
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-4.1/Realm.framework"; sourceTree = "<group>"; };
56B8C2411CA1758F00510325 /* RealmSwift.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = RealmSwift.framework; path = "Realm/build/osx/swift-4.1/RealmSwift.framework"; sourceTree = "<group>"; };
56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-4.2.1/Realm.framework"; sourceTree = "<group>"; };
56B8C2411CA1758F00510325 /* RealmSwift.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = RealmSwift.framework; path = "Realm/build/osx/swift-4.2.1/RealmSwift.framework"; sourceTree = "<group>"; };
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = "<group>"; };
56B9649C1DA51B4C0002DA19 /* FTS5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5.swift; sourceTree = "<group>"; };
56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TokenizerDescriptor.swift; sourceTree = "<group>"; };
@@ -1109,7 +1238,6 @@
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = "<group>"; };
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = "<group>"; };
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
56EE573C1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleTests.swift; sourceTree = "<group>"; };
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
56F3E7621E67F8C100BF0F01 /* Fixits-0.101.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.101.1.swift"; sourceTree = "<group>"; };
@@ -1268,6 +1396,8 @@
560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = {
isa = PBXGroup;
children = (
5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */,
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */,
566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */,
56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */,
5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */,
@@ -1278,19 +1408,39 @@
name = PersistableRecord;
sourceTree = "<group>";
};
5613ED4221A95AFB00DC7A68 /* ValueObservation */ = {
isa = PBXGroup;
children = (
563B06AA217EF0CC00B38F35 /* ValueObservation.swift */,
5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */,
564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */,
5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */,
5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */,
564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */,
5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */,
5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */,
564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */,
5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */,
564CE43021AA901800652B19 /* ValueObserver.swift */,
5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */,
);
path = ValueObservation;
sourceTree = "<group>";
};
56176C581EACC2D8000F3F2B /* GRDBTests */ = {
isa = PBXGroup;
children = (
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
562EA81E1F17B26F00FA528C /* Compilation */,
56A238111B9C74A90082EB20 /* Core */,
5698AC3E1DA2BEBB0056AF8C /* FTS */,
56176CA01EACEE2A000F3F2B /* GRDBCipher */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
56A238231B9C74A90082EB20 /* Migrations */,
569978D31B539038005EBEED /* Private */,
56300B5C1C53C38F005A543B /* QueryInterface */,
56A238251B9C74A90082EB20 /* Record */,
56176C9F1EACEE15000F3F2B /* Support */,
563B06BF2185CD1700B38F35 /* ValueObservation */,
);
path = GRDBTests;
sourceTree = "<group>";
@@ -1359,6 +1509,7 @@
56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */,
56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */,
5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */,
563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */,
56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */,
56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */,
566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */,
@@ -1410,9 +1561,29 @@
name = DatabaseQueue;
sourceTree = "<group>";
};
563B06BF2185CD1700B38F35 /* ValueObservation */ = {
isa = PBXGroup;
children = (
5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */,
564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */,
563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */,
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */,
563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */,
563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */,
564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */,
563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */,
563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */,
563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */,
563B0704218627F700B38F35 /* ValueObservationRowTests.swift */,
563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */,
);
name = ValueObservation;
sourceTree = "<group>";
};
5653EABF20944B1300F46237 /* Association */ = {
isa = PBXGroup;
children = (
563EF43E216131D1007DAACD /* AssociationAggregateTests.swift */,
5653EAD420944B4E00F46237 /* AssociationBelongsToDecodableRecordTests.swift */,
5653EACE20944B4D00F46237 /* AssociationBelongsToFetchableRecordTests.swift */,
5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */,
@@ -1435,6 +1606,7 @@
isa = PBXGroup;
children = (
5653EAFA20944C7B00F46237 /* Association.swift */,
563EF42C2161180D007DAACD /* AssociationAggregate.swift */,
5653EAFE20944C7C00F46237 /* AssociationQuery.swift */,
5653EAFC20944C7B00F46237 /* AssociationRequest.swift */,
5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */,
@@ -1449,10 +1621,12 @@
5659F4861EA8D94E004A4992 /* Utils */ = {
isa = PBXGroup;
children = (
5659F4871EA8D94E004A4992 /* Utils.swift */,
5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */,
563EF4492161F179007DAACD /* Inflections.swift */,
563EF414215F87EB007DAACD /* OrderedDictionary.swift */,
5659F4971EA8D989004A4992 /* Pool.swift */,
5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */,
5659F49F1EA8D997004A4992 /* Result.swift */,
5659F4871EA8D94E004A4992 /* Utils.swift */,
);
path = Utils;
sourceTree = "<group>";
@@ -1469,6 +1643,7 @@
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
isa = PBXGroup;
children = (
5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */,
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */,
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */,
);
@@ -1556,9 +1731,11 @@
560A37A91C90084600949E71 /* DatabasePool */,
563363BB1C93FD32000BE133 /* DatabaseQueue */,
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */,
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */,
56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */,
56A238191B9C74A90082EB20 /* DatabaseValueConvertible */,
56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */,
@@ -1573,7 +1750,7 @@
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */,
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */,
56A238201B9C74A90082EB20 /* Statement */,
56EE573B1BB317B7007A6A95 /* StatementColumnConvertible */,
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */,
5607EFD11BB8253300605DE3 /* TransactionObserver */,
);
name = Core;
@@ -1652,9 +1829,11 @@
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
@@ -1665,8 +1844,8 @@
56A238781B9C75030082EB20 /* Statement.swift */,
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
5605F1471C672E4000235C62 /* Support */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
);
path = Core;
sourceTree = "<group>";
@@ -1708,10 +1887,12 @@
56DE7B271C41302500861EB8 /* FetchNamedValuesTests.swift */,
56DE7B291C4130AF00861EB8 /* FetchPositionalValuesTests.swift */,
56DE7B2B1C41311900861EB8 /* FetchRecordClassTests.swift */,
5690AFDA212058CB001530EA /* FetchRecordCodableTests.swift */,
56D3BE701F4EB1900034C6D2 /* FetchRecordStructTests.swift */,
56DE7B251C412FDA00861EB8 /* InsertNamedValuesTests.swift */,
56DE7B231C412F7E00861EB8 /* InsertPositionalValuesTests.swift */,
56BB86121BA9886D001F9168 /* InsertRecordClassTests.swift */,
5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */,
56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */,
56CA22211BB41565009A04C5 /* PerformanceTests.swift */,
56B8C2401CA1758F00510325 /* Realm.framework */,
@@ -1789,15 +1970,6 @@
name = Cursor;
sourceTree = "<group>";
};
56EE573B1BB317B7007A6A95 /* StatementColumnConvertible */ = {
isa = PBXGroup;
children = (
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */,
56EE573C1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift */,
);
name = StatementColumnConvertible;
sourceTree = "<group>";
};
56F0B98C1B6001C600A2F135 /* Foundation */ = {
isa = PBXGroup;
children = (
@@ -1877,6 +2049,7 @@
56A2389F1B9C753B0082EB20 /* Record */,
DC37743319C8CFCE004FCF85 /* Supporting Files */,
5659F4861EA8D94E004A4992 /* Utils */,
5613ED4221A95AFB00DC7A68 /* ValueObservation */,
);
path = GRDB;
sourceTree = "<group>";
@@ -2269,6 +2442,8 @@
56707201208A509C006AD95A /* DateParsingTests.swift in Sources */,
56DE7B2C1C41311900861EB8 /* FetchRecordClassTests.swift in Sources */,
56DE7B281C41302500861EB8 /* FetchNamedValuesTests.swift in Sources */,
5690AFD82120589A001530EA /* InsertRecordCodableTests.swift in Sources */,
5690AFDB212058CB001530EA /* FetchRecordCodableTests.swift in Sources */,
56D507831F6D7B2E00AE1C5B /* InsertRecordStructTests.swift in Sources */,
56DE7B241C412F7E00861EB8 /* InsertPositionalValuesTests.swift in Sources */,
560C98241C0E23BB00BF8471 /* PerformanceTests.swift in Sources */,
@@ -2291,10 +2466,12 @@
56D507841F6D7B2F00AE1C5B /* InsertRecordStructTests.swift in Sources */,
56439B3A1F4CA1DC0066043F /* FMDatabaseQueue.m in Sources */,
56439B3B1F4CA1DC0066043F /* FMDatabasePool.m in Sources */,
5690AFD92120589A001530EA /* InsertRecordCodableTests.swift in Sources */,
56439B3C1F4CA1DC0066043F /* PerformanceTests.swift in Sources */,
56D3BE721F4EB1A00034C6D2 /* FetchRecordStructTests.swift in Sources */,
56439B3D1F4CA1DC0066043F /* InsertNamedValuesTests.swift in Sources */,
56439B3E1F4CA1DC0066043F /* PerformanceModel.xcdatamodeld in Sources */,
5690AFDC212058CB001530EA /* FetchRecordCodableTests.swift in Sources */,
56439B3F1F4CA1DC0066043F /* FetchPositionalValuesTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -2309,25 +2486,32 @@
56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
565490CE1D5AE252005622CB /* NSNull.swift in Sources */,
565490E41D5AE252005622CB /* TableRecord.swift in Sources */,
564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
565490CF1D5AE252005622CB /* NSNumber.swift in Sources */,
566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */,
56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
565490E21D5AE252005622CB /* Record.swift in Sources */,
5656BF5120C723E300F98521 /* QueryOrdering.swift in Sources */,
565490C11D5AE236005622CB /* FetchRequest.swift in Sources */,
5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */,
56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
5613ED5221A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */,
5653EB0B20944C7C00F46237 /* Association.swift in Sources */,
564CE59F21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */,
56F5ABDA1D814330001F60CB /* NSData.swift in Sources */,
56D121601ED34978001347D2 /* Fixits-0.109.0.swift in Sources */,
564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */,
566475A81D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
5613ED3721A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */,
5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */,
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */,
56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
565490B91D5AE236005622CB /* DatabasePool.swift in Sources */,
563B06AD217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
5674A6EF1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */,
56CEB5601EAA359A00BFAF62 /* SQLOrdering.swift in Sources */,
@@ -2336,17 +2520,23 @@
565490D91D5AE252005622CB /* Migration.swift in Sources */,
56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
5698AD271DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
5613ED4121A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */,
5653EB1120944C7C00F46237 /* AssociationRequest.swift in Sources */,
C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */,
566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
5613ED4A21A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */,
565490D51D5AE252005622CB /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */,
56F3E7691E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */,
5698AC7E1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
564CE52221B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */,
5653EB1A20944C7C00F46237 /* ForeignKey.swift in Sources */,
5698AC3D1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
563EF45D2163309F007DAACD /* Inflections.swift in Sources */,
565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */,
566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
5613ED4E21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */,
5613ED5621A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */,
56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
56E06F181E85906E008AE2A4 /* Fixits-0.102.0.swift in Sources */,
@@ -2400,13 +2590,17 @@
565490DE1D5AE252005622CB /* QueryInterfaceQuery.swift in Sources */,
56F5ABDD1D814330001F60CB /* UUID.swift in Sources */,
565490CB1D5AE252005622CB /* (null) in Sources */,
563EF417215F87EB007DAACD /* OrderedDictionary.swift in Sources */,
565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */,
5653EB1720944C7C00F46237 /* AssociationQuery.swift in Sources */,
565490B81D5AE236005622CB /* DatabaseError.swift in Sources */,
564CE4D821B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */,
56BF6D3C1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */,
56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */,
5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
565490BC1D5AE236005622CB /* DatabaseSchemaCache.swift in Sources */,
563EF42F2161180D007DAACD /* AssociationAggregate.swift in Sources */,
565490BA1D5AE236005622CB /* DatabaseQueue.swift in Sources */,
565490CD1D5AE252005622CB /* Date.swift in Sources */,
5653EB0820944C7C00F46237 /* ForeignKeyRequest.swift in Sources */,
@@ -2436,6 +2630,7 @@
files = (
56BF6D401DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */,
5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */,
563EF42E2161180D007DAACD /* AssociationAggregate.swift in Sources */,
56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
@@ -2450,7 +2645,9 @@
56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */,
5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
5605F1641C672E4000235C62 /* Date.swift in Sources */,
5613ED4921A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */,
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */,
5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
@@ -2461,6 +2658,7 @@
5698AC3A1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
5664759D1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
563EF416215F87EB007DAACD /* OrderedDictionary.swift in Sources */,
563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */,
5698AD1B1DAAD17D0056AF8C /* FTS5Tokenizer.swift in Sources */,
56F3E7661E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */,
@@ -2482,6 +2680,7 @@
56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
5653EB1620944C7C00F46237 /* AssociationQuery.swift in Sources */,
560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */,
564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */,
5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */,
5657AB121D10899D006283EF /* URL.swift in Sources */,
5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
@@ -2500,6 +2699,9 @@
566B91161FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
56A238881B9C75030082EB20 /* Row.swift in Sources */,
5613ED4D21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */,
564CE4D721B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */,
563EF44B2161F179007DAACD /* Inflections.swift in Sources */,
56CEB4F41EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */,
5605F15E1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
@@ -2511,23 +2713,31 @@
5605F1661C672E4000235C62 /* NSNull.swift in Sources */,
569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
563B06AC217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */,
56D1215D1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */,
5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */,
5605F1681C672E4000235C62 /* NSNumber.swift in Sources */,
5613ED5521A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */,
564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
5656BF5020C723E300F98521 /* QueryOrdering.swift in Sources */,
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */,
560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */,
5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
5613ED5121A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */,
560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
5613ED3621A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */,
566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
5653EB0720944C7C00F46237 /* ForeignKeyRequest.swift in Sources */,
5657AABC1D107001006283EF /* NSData.swift in Sources */,
31A778841C6A4E0600F507F6 /* FetchedRecordsController.swift in Sources */,
5613ED4021A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */,
56A238861B9C75030082EB20 /* DatabaseValue.swift in Sources */,
56CEB55D1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */,
566B91261FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
@@ -2535,6 +2745,7 @@
56CEB5641EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
56873BEF1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */,
564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */,
564CE59E21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */,
56B964A01DA51B4C0002DA19 /* FTS5.swift in Sources */,
5674A6F01F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
);
@@ -2544,6 +2755,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
563B06C82185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */,
6340BF841E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */,
56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */,
56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */,
@@ -2552,6 +2764,7 @@
56A238561B9C74A90082EB20 /* RecordPrimaryKeyNoneTests.swift in Sources */,
562EA8331F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */,
563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */,
563EF45421631E21007DAACD /* QueryInterfacePromiseTests.swift in Sources */,
56A238501B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
56A238461B9C74A90082EB20 /* RowFromDictionaryTests.swift in Sources */,
@@ -2568,15 +2781,16 @@
5657AB4A1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */,
569531351C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */,
56A2385A1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift in Sources */,
56EE573E1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift in Sources */,
562756471E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */,
569531381C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */,
563B06F821861D8400B38F35 /* ValueObservationCountTests.swift in Sources */,
56A238481B9C74A90082EB20 /* RowCopiedFromStatementTests.swift in Sources */,
56EA63C6209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */,
5674A71A1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
5698AC071D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */,
56C3F7561CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */,
56B021CD1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
563B0706218627F800B38F35 /* ValueObservationRowTests.swift in Sources */,
569531271C9087B700CF1A2B /* DatabaseQueueSchemaCacheTests.swift in Sources */,
56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */,
562393341DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */,
@@ -2593,6 +2807,7 @@
56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */,
56CC9252201E093F00CB597E /* PrefixCursorTests.swift in Sources */,
563363B01C933FF8000BE133 /* MutablePersistableRecordTests.swift in Sources */,
5665FA152129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */,
5657AB421D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
56CC922D201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */,
56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
@@ -2603,10 +2818,13 @@
567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
5657AB6A1D108BA9006283EF /* FoundationURLTests.swift in Sources */,
563B06C42185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */,
564FCE5F20F7E11B00202B90 /* DatabaseValueConversionErrorTests.swift in Sources */,
5653EADF20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */,
56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */,
56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */,
56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */,
563B071621862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */,
56176C7F1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */,
56741EAC1E66A8B3003E422D /* FetchRequestTests.swift in Sources */,
5672DE5C1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */,
@@ -2617,6 +2835,7 @@
564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */,
5674A7121F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */,
5657AB521D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */,
563B071921862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */,
5665F85E203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */,
56A238441B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
560A37AC1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift in Sources */,
@@ -2626,7 +2845,9 @@
565D5D721BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */,
5623936D1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */,
567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */,
563B06CB2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */,
5623935B1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
5613EDA721A96A9300DC7A68 /* ValueObservationCombineTests.swift in Sources */,
5674A72D1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
566A84412041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */,
56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
@@ -2646,6 +2867,7 @@
56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */,
56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */,
56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */,
5665FA342129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */,
@@ -2653,6 +2875,7 @@
56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */,
5653EAE120944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
5653EAE720944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */,
563EF440216131D1007DAACD /* AssociationAggregateTests.swift in Sources */,
5695312A1C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift in Sources */,
5653EADB20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
5698ACA21DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
@@ -2660,7 +2883,9 @@
56A238401B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
564F9C221F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */,
564CE5BF21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */,
5653EAEF20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */,
564CE4E721B2E06800652B19 /* ValueObservationCompactMapTests.swift in Sources */,
56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */,
5690C32A1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */,
5657AB3A1D108BA9006283EF /* FoundationDataTests.swift in Sources */,
@@ -2675,15 +2900,18 @@
56A238B71B9CA2590082EB20 /* DatabaseTimestampTests.swift in Sources */,
568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */,
56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */,
5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */,
562393641DEE06D300A6B01F /* CursorTests.swift in Sources */,
563B06C62185D29F00B38F35 /* ValueObservationSchedulingTests.swift in Sources */,
5657AB5A1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */,
56300B6C1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift in Sources */,
5674A7231F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */,
56F0B9921B6001C600A2F135 /* FoundationNSDateTests.swift in Sources */,
56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */,
5653EAED20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
564CE4EA21B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */,
56300B5F1C53C38F005A543B /* QueryInterfaceRequestTests.swift in Sources */,
5634B10A1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */,
560C97C81BFD0B8400BF8471 /* DatabaseFunctionTests.swift in Sources */,
@@ -2691,6 +2919,7 @@
56A2383A1B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift in Sources */,
56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */,
5653EAF520944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */,
563B06BE2185CCD300B38F35 /* ValueObservationReducerTests.swift in Sources */,
56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */,
56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */,
5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */,
@@ -2706,6 +2935,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
563B06C72185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */,
6340BF801E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */,
56D496771D81309E008276D7 /* RecordInitializersTests.swift in Sources */,
56D496651D813076008276D7 /* DatabaseMigratorTests.swift in Sources */,
@@ -2714,6 +2944,7 @@
56D496B31D8133E3008276D7 /* IndexInfoTests.swift in Sources */,
562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */,
5698AC961DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
563EF45321631E21007DAACD /* QueryInterfacePromiseTests.swift in Sources */,
56D4966D1D81309E008276D7 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */,
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
56D496811D813131008276D7 /* TransactionObserverSavepointsTests.swift in Sources */,
@@ -2732,12 +2963,14 @@
56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */,
56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */,
563B06F721861D8400B38F35 /* ValueObservationCountTests.swift in Sources */,
56D4965B1D81304E008276D7 /* FoundationNSDecimalNumberTests.swift in Sources */,
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */,
56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */,
56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */,
5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
56D496801D813131008276D7 /* StatementColumnConvertibleFetchTests.swift in Sources */,
563B0705218627F800B38F35 /* ValueObservationRowTests.swift in Sources */,
56D4966E1D81309E008276D7 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
56D496891D81316E008276D7 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
56D4967C1D8130DB008276D7 /* CGFloatTests.swift in Sources */,
@@ -2754,6 +2987,7 @@
56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */,
56D4965F1D81304E008276D7 /* FoundationNSURLTests.swift in Sources */,
562393301DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */,
5665FA142129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift in Sources */,
56CC9251201E093F00CB597E /* PrefixCursorTests.swift in Sources */,
56D4965E1D81304E008276D7 /* FoundationNSStringTests.swift in Sources */,
5698AC891DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */,
@@ -2764,10 +2998,13 @@
56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */,
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
563B06C32185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */,
56D4968D1D81316E008276D7 /* DatabaseFunctionTests.swift in Sources */,
564FCE5E20F7E11B00202B90 /* DatabaseValueConversionErrorTests.swift in Sources */,
5653EADE20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */,
56D496661D813086008276D7 /* QueryInterfaceRequestTests.swift in Sources */,
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */,
563B071521862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */,
56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */,
5698ACD71DA925420056AF8C /* RowTestCase.swift in Sources */,
56176C7D1EACCD2D000F3F2B /* EncryptionTests.swift in Sources */,
@@ -2778,6 +3015,7 @@
56D496581D81304E008276D7 /* FoundationDateTests.swift in Sources */,
562205F31E420E47005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */,
564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */,
563B071821862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */,
5674A70F1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */,
56D496711D81309E008276D7 /* RecordPrimaryKeySingleTests.swift in Sources */,
5665F85D203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */,
@@ -2787,7 +3025,9 @@
5653EAF220944B4F00F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */,
56D496851D813147008276D7 /* StatementArgumentsTests.swift in Sources */,
56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */,
563B06CA2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */,
56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */,
5613EDA621A96A9300DC7A68 /* ValueObservationCombineTests.swift in Sources */,
56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */,
5698AC9E1DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
@@ -2807,6 +3047,7 @@
5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */,
56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */,
5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */,
5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */,
562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
@@ -2814,6 +3055,7 @@
56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
56D496B61D813434008276D7 /* DatabaseRegionTests.swift in Sources */,
5653EAE020944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
563EF43F216131D1007DAACD /* AssociationAggregateTests.swift in Sources */,
5653EAE620944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */,
562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */,
5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
@@ -2821,7 +3063,9 @@
56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */,
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */,
56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */,
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
564CE4E621B2E06700652B19 /* ValueObservationCompactMapTests.swift in Sources */,
5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */,
56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */,
56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */,
@@ -2836,23 +3080,26 @@
56D496681D813086008276D7 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */,
56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */,
5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */,
563B06C52185D29F00B38F35 /* ValueObservationSchedulingTests.swift in Sources */,
5698AC801DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */,
56D496821D813131008276D7 /* TransactionObserverTests.swift in Sources */,
56D496941D81317B008276D7 /* SchedulingWatchdogTests.swift in Sources */,
5674A7201F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */,
56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */,
56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */,
564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */,
5653EAEC20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
562206071E420EA4005860AC /* DatabasePoolConcurrencyTests.swift in Sources */,
5698ACB61DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */,
56D4965C1D81304E008276D7 /* FoundationNSNullTests.swift in Sources */,
5653EAD820944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */,
562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */,
56D4967F1D813131008276D7 /* StatementColumnConvertibleTests.swift in Sources */,
5653EAF420944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */,
563B06BD2185CCD300B38F35 /* ValueObservationReducerTests.swift in Sources */,
56D496971D81317B008276D7 /* DatabaseReaderTests.swift in Sources */,
56D496911D81316E008276D7 /* RowFromStatementTests.swift in Sources */,
56071A411DB54ED000CA6E47 /* FetchedRecordsControllerTests.swift in Sources */,
@@ -2869,12 +3116,18 @@
buildActionMask = 2147483647;
files = (
56873BEC1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */,
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
5613ED4C21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */,
56BF6D3D1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */,
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */,
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
563EF44A2161F179007DAACD /* Inflections.swift in Sources */,
566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
5613ED3F21A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */,
563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
@@ -2882,22 +3135,27 @@
56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */,
5613ED5421A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */,
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
56D1215A1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */,
566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
56CEB5611EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
564CE59D21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */,
5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
5605F1591C672E4000235C62 /* CGFloat.swift in Sources */,
5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
564CE52021B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */,
5659F4A01EA8D997004A4992 /* Result.swift in Sources */,
5605F1631C672E4000235C62 /* Date.swift in Sources */,
5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */,
566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
5698AC371D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */,
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */,
564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
5659F4981EA8D989004A4992 /* Pool.swift in Sources */,
5674A6F41F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */,
56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
@@ -2913,6 +3171,7 @@
5653EB252094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
564CE4D621B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */,
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */,
56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
56CEB55A1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */,
@@ -2926,13 +3185,16 @@
5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
56A238A41B9C753B0082EB20 /* Record.swift in Sources */,
56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */,
5613ED5021A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */,
5657AB0F1D10899D006283EF /* URL.swift in Sources */,
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */,
5613ED4821A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */,
56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */,
5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */,
56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */,
5605F1931C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */,
5613ED3521A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */,
566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */,
56A2388B1B9C75030082EB20 /* Statement.swift in Sources */,
5690C3401D23E82A00E59934 /* Data.swift in Sources */,
@@ -2947,6 +3209,7 @@
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
5653EB1520944C7C00F46237 /* AssociationQuery.swift in Sources */,
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */,
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */,
5605F1651C672E4000235C62 /* NSNull.swift in Sources */,
56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
5653EB1820944C7C00F46237 /* ForeignKey.swift in Sources */,
@@ -2968,6 +3231,7 @@
566475A21D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
5644DE6D20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
5657AAB91D107001006283EF /* NSData.swift in Sources */,
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
@@ -3060,13 +3324,13 @@
DEBUG_INFORMATION_FORMAT = dwarf;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-4.1",
"$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-4.2.1",
);
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = Tests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 10.12;
OTHER_SWIFT_FLAGS = "-D GRDB_COMPARE";
OTHER_SWIFT_FLAGS = "$(inherited) -D GRDB_COMPARE";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
@@ -3083,13 +3347,13 @@
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-4.1",
"$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-4.2.1",
);
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = Tests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 10.12;
OTHER_SWIFT_FLAGS = "-D GRDB_COMPARE";
OTHER_SWIFT_FLAGS = "$(inherited) -D GRDB_COMPARE";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
@@ -3245,7 +3509,7 @@
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = Tests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
OTHER_SWIFT_FLAGS = "-D SQLITE_MODULE";
OTHER_SWIFT_FLAGS = "$(inherited) -D SQLITE_MODULE";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBiOSTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@@ -3263,7 +3527,7 @@
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = Tests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
OTHER_SWIFT_FLAGS = "-D SQLITE_MODULE";
OTHER_SWIFT_FLAGS = "$(inherited) -D SQLITE_MODULE";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBiOSTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@@ -3281,7 +3545,7 @@
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = Tests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks";
OTHER_SWIFT_FLAGS = "-D SQLITE_MODULE";
OTHER_SWIFT_FLAGS = "$(inherited) -D SQLITE_MODULE";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
@@ -3299,7 +3563,7 @@
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = Tests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks";
OTHER_SWIFT_FLAGS = "-D SQLITE_MODULE";
OTHER_SWIFT_FLAGS = "$(inherited) -D SQLITE_MODULE";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
+1 -1
View File
@@ -20,7 +20,7 @@
location = "group:Issue156.playground">
</FileRef>
<FileRef
location = "group:/Users/groue/Documents/git/groue/GRDB.swift/Playgrounds/CustomizedDecodingOfDatabaseRows.playground">
location = "group:CustomizedDecodingOfDatabaseRows.playground">
</FileRef>
<FileRef
location = "group:Associations.playground">
+28 -1
View File
@@ -1,4 +1,5 @@
import Foundation
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
@@ -136,11 +137,28 @@ public struct Configuration {
/// Default: 5
public var maximumReaderCount: Int = 5
/// The quality of service class for the work performed by the database.
///
/// The quality of service is ignored if you supply a target queue.
///
/// Default: .default (.unspecified on macOS < 10.10)
public var qos: DispatchQoS
/// The target queue for the work performed by the database.
///
/// Default: nil
public var targetQueue: DispatchQueue? = nil
// MARK: - Factory Configuration
/// Creates a factory configuration
public init() { }
public init() {
if #available(OSX 10.10, *) {
qos = .default
} else {
qos = .unspecified
}
}
// MARK: - Not Public
@@ -153,6 +171,15 @@ public struct Configuration {
let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
return threadingMode.SQLiteOpenFlags | readWriteFlags
}
func makeDispatchQueue(defaultLabel: String, purpose: String? = nil) -> DispatchQueue {
let label = (self.label ?? defaultLabel) + (purpose.map { "." + $0 } ?? "")
if let targetQueue = targetQueue {
return DispatchQueue(label: label, target: targetQueue)
} else {
return DispatchQueue(label: label, qos: qos)
}
}
}
/// A tracing function that takes an SQL string.
+6
View File
@@ -85,6 +85,12 @@ public protocol Cursor : class {
}
extension Cursor {
/// Returns a Boolean value indicating whether the cursor contains
/// an element.
public func isEmpty() throws -> Bool {
return try next() == nil
}
/// Returns a Boolean value indicating whether the cursor contains an
/// element that satisfies the given predicate.
///
+81 -41
View File
@@ -25,9 +25,8 @@ extension Database {
}
/// 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
public func tableExists(_ name: String) throws -> Bool {
return try exists(type: .table, name: name)
}
/// Returns whether a table is an internal SQLite table.
@@ -53,15 +52,22 @@ extension Database {
}
/// 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
public func viewExists(_ name: String) throws -> Bool {
return try exists(type: .view, name: name)
}
/// 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
public func triggerExists(_ name: String) throws -> Bool {
return try exists(type: .trigger, name: name)
}
private func exists(type: SchemaObjectType, name: String) throws -> Bool {
// SQlite identifiers are case-insensitive, case-preserving:
// http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html
let name = name.lowercased()
return try schema()
.names(ofType: type)
.contains { $0.lowercased() == name }
}
/// The primary key for table named `tableName`.
@@ -164,14 +170,21 @@ extension Database {
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)
let indexes = try Row
.fetchAll(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))")
.map { row -> IndexInfo in
// [seq:0 name:"index" unique:0 origin:"c" partial:0]
let indexName: String = row[1]
let unique: Bool = row[2]
let columns = try Row
.fetchAll(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
.map { row -> (Int, String) in
// [seqno:0 cid:2 name:"column"]
(row[0] as Int, row[2] as String)
}
.sorted { $0.0 < $1.0 }
.map { $0.1 }
return IndexInfo(name: indexName, columns: columns, unique: unique)
}
if indexes.isEmpty {
@@ -249,27 +262,19 @@ extension Database {
/// Returns the actual name of the database table
func canonicalTableName(_ tableName: String) throws -> String {
if let canonicalTableName = schemaCache.canonicalTableName(tableName) {
return canonicalTableName
}
guard let canonicalTableName = try String.fetchOne(self, """
SELECT name FROM (
SELECT name, type FROM sqlite_master
UNION
SELECT name, type FROM sqlite_temp_master)
WHERE type = 'table' AND LOWER(name) = ?
""", arguments: [tableName.lowercased()])
else {
guard let name = try schema().canonicalName(tableName, ofType: .table) else {
throw DatabaseError(message: "no such table: \(tableName)")
}
schemaCache.set(canonicalTableName: canonicalTableName, forTable: tableName)
return canonicalTableName
return name
}
func schema() throws -> SchemaInfo {
return try SchemaInfo(self)
if let schemaInfo = schemaCache.schemaInfo {
return schemaInfo
}
let schemaInfo = try SchemaInfo(self)
schemaCache.schemaInfo = schemaInfo
return schemaInfo
}
}
@@ -563,23 +568,58 @@ public struct ForeignKeyInfo {
}
}
enum SchemaObjectType: String {
case index
case table
case trigger
case view
}
struct SchemaInfo: Equatable {
var objects: [SchemaKey: String?]
private var objects: Set<SchemaObject>
init(_ db: Database) throws {
objects = try Dictionary(uniqueKeysWithValues: Row
.fetchAll(db, "SELECT type, name, tbl_name, sql FROM sqlite_master")
.map { row in (SchemaKey(row: row), row["sql"]) })
objects = try Set(SchemaObject.fetchCursor(db, """
SELECT type, name, tbl_name, sql, 0 AS isTemporary FROM sqlite_master \
UNION \
SELECT type, name, tbl_name, sql, 1 FROM sqlite_temp_master
"""))
}
struct SchemaKey: Codable, Hashable, FetchableRecord {
/// All names for a given type
func names(ofType type: SchemaObjectType) -> Set<String> {
return objects.reduce(into: []) { (set, key) in
if key.type == type.rawValue {
set.insert(key.name)
}
}
}
/// Returns the canonical name of the object:
///
/// try db.execute("CREATE TABLE FooBar (...)")
/// try db.schema().canonicalName("foobar", ofType: .table) // "FooBar"
func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? {
let name = name.lowercased()
return objects.first { $0.name.lowercased() == name }?.name
}
private struct SchemaObject: Codable, Hashable, FetchableRecord {
var type: String
var name: String
var tbl_name: String?
// TODO: remove when Hashable conformance is synthesized
var sql: String?
var isTemporary: Bool
#if !swift(>=4.2)
var hashValue: Int {
return type.hashValue ^ name.hashValue ^ (tbl_name?.hashValue ?? 0)
var hash = type.hashValue
hash ^= name.hashValue
hash ^= (tbl_name?.hashValue ?? 0)
hash ^= (sql?.hashValue ?? 0)
hash ^= isTemporary.hashValue
return hash
}
#endif
}
}
+78
View File
@@ -223,3 +223,81 @@ extension Database {
publicStatementCache.remove(statement)
}
}
/// A thread-unsafe statement cache
struct StatementCache {
unowned let db: Database
private var selectStatements: [String: SelectStatement] = [:]
private var updateStatements: [String: UpdateStatement] = [:]
init(database: Database) {
self.db = database
}
mutating func selectStatement(_ sql: String) throws -> SelectStatement {
if let statement = selectStatements[sql] {
return statement
}
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
// > planner that the prepared statement will be retained for a long
// > time and probably reused many times.
//
// This looks like a perfect match for cached statements.
//
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
//
// TODO: use SQLITE_PREPARE_PERSISTENT if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let statement = try db.makeSelectStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement = try db.makeSelectStatement(sql)
#endif
selectStatements[sql] = statement
return statement
}
mutating func updateStatement(_ sql: String) throws -> UpdateStatement {
if let statement = updateStatements[sql] {
return statement
}
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
// > planner that the prepared statement will be retained for a long
// > time and probably reused many times.
//
// This looks like a perfect match for cached statements.
//
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
//
// TODO: use SQLITE_PREPARE_PERSISTENT if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let statement = try db.makeUpdateStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement = try db.makeUpdateStatement(sql)
#endif
updateStatements[sql] = statement
return statement
}
mutating func clear() {
updateStatements = [:]
selectStatements = [:]
}
mutating func remove(_ statement: SelectStatement) {
if let index = selectStatements.index(where: { $0.1 === statement }) {
selectStatements.remove(at: index)
}
}
mutating func remove(_ statement: UpdateStatement) {
if let index = updateStatements.index(where: { $0.1 === statement }) {
updateStatements.remove(at: index)
}
}
}
+133 -81
View File
@@ -202,6 +202,16 @@ extension Database {
var sqliteConnection: SQLiteConnection? = nil
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
guard code == SQLITE_OK else {
// https://www.sqlite.org/c3ref/open.html
// > Whether or not an error occurs when it is opened, resources
// > associated with the database connection handle should be
// > released by passing it to sqlite3_close() when it is no
// > longer required.
//
// https://www.sqlite.org/c3ref/close.html
// > Calling sqlite3_close() or sqlite3_close_v2() with a NULL
// > pointer argument is a harmless no-op.
sqlite3_close(sqliteConnection)
throw DatabaseError(resultCode: code)
}
if let sqliteConnection = sqliteConnection {
@@ -285,52 +295,55 @@ extension Database {
guard configuration.trace != nil else {
return
}
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0 http://www.sqlite.org/changes.html#version_3_14
// It is available from iOS 10.0 and OS X 10.12 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
guard let stmt = stmt else { return SQLITE_OK }
guard let expandedSQLCString = sqlite3_expanded_sql(OpaquePointer(stmt)) else { return SQLITE_OK }
let sql = String(cString: expandedSQLCString)
sqlite3_free(expandedSQLCString)
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
return SQLITE_OK
return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
}, dbPointer)
#elseif GRDBCIPHER
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
guard let sql = sql.map({ String(cString: $0) }) else { return }
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
}, dbPointer)
#elseif !os(Linux)
#elseif os(Linux)
setupTrace_v1()
#else
if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
guard let stmt = stmt else { return SQLITE_OK }
guard let expandedSQLCString = sqlite3_expanded_sql(OpaquePointer(stmt)) else { return SQLITE_OK }
let sql = String(cString: expandedSQLCString)
sqlite3_free(expandedSQLCString)
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
return SQLITE_OK
return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
}, dbPointer)
} else {
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
guard let sql = sql.map({ String(cString: $0) }) else { return }
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
}, dbPointer)
setupTrace_v1()
}
#else
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
guard let sql = sql.map({ String(cString: $0) }) else { return }
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
}, dbPointer)
#endif
}
// Precondition: configuration.trace != nil
private func setupTrace_v1() {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
guard let sql = sql.map({ String(cString: $0) }) else { return }
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
}, dbPointer)
}
// Precondition: configuration.trace != nil
private static func trace_v2(
_ mask: UInt32,
_ dbPointer: UnsafeMutableRawPointer?,
_ stmt: UnsafeMutableRawPointer?,
_ unexpandedSQL: UnsafeMutableRawPointer?,
_ sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
-> Int32
{
guard let stmt = stmt else { return SQLITE_OK }
guard let expandedSQLCString = sqlite3_expanded_sql(OpaquePointer(stmt)) else { return SQLITE_OK }
let sql = String(cString: expandedSQLCString)
sqlite3_free(expandedSQLCString)
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
return SQLITE_OK
}
private func setupForeignKeys() throws {
// Foreign keys are disabled by default with SQLite3
if configuration.foreignKeysEnabled {
@@ -400,41 +413,47 @@ extension Database {
}
private static func closeConnection(_ sqliteConnection: SQLiteConnection) {
// sqlite3_close_v2 was added in SQLite 3.7.14 http://www.sqlite.org/changes.html#version_3_7_14
// 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
close_v2(connection: sqliteConnection)
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
close_v2(connection: sqliteConnection)
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
} else {
// https://www.sqlite.org/c3ref/close.html
// > If the database connection is associated with unfinalized prepared
// > statements or unfinished sqlite3_backup objects then
// > sqlite3_close() will leave the database connection open and
// > return SQLITE_BUSY.
let code = sqlite3_close(sqliteConnection)
if code != SQLITE_OK, let log = logError {
// A rare situation where GRDB doesn't fatalError on
// unprocessed errors.
let message = String(cString: sqlite3_errmsg(sqliteConnection))
log(ResultCode(rawValue: code), "could not close database: \(message)")
if code == SQLITE_BUSY {
// Let the user know about unfinalized statements that did
// prevent the connection from closing properly.
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
while stmt != nil {
log(ResultCode(rawValue: code), "unfinalized statement: \(String(cString: sqlite3_sql(stmt)))")
stmt = sqlite3_next_stmt(sqliteConnection, stmt)
}
}
}
closeConnection_v1(sqliteConnection)
}
#endif
}
private static func closeConnection_v1(_ sqliteConnection: SQLiteConnection) {
// https://www.sqlite.org/c3ref/close.html
// > If the database connection is associated with unfinalized prepared
// > statements or unfinished sqlite3_backup objects then
// > sqlite3_close() will leave the database connection open and
// > return SQLITE_BUSY.
let code = sqlite3_close(sqliteConnection)
if code != SQLITE_OK, let log = logError {
// A rare situation where GRDB doesn't fatalError on
// unprocessed errors.
let message = String(cString: sqlite3_errmsg(sqliteConnection))
log(ResultCode(rawValue: code), "could not close database: \(message)")
if code == SQLITE_BUSY {
// Let the user know about unfinalized statements that did
// prevent the connection from closing properly.
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
while stmt != nil {
log(ResultCode(rawValue: code), "unfinalized statement: \(String(cString: sqlite3_sql(stmt)))")
stmt = sqlite3_next_stmt(sqliteConnection, stmt)
}
}
}
}
// sqlite3_close_v2 was added in SQLite 3.7.14 http://www.sqlite.org/changes.html#version_3_7_14
// 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
private static func close_v2(connection sqliteConnection: SQLiteConnection) {
private static func closeConnection_v2(
_ sqliteConnection: SQLiteConnection,
_ sqlite3_close_v2: @convention(c) (OpaquePointer?) -> Int32)
{
// https://www.sqlite.org/c3ref/close.html
// > If sqlite3_close_v2() is called with unfinalized prepared
// > statements and/or unfinished sqlite3_backups, then the database
@@ -449,24 +468,6 @@ extension Database {
log(ResultCode(rawValue: code), "could not close database: \(message)")
}
}
#else
@available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *)
private static func close_v2(connection sqliteConnection: SQLiteConnection) {
// https://www.sqlite.org/c3ref/close.html
// > If sqlite3_close_v2() is called with unfinalized prepared
// > statements and/or unfinished sqlite3_backups, then the database
// > connection becomes an unusable "zombie" which will automatically
// > be deallocated when the last prepared statement is finalized or the
// > last sqlite3_backup is finished.
let code = sqlite3_close_v2(sqliteConnection)
if code != SQLITE_OK, let log = logError {
// A rare situation where GRDB doesn't fatalError on
// unprocessed errors.
let message = String(cString: sqlite3_errmsg(sqliteConnection))
log(ResultCode(rawValue: code), "could not close database: \(message)")
}
}
#endif
}
extension Database {
@@ -548,8 +549,8 @@ extension Database {
// 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)
// Assume those pragmas never fail
try! execute("PRAGMA query_only = 1")
defer { try! execute("PRAGMA query_only = 0") }
try! internalCachedUpdateStatement("PRAGMA query_only = 1").execute()
defer { try! internalCachedUpdateStatement("PRAGMA query_only = 0").execute() }
return try block()
}
}
@@ -713,6 +714,56 @@ extension Database {
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
let kind = kind ?? configuration.defaultTransactionKind
try execute("BEGIN \(kind.rawValue) TRANSACTION")
assert(isInsideTransaction)
}
/// Begins a database transaction and take a snapshot of the last committed
/// database state.
func beginSnapshotIsolation() throws {
// https://www.sqlite.org/isolation.html
//
// > In WAL mode, SQLite exhibits "snapshot isolation". When a read
// > transaction starts, that reader continues to see an unchanging
// > "snapshot" of the database file as it existed at the moment in time
// > when the read transaction started. Any write transactions that
// > commit while the read transaction is active are still invisible to
// > the read transaction, because the reader is seeing a snapshot of
// > database file from a prior moment in time.
//
// That's exactly what we need. But what does "when read transaction
// starts" mean?
//
// http://www.sqlite.org/lang_transaction.html
//
// > Deferred [transaction] means that no locks are acquired on the
// > database until the database is first accessed. [...] Locks are not
// > acquired until the first read or write operation. [...] Because the
// > acquisition of locks is deferred until they are needed, it is
// > possible that another thread or process could create a separate
// > transaction and write to the database after the BEGIN on the
// > current thread has executed.
//
// Now that's precise enough: SQLite defers "snapshot isolation" until
// the first SELECT:
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
// UPDATE ... (1)
// Here the change (1) is visible
// SELECT ...
// UPDATE ... (2)
// Here the change (2) is not visible
//
// We thus have to perform a select that establishes the
// snapshot isolation before we release the writer queue:
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
// SELECT anything
// UPDATE ...
// Here the change is not visible by GRDB user
try beginTransaction(.deferred)
try internalCachedSelectStatement("SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
}
/// Rollbacks a database transaction.
@@ -820,6 +871,7 @@ extension Database {
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
}
// The schema of the destination database has changed:
dbDest.clearSchemaCache()
}
}
+14 -7
View File
@@ -32,17 +32,24 @@ public final class DatabaseCollation {
}
}
extension DatabaseCollation : Hashable {
extension DatabaseCollation: Hashable {
// 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.
#if swift(>=4.2)
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(0)
}
#else
/// :nodoc:
public var hashValue: Int {
// Collation equality is based on the sqlite3_strnicmp SQLite function.
// (see https://www.sqlite.org/c3ref/create_collation.html). Computing
// 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
}
#endif
/// Two collations are equal if they share the same name (case insensitive)
/// :nodoc:
+14 -6
View File
@@ -141,20 +141,28 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
// CustomStringConvertible
extension ResultCode {
/// :nodoc:
public var description: String {
var errorString: 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))))"
return 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))))"
return String(cString: sqlite3_errstr(rawValue))
} else {
return "\(rawValue)"
return nil
}
#endif
}
/// :nodoc:
public var description: String {
if let errorString = errorString {
return "\(rawValue) (\(errorString))"
} else {
return "\(rawValue)"
}
}
}
/// DatabaseError wraps an SQLite error.
@@ -199,7 +207,7 @@ public struct DatabaseError : Error, CustomStringConvertible, CustomNSError {
/// Creates a Database Error
public init(resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
self.extendedResultCode = resultCode
self.message = message
self.message = message ?? resultCode.errorString
self.sql = sql
self.arguments = arguments
}
+7 -1
View File
@@ -313,11 +313,17 @@ public final class DatabaseFunction: Hashable {
}
extension DatabaseFunction {
/// The hash value
#if swift(>=4.2)
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(identity)
}
#else
/// :nodoc:
public var hashValue: Int {
return identity.hashValue
}
#endif
/// Two functions are equal if they share the same name and arity.
/// :nodoc:
+138 -90
View File
@@ -1,4 +1,5 @@
import Foundation
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
@@ -16,6 +17,7 @@ public final class DatabasePool: DatabaseWriter {
private var functions = Set<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
private var tokenizerRegistrations: [(Database) -> Void] = []
var snapshotCount = ReadWriteBox(0)
@@ -50,7 +52,8 @@ public final class DatabasePool: DatabaseWriter {
path: path,
configuration: configuration,
schemaCache: SimpleDatabaseSchemaCache(),
label: (configuration.label ?? "GRDB.DatabasePool") + ".writer")
defaultLabel: "GRDB.DatabasePool",
purpose: "writer")
// Activate WAL Mode unless readonly
if !configuration.readonly {
@@ -87,7 +90,8 @@ public final class DatabasePool: DatabaseWriter {
path: path,
configuration: self.readerConfig,
schemaCache: SimpleDatabaseSchemaCache(),
label: (self.readerConfig.label ?? "GRDB.DatabasePool") + ".reader.\(readerCount)")
defaultLabel: "GRDB.DatabasePool",
purpose: "reader.\(readerCount)")
reader.sync { self.setupDatabase($0) }
return reader
})
@@ -104,12 +108,22 @@ public final class DatabasePool: DatabaseWriter {
#endif
private func setupDatabase(_ db: Database) {
for function in self.functions {
for function in functions {
db.add(function: function)
}
for collation in self.collations {
for collation in collations {
db.add(collation: collation)
}
for registration in tokenizerRegistrations {
registration(db)
}
}
/// Blocks the current thread until all database connections have
/// executed the *body* block.
fileprivate func forEachConnection(_ body: (Database) -> Void) {
writer.sync(body)
readerPool.forEach { $0.sync(body) }
}
}
@@ -147,11 +161,7 @@ extension DatabasePool {
///
/// See also setupMemoryManagement(application:)
public func releaseMemory() {
// TODO: test that this method blocks the current thread until all database accesses are completed.
writer.sync { $0.releaseMemory() }
readerPool.forEach { reader in
reader.sync { $0.releaseMemory() }
}
forEachConnection { $0.releaseMemory() }
readerPool.clear()
}
@@ -167,8 +177,13 @@ extension DatabasePool {
public func setupMemoryManagement(in application: UIApplication) {
self.application = application
let center = NotificationCenter.default
#if swift(>=4.2)
center.addObserver(self, selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
center.addObserver(self, selector: #selector(DatabasePool.applicationDidEnterBackground(_:)), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
#else
center.addObserver(self, selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
center.addObserver(self, selector: #selector(DatabasePool.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
#endif
}
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
@@ -176,10 +191,13 @@ extension DatabasePool {
return
}
var task: UIBackgroundTaskIdentifier! = nil
task = application.beginBackgroundTask(expirationHandler: nil)
if task == UIBackgroundTaskInvalid {
let task: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
#if swift(>=4.2)
let taskIsInvalid = task == UIBackgroundTaskIdentifier.invalid
#else
let taskIsInvalid = task == UIBackgroundTaskInvalid
#endif
if taskIsInvalid {
// Perform releaseMemory() synchronously.
releaseMemory()
} else {
@@ -341,6 +359,8 @@ extension DatabasePool : DatabaseReader {
}
}
/// This method is deprecated. Use concurrentRead instead.
///
/// Asynchronously executes a read-only block in a protected dispatch queue,
/// wrapped in a deferred transaction.
///
@@ -366,89 +386,112 @@ extension DatabasePool : DatabaseReader {
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
@available(*, deprecated, message: "Use concurrentRead instead")
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
// https://www.sqlite.org/isolation.html
//
// > In WAL mode, SQLite exhibits "snapshot isolation". When a read
// > transaction starts, that reader continues to see an unchanging
// > "snapshot" of the database file as it existed at the moment in time
// > when the read transaction started. Any write transactions that
// > commit while the read transaction is active are still invisible to
// > the read transaction, because the reader is seeing a snapshot of
// > database file from a prior moment in time.
//
// That's exactly what we need. But what does "when read transaction
// starts" mean?
//
// http://www.sqlite.org/lang_transaction.html
//
// > Deferred [transaction] means that no locks are acquired on the
// > database until the database is first accessed. [...] Locks are not
// > acquired until the first read or write operation. [...] Because the
// > acquisition of locks is deferred until they are needed, it is
// > possible that another thread or process could create a separate
// > transaction and write to the database after the BEGIN on the
// > current thread has executed.
//
// Now that's precise enough: SQLite defers "snapshot isolation" until
// the first SELECT:
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
// UPDATE ... (1)
// Here the change (1) is visible
// SELECT ...
// UPDATE ... (2)
// Here the change (2) is not visible
//
// The readFromCurrentState method says that no change should be visible
// at all. We thus have to perform a select that establishes the
// snapshot isolation before we release the writer queue:
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
// SELECT anything
// UPDATE ...
// Here the change is not visible by GRDB user
// 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. If this error is raised from a DatabasePool.write block, use DatabasePool.writeWithoutTransaction instead (and use transactions when needed).")
GRDBPrecondition(!db.isInsideTransaction, """
readFromCurrentState must not be called from inside a transaction. \
If this error is raised from a DatabasePool.write block, use \
DatabasePool.writeWithoutTransaction instead (and use \
transactions when needed).
""")
}
// The semaphore that blocks the writing dispatch queue until snapshot
// isolation has been established:
let semaphore = DispatchSemaphore(value: 0)
var readError: Error? = nil
try readerPool.get { reader in
var snapshotIsolationError: Error? = nil
let (reader, releaseReader) = try readerPool.get()
reader.async { db in
defer {
_ = try? db.commit() // Ignore commit error
releaseReader()
}
do {
try db.beginSnapshotIsolation()
} catch {
snapshotIsolationError = error
semaphore.signal() // Release the writer queue and rethrow error
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)
}
_ = semaphore.wait(timeout: .distantFuture)
if let error = snapshotIsolationError {
// TODO: write a test for this
throw error
}
}
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T> {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
GRDBPrecondition(!db.isInsideTransaction, """
concurrentRead must not be called from inside a transaction. \
If this error is raised from a DatabasePool.write block, use \
DatabasePool.writeWithoutTransaction instead (and use \
transactions when needed).
""")
}
// The semaphore that blocks the writing dispatch queue until snapshot
// isolation has been established:
let isolationSemaphore = DispatchSemaphore(value: 0)
// The semaphore that blocks until futureResult is defined:
let futureSemaphore = DispatchSemaphore(value: 0)
var futureResult: Result<T>? = nil
do {
let (reader, releaseReader) = try readerPool.get()
reader.async { db in
defer {
try? db.commit() // Ignore commit error
releaseReader()
}
do {
try db.beginTransaction(.deferred)
assert(db.isInsideTransaction)
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next()
try db.beginSnapshotIsolation()
} catch {
readError = error
semaphore.signal() // Release the writer queue and rethrow error
futureResult = .failure(error)
isolationSemaphore.signal()
futureSemaphore.signal()
return
}
semaphore.signal() // We can release the writer queue now that we are isolated for good
// Release the writer queue
isolationSemaphore.signal()
// Reset the schema cache before running user code in snapshot isolation
db.schemaCache = SimpleDatabaseSchemaCache()
block(db)
_ = try? db.commit() // Ignore commit error
// Fetch and release the future
futureResult = Result { try block(db) }
futureSemaphore.signal()
}
} catch {
return Future { throw error }
}
_ = semaphore.wait(timeout: .distantFuture)
if let readError = readError {
// TODO: write a test for this
throw readError
// Block the writer queue until snapshot isolation success or error
_ = isolationSemaphore.wait(timeout: .distantFuture)
return Future {
// Block the future until results are fetched
_ = futureSemaphore.wait(timeout: .distantFuture)
return try futureResult!.unwrap()
}
}
/// Returns a reader that can be used from the current dispatch queue,
/// if any.
private var currentReader: SerializedDatabase? {
@@ -593,19 +636,13 @@ extension DatabasePool : DatabaseReader {
/// }
public func add(function: DatabaseFunction) {
functions.update(with: function)
writer.sync { $0.add(function: function) }
readerPool.forEach { reader in
reader.sync { $0.add(function: function) }
}
forEachConnection { $0.add(function: function) }
}
/// Remove an SQL function.
public func remove(function: DatabaseFunction) {
functions.remove(function)
writer.sync { $0.remove(function: function) }
readerPool.forEach { reader in
reader.sync { $0.remove(function: function) }
}
forEachConnection { $0.remove(function: function) }
}
// MARK: - Collations
@@ -621,20 +658,30 @@ extension DatabasePool : DatabaseReader {
/// }
public func add(collation: DatabaseCollation) {
collations.update(with: collation)
writer.sync { $0.add(collation: collation) }
readerPool.forEach { reader in
reader.sync { $0.add(collation: collation) }
}
forEachConnection { $0.add(collation: collation) }
}
/// Remove a collation.
public func remove(collation: DatabaseCollation) {
collations.remove(collation)
writer.sync { $0.remove(collation: collation) }
readerPool.forEach { reader in
reader.sync { $0.remove(collation: collation) }
}
forEachConnection { $0.remove(collation: collation) }
}
// MARK: - Custom FTS5 Tokenizers
#if SQLITE_ENABLE_FTS5
/// Add a custom FTS5 tokenizer.
///
/// class MyTokenizer : FTS5CustomTokenizer { ... }
/// dbPool.add(tokenizer: MyTokenizer.self)
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
func registerTokenizer(db: Database) {
db.add(tokenizer: Tokenizer.self)
}
tokenizerRegistrations.append(registerTokenizer)
forEachConnection(registerTokenizer)
}
#endif
}
extension DatabasePool {
@@ -710,7 +757,8 @@ extension DatabasePool {
let snapshot = try DatabaseSnapshot(
path: path,
configuration: writer.configuration,
labelSuffix: ".snapshot.\(snapshotCount.increment())")
defaultLabel: "GRDB.DatabasePool",
purpose: "snapshot.\(snapshotCount.increment())")
snapshot.read { setupDatabase($0) }
return snapshot
}
+34 -13
View File
@@ -40,7 +40,7 @@ public final class DatabaseQueue: DatabaseWriter {
path: path,
configuration: configuration,
schemaCache: SimpleDatabaseSchemaCache(),
label: configuration.label ?? "GRDB.DatabaseQueue")
defaultLabel: "GRDB.DatabaseQueue")
}
/// Opens an in-memory SQLite database.
@@ -56,7 +56,7 @@ public final class DatabaseQueue: DatabaseWriter {
path: ":memory:",
configuration: configuration,
schemaCache: SimpleDatabaseSchemaCache(),
label: configuration.label ?? "GRDB.DatabaseQueue")
defaultLabel: "GRDB.DatabaseQueue")
}
#if os(iOS)
@@ -94,8 +94,13 @@ extension DatabaseQueue {
public func setupMemoryManagement(in application: UIApplication) {
self.application = application
let center = NotificationCenter.default
#if swift(>=4.2)
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidReceiveMemoryWarning(_:)), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
#else
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidReceiveMemoryWarning(_:)), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
#endif
}
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
@@ -103,10 +108,13 @@ extension DatabaseQueue {
return
}
var task: UIBackgroundTaskIdentifier! = nil
task = application.beginBackgroundTask(expirationHandler: nil)
if task == UIBackgroundTaskInvalid {
let task: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
#if swift(>=4.2)
let taskIsInvalid = task == UIBackgroundTaskIdentifier.invalid
#else
let taskIsInvalid = task == UIBackgroundTaskInvalid
#endif
if taskIsInvalid {
// Perform releaseMemory() synchronously.
releaseMemory()
} else {
@@ -191,10 +199,12 @@ extension DatabaseQueue {
/// concurrency practices.
///
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) rethrows -> T {
return try writer.reentrantSync(block)
}
/// This method is deprecated. Use concurrentRead instead.
///
/// Synchronously executes *block*.
///
/// This method must be called from the protected database dispatch queue,
@@ -203,10 +213,7 @@ extension DatabaseQueue {
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
/// SQLCipher), attempts to write in the database from this meethod throw a
/// DatabaseError of resultCode `SQLITE_READONLY`.
///
/// See `DatabaseWriter.readFromCurrentState`.
///
/// :nodoc:
@available(*, deprecated, message: "Use concurrentRead instead")
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
// Check that we're on the correct queue...
writer.execute { db in
@@ -216,6 +223,21 @@ extension DatabaseQueue {
}
}
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T> {
// DatabaseQueue can't perform parallel reads.
// Perform a blocking read instead.
return Future(Result {
// Check that we're on the writer queue...
try writer.execute { db in
// ... and that no transaction is opened.
GRDBPrecondition(!db.isInsideTransaction, "concurrentRead must not be called from inside a transaction.")
return try db.readOnly {
try block(db)
}
}
})
}
// MARK: - Writing in Database
/// Synchronously executes a block in a protected dispatch queue, wrapped
@@ -232,7 +254,7 @@ extension DatabaseQueue {
///
/// - parameter block: A block that executes SQL statements.
/// - throws: An eventual database error, or the error thrown by the block.
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
public func write<T>(_ block: (Database) throws -> T) throws -> T {
return try writer.sync { db in
var result: T? = nil
try db.inTransaction {
@@ -363,4 +385,3 @@ extension DatabaseQueue {
writer.sync { $0.remove(collation: collation) }
}
}
+38
View File
@@ -149,6 +149,27 @@ public protocol DatabaseReader : class {
/// Remove a collation.
func remove(collation: DatabaseCollation)
// MARK: - Value Observation
/// Starts a value observation.
///
/// You should use the `ValueObservation.start(in:onError:onChange:)`
/// method instead.
///
/// - parameter observation: the stared observation
/// - parameter onError: a closure that is provided by eventual errors that happen
/// during observation
/// - parameter onChange: a closure that is provided fresh values
/// - returns: a TransactionObserver
func add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
onError: ((Error) -> Void)?,
onChange: @escaping (Reducer.Value) -> Void)
throws -> TransactionObserver
/// Remove a transaction observer.
func remove(transactionObserver: TransactionObserver)
}
extension DatabaseReader {
@@ -228,4 +249,21 @@ public final class AnyDatabaseReader : DatabaseReader {
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
// MARK: - Value Observation
/// :nodoc:
public func add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
onError: ((Error) -> Void)?,
onChange: @escaping (Reducer.Value) -> Void)
throws -> TransactionObserver
{
return try base.add(observation: observation, onError: onError, onChange: onChange)
}
/// :nodoc:
public func remove(transactionObserver: TransactionObserver) {
base.remove(transactionObserver: transactionObserver)
}
}
+94 -28
View File
@@ -18,15 +18,15 @@
///
/// - `SelectStatement.databaseRegion`:
///
/// let statement = db.makeSelectStatement("SELECT name, score FROM player")
/// print(statement.databaseRegion)
/// // prints "player(name,score)"
/// let statement = db.makeSelectStatement("SELECT name, score FROM player")
/// print(statement.databaseRegion)
/// // prints "player(name,score)"
///
/// - `FetchRequest.databaseRegion(_:)`
///
/// let request = Player.filter(key: 1)
/// try print(request.databaseRegion(db))
/// // prints "player(*)[1]"
/// let request = Player.filter(key: 1)
/// try print(request.databaseRegion(db))
/// // prints "player(*)[1]"
///
/// Database regions returned by requests can be more precise than regions
/// returned by select statements. Especially, regions returned by statements
@@ -47,7 +47,10 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
/// Returns whether the region is empty.
public var isEmpty: Bool {
guard let tableRegions = tableRegions else { return false }
guard let tableRegions = tableRegions else {
// full database
return false
}
return tableRegions.isEmpty
}
@@ -122,7 +125,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
guard let otherTableRegions = other.tableRegions else { return .fullDatabase }
var tableRegionsUnion: [String: TableRegion] = [:]
let tableNames = Set(tableRegions.map { $0.key }).union(Set(otherTableRegions.map { $0.key }))
let tableNames = Set(tableRegions.keys).union(Set(otherTableRegions.keys))
for table in tableNames {
let tableRegion = tableRegions[table]
let otherTableRegion = otherTableRegions[table]
@@ -145,6 +148,13 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
public mutating func formUnion(_ other: DatabaseRegion) {
self = union(other)
}
func ignoring(_ tables: Set<String>) -> DatabaseRegion {
guard tables.isEmpty == false else { return self }
guard let tableRegions = tableRegions else { return .fullDatabase }
let filteredRegions = tableRegions.filter { tables.contains($0.key) == false }
return DatabaseRegion(tableRegions: filteredRegions)
}
}
extension DatabaseRegion {
@@ -154,7 +164,7 @@ extension DatabaseRegion {
/// Returns whether the content in the region would be impacted if the
/// database were modified by an event of this kind.
public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool {
return !intersection(eventKind.modifiedRegion).isEmpty
return intersection(eventKind.modifiedRegion).isEmpty == false
}
/// Returns whether the content in the region is impacted by this event.
@@ -164,31 +174,27 @@ extension DatabaseRegion {
/// region.isModified(byEventsOfKind:)
public func isModified(by event: DatabaseEvent) -> Bool {
guard let tableRegions = tableRegions else {
// Full database: all changes are impactful
return true
}
switch tableRegions.count {
case 1:
// The precondition applies here:
if tableRegions.count == 1 {
// Fast path when the region contains a single table.
//
// The region contains a single table. Due to the
// filtering of events performed in observes(eventsOfKind:), the
// event argument is guaranteed to be about the fetched table.
// We thus only have to check for rowIds.
assert(event.tableName == tableRegions[tableRegions.startIndex].key) // sanity check
guard let rowIds = tableRegions[tableRegions.startIndex].value.rowIds else {
return true
}
return rowIds.contains(event.rowID)
default:
// We can apply the precondition: due to the filtering of events
// performed in observes(eventsOfKind:), the event argument is
// guaranteed to be about the fetched table. We thus only have to
// check for rowIds.
assert(event.tableName == tableRegions[tableRegions.startIndex].key) // sanity check in debug mode
let tableRegion = tableRegions[tableRegions.startIndex].value
return tableRegion.contains(rowID: event.rowID)
} else {
// Slow path when several tables are observed.
guard let tableRegion = tableRegions[event.tableName] else {
// Shouldn't happen if the precondition is met.
fatalError("precondition failure: event was not filtered out in observes(eventsOfKind:) by region.isModified(byEventsOfKind:)")
}
guard let rowIds = tableRegion.rowIds else {
return true
}
return rowIds.contains(event.rowID)
return tableRegion.contains(rowID: event.rowID)
}
}
}
@@ -201,8 +207,8 @@ extension DatabaseRegion {
case (nil, nil):
return true
case (let ltableRegions?, let rtableRegions?):
let ltableNames = Set(ltableRegions.map { $0.key })
let rtableNames = Set(rtableRegions.map { $0.key })
let ltableNames = Set(ltableRegions.keys)
let rtableNames = Set(rtableRegions.keys)
guard ltableNames == rtableNames else {
return false
}
@@ -295,4 +301,64 @@ private struct TableRegion: Equatable {
return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion)
}
@inline(__always)
func contains(rowID: Int64) -> Bool {
guard let rowIds = rowIds else {
return true
}
return rowIds.contains(rowID)
}
}
// MARK: - DatabaseRegionConvertible
public protocol DatabaseRegionConvertible {
/// Returns a database region.
///
/// - parameter db: A database connection.
func databaseRegion(_ db: Database) throws -> DatabaseRegion
}
extension DatabaseRegion: DatabaseRegionConvertible {
/// :nodoc:
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
return self
}
}
/// A type-erased DatabaseRegionConvertible
public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
let _region: (Database) throws -> DatabaseRegion
public init(_ region: @escaping (Database) throws -> DatabaseRegion) {
_region = region
}
public init(_ region: DatabaseRegionConvertible) {
_region = { try region.databaseRegion($0) }
}
/// :nodoc:
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
return try _region(db)
}
}
// MARK: - Utils
extension DatabaseRegion {
static func union(_ regions: DatabaseRegion...) -> DatabaseRegion {
return regions.reduce(into: DatabaseRegion()) { union, region in
union.formUnion(region)
}
}
static func union(_ regions: [DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion {
return { db in
try regions.reduce(into: DatabaseRegion()) { union, region in
try union.formUnion(region.databaseRegion(db))
}
}
}
}
+133
View File
@@ -0,0 +1,133 @@
/// DatabaseRegionObservation tracks changes in the results of database
/// requests, and notifies each database transaction whenever the
/// database changes.
///
/// For example:
///
/// let observation = DatabaseRegionObservation(tracking: Player.all)
/// let observer = try observation.start(in: dbQueue) { db: Database in
/// print("Players have changed.")
/// }
public struct DatabaseRegionObservation {
/// The extent of the database observation. The default is
/// `.observerLifetime`: the observation lasts until the
/// observer returned by the `start(in:onChange:)` method
/// is deallocated.
public var extent = Database.TransactionObservationExtent.observerLifetime
/// A closure that is evaluated when the observation starts, and returns
/// the observed database region.
var observedRegion: (Database) throws -> DatabaseRegion
// Not public because we foster DatabaseRegionConvertible.
init(tracking region: @escaping (Database) throws -> DatabaseRegion) {
self.observedRegion = { db in
// Remove views from the observed region.
//
// We can do it because we are only interested in modifications in
// actual tables. And we want to do it because we have a fast path
// for simple regions that span a single table.
let views = try db.schema().names(ofType: .view)
return try region(db).ignoring(views)
}
}
/// Creates a DatabaseRegionObservation which observes *regions*, and
/// notifies whenever one of the observed regions is modified by a
/// database transaction.
///
/// For example, this sample code counts the number of a times the player
/// table is modified:
///
/// let observation = DatabaseRegionObservation(tracking: Player.all())
///
/// var count = 0
/// let observer = observation.start(in: dbQueue) { _ in
/// count += 1
/// print("Players have been modified \(count) times.")
/// }
///
/// The observation lasts until the observer returned by `start` is
/// deallocated. See the `extent` property for more information.
///
/// - parameter regions: A list of observed regions.
public init(tracking regions: DatabaseRegionConvertible...) {
self.init(tracking: regions)
}
/// Creates a DatabaseRegionObservation which observes *regions*, and
/// notifies whenever one of the observed regions is modified by a
/// database transaction.
///
/// For example, this sample code counts the number of a times the player
/// table is modified:
///
/// let observation = DatabaseRegionObservation(tracking: [Player.all()])
///
/// var count = 0
/// let observer = observation.start(in: dbQueue) { _ in
/// count += 1
/// print("Players have been modified \(count) times.")
/// }
///
/// The observation lasts until the observer returned by `start` is
/// deallocated. See the `extent` property for more information.
///
/// - parameter regions: A list of observed regions.
public init(tracking regions: [DatabaseRegionConvertible]) {
self.init(tracking: DatabaseRegion.union(regions))
}
}
extension DatabaseRegionObservation {
/// Starts the observation in the provided database writer (such as
/// a database queue or database pool), and returns a transaction observer.
///
/// - parameter reader: A DatabaseWriter.
/// - parameter onChange: A closure that is provided a database connection
/// with write access each time the observed region has been modified.
/// - returns: a TransactionObserver
public func start(in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) throws -> TransactionObserver {
// Use unsafeReentrantWrite so that observation can start from any
// dispatch queue.
return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in
let region = try observedRegion(db)
let observer = DatabaseRegionObserver(region: region, onChange: onChange)
db.add(transactionObserver: observer, extent: extent)
return observer
}
}
}
private class DatabaseRegionObserver: TransactionObserver {
let region: DatabaseRegion
let onChange: (Database) -> Void
var isChanged = false
init(region: DatabaseRegion, onChange: @escaping (Database) -> Void) {
self.region = region
self.onChange = onChange
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return region.isModified(byEventsOfKind: eventKind)
}
func databaseDidChange(with event: DatabaseEvent) {
if region.isModified(by: event) {
isChanged = true
stopObservingDatabaseChangesUntilNextTransaction()
}
}
func databaseDidCommit(_ db: Database) {
guard isChanged else { return }
isChanged = false
onChange(db)
}
func databaseDidRollback(_ db: Database) {
isChanged = false
}
}
+8 -15
View File
@@ -2,9 +2,8 @@
protocol DatabaseSchemaCache {
mutating func clear()
func canonicalTableName(_ table: String) -> String?
mutating func set(canonicalTableName: String, forTable table: String)
var schemaInfo: SchemaInfo? { get set }
func primaryKey(_ table: String) -> PrimaryKeyInfo?
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String)
@@ -20,26 +19,18 @@ protocol DatabaseSchemaCache {
/// A thread-unsafe database schema cache
struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
private var canonicalTableNames: [String: String] = [:]
var schemaInfo: SchemaInfo?
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
private var columns: [String: [ColumnInfo]] = [:]
private var indexes: [String: [IndexInfo]] = [:]
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
mutating func clear() {
canonicalTableNames = [:]
primaryKeys = [:]
columns = [:]
indexes = [:]
foreignKeys = [:]
}
func canonicalTableName(_ table: String) -> String? {
return canonicalTableNames[table]
}
mutating func set(canonicalTableName: String, forTable table: String) {
canonicalTableNames[table] = table
schemaInfo = nil
}
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
@@ -79,8 +70,10 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
struct EmptyDatabaseSchemaCache: DatabaseSchemaCache {
func clear() { }
func canonicalTableName(_ table: String) -> String? { return nil }
func set(canonicalTableName: String, forTable table: String) { }
var schemaInfo: SchemaInfo? {
get { return nil }
set { }
}
func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil }
func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
+67 -32
View File
@@ -1,3 +1,5 @@
import Dispatch
/// A DatabaseSnapshot sees an unchanging database content, as it existed at the
/// moment it was created.
///
@@ -12,7 +14,7 @@ public class DatabaseSnapshot : DatabaseReader {
return serializedDatabase.configuration
}
init(path: String, configuration: Configuration = Configuration(), labelSuffix: String) throws {
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
var configuration = configuration
configuration.readonly = true
configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction
@@ -21,7 +23,8 @@ public class DatabaseSnapshot : DatabaseReader {
path: path,
configuration: configuration,
schemaCache: SimpleDatabaseSchemaCache(),
label: (configuration.label ?? "GRDB.DatabasePool") + labelSuffix)
defaultLabel: defaultLabel,
purpose: purpose)
try serializedDatabase.sync { db in
// Assert WAL mode
@@ -29,13 +32,7 @@ public class DatabaseSnapshot : DatabaseReader {
guard journalMode == "wal" else {
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
}
// Establish snapshot isolation (see deinit)
try db.beginTransaction(.deferred)
// Take snapshot
// See DatabasePool.readFromCurrentState for a complete discussion
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next()
try db.beginSnapshotIsolation()
}
}
@@ -81,45 +78,83 @@ extension DatabaseSnapshot {
// MARK: - Functions
/// Add or redefine an SQL function.
///
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
/// return nil
/// }
/// return int + 1
/// }
/// snapshot.add(function: fn)
/// try snapshot.read { db in
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
/// }
public func add(function: DatabaseFunction) {
serializedDatabase.sync { $0.add(function: function) }
}
/// Remove an SQL function.
public func remove(function: DatabaseFunction) {
serializedDatabase.sync { $0.remove(function: function) }
}
// MARK: - Collations
/// Add or redefine a collation.
///
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// snapshot.add(collation: collation)
/// let files = try snapshot.read { db in
/// try File.fetchAll(db, "SELECT * FROM file ORDER BY name COLLATE localized_standard")
/// }
public func add(collation: DatabaseCollation) {
serializedDatabase.sync { $0.add(collation: collation) }
}
/// Remove a collation.
public func remove(collation: DatabaseCollation) {
serializedDatabase.sync { $0.remove(collation: collation) }
}
// MARK: - Value Observation
public func add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
onError: ((Error) -> Void)?,
onChange: @escaping (Reducer.Value) -> Void)
throws -> TransactionObserver
{
// Deal with initial value
switch observation.scheduling {
case .mainQueue:
if let value = try unsafeReentrantRead(observation.initialValue) {
if DispatchQueue.isMain {
onChange(value)
} else {
DispatchQueue.main.async {
onChange(value)
}
}
}
case let .onQueue(queue, startImmediately: startImmediately):
if startImmediately {
if let value = try unsafeReentrantRead(observation.initialValue) {
queue.async {
onChange(value)
}
}
}
case let .unsafe(startImmediately: startImmediately):
if startImmediately {
if let value = try unsafeReentrantRead(observation.initialValue) {
onChange(value)
}
}
}
// Return a dummy observer, because snapshots never change
return SnapshotValueObserver()
}
public func remove(transactionObserver: TransactionObserver) {
// Can't remove an observer which could not be added :-)
}
}
extension ValueObservation where Reducer: ValueReducer {
/// Helper method for DatabaseSnapshot.add(observation:onError:onChange:)
fileprivate func initialValue(_ db: Database) throws -> Reducer.Value? {
var reducer = try makeReducer(db)
let fetched = try reducer.fetch(db)
return reducer.value(fetched)
}
}
/// An observer that does nothing, support for
/// `DatabaseSnapshot.add(observation:onError:onChange:)`.
private class SnapshotValueObserver: TransactionObserver {
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false }
func databaseDidChange(with event: DatabaseEvent) { }
func databaseDidCommit(_ db: Database) { }
func databaseDidRollback(_ db: Database) { }
}
+29 -38
View File
@@ -121,18 +121,18 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
/// Returns a DatabaseValue initialized from a raw SQLite statement pointer.
init(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, Int32(index)) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
storage = .null
case SQLITE_INTEGER:
storage = .int64(sqlite3_column_int64(sqliteStatement, Int32(index)))
storage = .int64(sqlite3_column_int64(sqliteStatement, index))
case SQLITE_FLOAT:
storage = .double(sqlite3_column_double(sqliteStatement, Int32(index)))
storage = .double(sqlite3_column_double(sqliteStatement, index))
case SQLITE_TEXT:
storage = .string(String(cString: sqlite3_column_text(sqliteStatement, Int32(index))))
storage = .string(String(cString: sqlite3_column_text(sqliteStatement, index)))
case SQLITE_BLOB:
if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) {
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
} else {
storage = .blob(Data())
@@ -149,7 +149,24 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
// Hashable
extension DatabaseValue {
/// The hash value
#if swift(>=4.2)
/// :nodoc:
public func hash(into hasher: inout Hasher) {
switch storage {
case .null:
hasher.combine(0)
case .int64(let int64):
// 1 == 1.0, hence 1 and 1.0 must have the same hash:
hasher.combine(Double(int64))
case .double(let double):
hasher.combine(double)
case .string(let string):
hasher.combine(string)
case .blob(let data):
hasher.combine(data)
}
}
#else
/// :nodoc:
public var hashValue: Int {
switch storage {
@@ -166,6 +183,7 @@ extension DatabaseValue {
return data.hashValue
}
}
#endif
/// Returns whether two DatabaseValues are equal.
///
@@ -207,6 +225,7 @@ extension DatabaseValue {
// MARK: - Lossless conversions
extension DatabaseValue {
// TODO: deprecate and rename to DatabaseValue.decode(_:sql:arguments:)
/// Converts the database value to the type T.
///
/// let dbValue = "foo".databaseValue
@@ -226,20 +245,10 @@ extension DatabaseValue {
/// - arguments: Optional statement arguments that enhances the eventual
/// conversion error
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T where T : DatabaseValueConvertible {
if let value = T.fromDatabaseValue(self) {
return value
}
// Failed conversion: this is data loss, a programmer error.
var error = "could not convert database value \(self) to \(T.self)"
if let sql = sql {
error += " with statement `\(sql)`"
}
if let arguments = arguments, !arguments.isEmpty {
error += " arguments \(arguments)"
}
fatalError(error)
return T.decode(from: self, conversionContext: sql.map { ValueConversionContext(sql: $0, arguments: arguments) })
}
// TODO: deprecate and rename to DatabaseValue.decodeIfPresent(_:sql:arguments:)
/// Converts the database value to the type Optional<T>.
///
/// let dbValue = "foo".databaseValue
@@ -260,25 +269,7 @@ extension DatabaseValue {
/// - arguments: Optional statement arguments that enhances the eventual
/// conversion error
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T? where T : DatabaseValueConvertible {
// Use fromDatabaseValue first: this allows DatabaseValue to convert NULL to .null.
if let value = T.fromDatabaseValue(self) {
return value
}
if isNull {
// Failed conversion from null: ok
return nil
} else {
// Failed conversion from a non-null database value: this is data
// loss, a programmer error.
var error = "could not convert database value \(self) to \(T.self)"
if let sql = sql {
error += " with statement `\(sql)`"
}
if let arguments = arguments, !arguments.isEmpty {
error += " arguments \(arguments)"
}
fatalError(error)
}
return T.decodeIfPresent(from: self, conversionContext: sql.map { ValueConversionContext(sql: $0, arguments: arguments) })
}
}
+227
View File
@@ -0,0 +1,227 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - Conversion Context and Errors
/// A type that helps the user understanding value conversion errors
struct ValueConversionContext {
private enum Column {
case columnIndex(Int)
case columnName(String)
}
var row: Row?
var sql: String?
var arguments: StatementArguments?
private var column: Column?
func atColumn(_ columnIndex: Int) -> ValueConversionContext {
var result = self
result.column = .columnIndex(columnIndex)
return result
}
func atColumn(_ columnName: String) -> ValueConversionContext {
var result = self
result.column = .columnName(columnName)
return result
}
var columnIndex: Int? {
guard let column = column else { return nil }
switch column {
case .columnIndex(let index):
return index
case .columnName(let name):
return row?.index(ofColumn: name)
}
}
var columnName: String? {
guard let column = column else { return nil }
switch column {
case .columnIndex(let index):
guard let row = row else { return nil }
return Array(row.columnNames)[index]
case .columnName(let name):
return name
}
}
}
extension ValueConversionContext {
init(_ statement: SelectStatement) {
self.init(
row: Row(statement: statement).copy(),
sql: statement.sql,
arguments: statement.arguments,
column: nil)
}
init(_ row: Row) {
if let statement = row.statement {
self.init(
row: row.copy(),
sql: statement.sql,
arguments: statement.arguments,
column: nil)
} else if let sqliteStatement = row.sqliteStatement {
let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: statementSeparatorCharacterSet)
self.init(
row: row.copy(),
sql: sql,
arguments: nil,
column: nil)
} else {
self.init(
row: row.copy(),
sql: nil,
arguments: nil,
column: nil)
}
}
init(sql: String, arguments: StatementArguments?) {
self.init(
row: nil,
sql: sql,
arguments: arguments,
column: nil)
}
}
/// The canonical conversion error message
///
/// - parameter dbValue: nil means "missing column"
func conversionErrorMessage<T>(to: T.Type, from dbValue: DatabaseValue?, conversionContext: ValueConversionContext?) -> String {
var message: String
var extras: [String] = []
if let dbValue = dbValue {
message = "could not convert database value \(dbValue) to \(T.self)"
if let columnName = conversionContext?.columnName {
extras.append("column: `\(columnName)`")
}
if let columnIndex = conversionContext?.columnIndex {
extras.append("column index: \(columnIndex)")
}
} else {
message = "could not read \(T.self) from missing column"
if let columnName = conversionContext?.columnName {
message += " `\(columnName)`"
}
}
if let row = conversionContext?.row {
extras.append("row: \(row)")
}
if let sql = conversionContext?.sql {
extras.append("sql: `\(sql)`")
if let arguments = conversionContext?.arguments, arguments.isEmpty == false {
extras.append("arguments: \(arguments)")
}
}
if extras.isEmpty == false {
message += " (" + extras.joined(separator: ", ") + ")"
}
return message
}
/// The canonical conversion fatal error
///
/// - parameter dbValue: nil means "missing column", for consistency with (row["missing"] as DatabaseValue? == nil)
func fatalConversionError<T>(to: T.Type, from dbValue: DatabaseValue?, conversionContext: ValueConversionContext?, file: StaticString = #file, line: UInt = #line) -> Never {
fatalError(conversionErrorMessage(to: T.self, from: dbValue, conversionContext: conversionContext), file: file, line: line)
}
func fatalConversionError<T>(to: T.Type, sqliteStatement: SQLiteStatement, index: Int32) -> Never {
let row = Row(sqliteStatement: sqliteStatement)
fatalConversionError(
to: T.self,
from: DatabaseValue(sqliteStatement: sqliteStatement, index: index),
conversionContext: ValueConversionContext(row).atColumn(Int(index)))
}
// MARK: - DatabaseValueConvertible
/// Lossless conversions from database values and rows
extension DatabaseValueConvertible {
@inline(__always)
static func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Self {
if let value = fromDatabaseValue(dbValue) {
return value
} else {
fatalConversionError(to: Self.self, from: dbValue, conversionContext: conversionContext())
}
}
@inline(__always)
static func decode(from row: Row, atUncheckedIndex index: Int) -> Self {
return decode(
from: row.impl.databaseValue(atUncheckedIndex: index),
conversionContext: ValueConversionContext(row).atColumn(index))
}
@inline(__always)
static func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Self? {
// Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null.
if let value = fromDatabaseValue(dbValue) {
return value
} else if dbValue.isNull {
return nil
} else {
fatalConversionError(to: Self.self, from: dbValue, conversionContext: conversionContext())
}
}
@inline(__always)
static func decodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
return decodeIfPresent(
from: row.impl.databaseValue(atUncheckedIndex: index),
conversionContext: ValueConversionContext(row).atColumn(index))
}
}
// MARK: - DatabaseValueConvertible & StatementColumnConvertible
/// Lossless conversions from database values and rows
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
@inline(__always)
static func fastDecode(from sqliteStatement: SQLiteStatement, index: Int32) -> Self {
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
fatalConversionError(
to: Self.self,
from: .null,
conversionContext: ValueConversionContext(Row(sqliteStatement: sqliteStatement)).atColumn(Int(index)))
}
return self.init(sqliteStatement: sqliteStatement, index: index)
}
@inline(__always)
static func fastDecode(from row: Row, atUncheckedIndex index: Int) -> Self {
if let sqliteStatement = row.sqliteStatement {
return fastDecode(from: sqliteStatement, index: Int32(index))
}
return row.impl.fastDecode(Self.self, atUncheckedIndex: index)
}
@inline(__always)
static func fastDecodeIfPresent(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? {
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
return nil
}
return self.init(sqliteStatement: sqliteStatement, index: index)
}
@inline(__always)
static func fastDecodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
if let sqliteStatement = row.sqliteStatement {
return fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index))
}
return row.impl.fastDecodeIfPresent(Self.self, atUncheckedIndex: index)
}
}
+52 -12
View File
@@ -55,25 +55,45 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
// We'll read from leftmost column at index 0, unless adapter mangles columns
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
if let adapter = adapter {
// adapter may redefine the index of the leftmost column
self.columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
} else {
self.columnIndex = 0
}
statement.reset(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? statement.reset()
}
/// :nodoc:
public func next() throws -> Value? {
if done { return nil }
if done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
}
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
return dbValue.losslessConvert() as Value
return Value.decode(
from: dbValue,
conversionContext: ValueConversionContext(statement).atColumn(Int(columnIndex)))
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
throw DatabaseError(
resultCode: code,
message: statement.database.lastErrorMessage,
sql: statement.sql,
arguments: statement.arguments)
}
}
}
@@ -95,25 +115,45 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
// We'll read from leftmost column at index 0, unless adapter mangles columns
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
if let adapter = adapter {
// adapter may redefine the index of the leftmost column
self.columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
} else {
self.columnIndex = 0
}
statement.reset(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? statement.reset()
}
/// :nodoc:
public func next() throws -> Value?? {
if done { return nil }
if done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
}
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
return dbValue.losslessConvert() as Value?
return Value.decodeIfPresent(
from: dbValue,
conversionContext: ValueConversionContext(statement).atColumn(Int(columnIndex)))
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
throw DatabaseError(
resultCode: code,
message: statement.database.lastErrorMessage,
sql: statement.sql,
arguments: statement.arguments)
}
}
}
+181 -2
View File
@@ -1,3 +1,5 @@
import Dispatch
/// The protocol for all types that can update a database.
///
/// It is adopted by DatabaseQueue and DatabasePool.
@@ -60,6 +62,8 @@ public protocol DatabaseWriter : DatabaseReader {
// MARK: - Reading from Database
/// This method is deprecated. Use concurrentRead instead.
///
/// Synchronously or asynchronously executes a read-only block that takes a
/// database connection.
///
@@ -72,7 +76,7 @@ public protocol DatabaseWriter : DatabaseReader {
///
/// For example:
///
/// try writer.write { db in
/// try writer.writeWithoutTransaction { db in
/// try db.execute("DELETE FROM player")
/// try writer.readFromCurrentState { db in
/// // Guaranteed to be zero
@@ -80,7 +84,42 @@ public protocol DatabaseWriter : DatabaseReader {
/// }
/// try db.execute("INSERT INTO player ...")
/// }
@available(*, deprecated, message: "Use concurrentRead instead")
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
/// Concurrently executes a read-only block that takes a
/// database connection.
///
/// 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 last
/// committed state at the moment this method is called. Eventual concurrent
/// database updates are *not visible* inside the block.
///
/// This method returns as soon as the isolation guarantees described above
/// are established. To access the fetched results, you call the wait()
/// method of the returned future, on any dispatch queue.
///
/// In the example below, the number of players is fetched concurrently with
/// the player insertion. Yet the future is guaranteed to return zero:
///
/// try writer.writeWithoutTransaction { db in
/// // Delete all players
/// try Player.deleteAll()
///
/// // Count players concurrently
/// let future = writer.concurrentRead { db in
/// return try Player.fetchCount()
/// }
///
/// // Insert a player
/// try Player(...).insert(db)
///
/// // Guaranteed to be zero
/// let count = try future.wait()
/// }
func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T>
}
extension DatabaseWriter {
@@ -90,6 +129,8 @@ extension DatabaseWriter {
/// Add a transaction observer, so that it gets notified of
/// database changes.
///
/// To remove the observer, use `DatabaseReader.remove(transactionObserver:)`.
///
/// - parameter transactionObserver: A transaction observer.
/// - parameter extent: The duration of the observation. The default is
/// the observer lifetime (observation lasts until observer
@@ -98,7 +139,8 @@ extension DatabaseWriter {
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
}
/// Remove a transaction observer.
/// Default implementation for the DatabaseReader requirement.
/// :nodoc:
public func remove(transactionObserver: TransactionObserver) {
writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) }
}
@@ -157,6 +199,137 @@ extension DatabaseWriter {
public func vacuum() throws {
try writeWithoutTransaction { try $0.execute("VACUUM") }
}
// MARK: - Value Observation
/// Default implementation for the DatabaseReader requirement.
/// :nodoc:
public func add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
onError: ((Error) -> Void)?,
onChange: @escaping (Reducer.Value) -> Void)
throws -> TransactionObserver
{
let calledOnMainQueue = DispatchQueue.isMain
var startValue: Reducer.Value? = nil
defer {
if let startValue = startValue {
onChange(startValue)
}
}
// Use unsafeReentrantWrite so that observation can start from any
// dispatch queue.
return try unsafeReentrantWrite { db in
// Create the reducer
var reducer = try observation.makeReducer(db)
// Take care of initial value. Make sure it is dispatched before
// any future transaction can trigger a change.
switch observation.scheduling {
case .mainQueue:
if let value = try reducer.initialValue(db, requiresWriteAccess: observation.requiresWriteAccess) {
if calledOnMainQueue {
startValue = value
} else {
DispatchQueue.main.async { onChange(value) }
}
}
case let .onQueue(queue, startImmediately: startImmediately):
if startImmediately {
if let value = try reducer.initialValue(db, requiresWriteAccess: observation.requiresWriteAccess) {
queue.async { onChange(value) }
}
}
case let .unsafe(startImmediately: startImmediately):
if startImmediately {
startValue = try reducer.initialValue(db, requiresWriteAccess: observation.requiresWriteAccess)
}
}
// Start observing the database
let valueObserver = try ValueObserver(
region: observation.observedRegion(db),
reducer: reducer,
configuration: db.configuration,
fetch: observation.fetchAfterChange(in: self),
notificationQueue: observation.notificationQueue,
onError: onError,
onChange: onChange)
db.add(transactionObserver: valueObserver, extent: observation.extent)
return valueObserver
}
}
}
extension ValueReducer {
/// Helper method for DatabaseWriter.add(observation:onError:onChange:)
fileprivate mutating func initialValue(_ db: Database, requiresWriteAccess: Bool) throws -> Value? {
if requiresWriteAccess {
var fetchedValue: Fetched!
try db.inSavepoint {
fetchedValue = try fetch(db)
return .commit
}
return value(fetchedValue)
} else {
return try value(db.readOnly { try fetch(db) })
}
}
}
extension ValueObservation where Reducer: ValueReducer {
/// Helper method for DatabaseWriter.add(observation:onError:onChange:)
fileprivate func fetchAfterChange(in writer: DatabaseWriter) -> (Database, Reducer) -> Future<Reducer.Fetched> {
// The technique to return a future value after database has changed
// depends on the requiresWriteAccess flag:
if requiresWriteAccess {
// Synchronous fetch
return { (db, reducer) in
Future(Result {
var fetchedValue: Reducer.Fetched!
try db.inTransaction {
fetchedValue = try reducer.fetch(db)
return .commit
}
return fetchedValue
})
}
} else {
// Concurrent fetch
return { [unowned writer] (_, reducer) in
writer.concurrentRead(reducer.fetch)
}
}
}
}
/// A future value.
public class Future<Value> {
private var consumed = false
private let _wait: () throws -> Value
init(_ wait: @escaping () throws -> Value) {
_wait = wait
}
init(_ result: Result<Value>) {
_wait = { try result.unwrap() }
}
/// Blocks the current thread until the value is available, and returns it.
///
/// It is a programmer error to call this method several times.
///
/// - throws: Any error that prevented the value from becoming available.
public func wait() throws -> Value {
// Not thread-safe and quick and dirty.
// Goal is that users learn not to call this method twice.
GRDBPrecondition(consumed == false, "Future.wait() must be called only once")
consumed = true
return try _wait()
}
}
/// A type-erased DatabaseWriter
@@ -189,9 +362,15 @@ public final class AnyDatabaseWriter : DatabaseWriter {
}
/// :nodoc:
@available(*, deprecated, message: "Use concurrentRead instead")
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
try base.readFromCurrentState(block)
}
/// :nodoc:
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T> {
return base.concurrentRead(block)
}
// MARK: - Writing in Database
+1 -6
View File
@@ -8,7 +8,7 @@
/// try request.fetchCursor(db) // Cursor of Player
/// try request.fetchAll(db) // [Player]
/// try request.fetchOne(db) // Player?
public protocol FetchRequest {
public protocol FetchRequest: DatabaseRegionConvertible {
/// The type that tells how fetched database rows should be interpreted.
associatedtype RowDecoder
@@ -30,11 +30,6 @@ public protocol FetchRequest {
///
/// - parameter db: A database connection.
func fetchCount(_ db: Database) throws -> Int
/// Returns the database region that the request looks into.
///
/// - parameter db: A database connection.
func databaseRegion(_ db: Database) throws -> DatabaseRegion
}
extension FetchRequest {
+170 -89
View File
@@ -7,6 +7,8 @@ import Foundation
/// A database row.
public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible, CustomDebugStringConvertible {
// It is not a violation of the Demeter law when another type uses this
// property, which is exposed for optimizations.
let impl: RowImpl
/// Unless we are producing a row array, we use a single row when iterating
@@ -21,6 +23,9 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl
/// The statementRef is released in deinit.
let statementRef: Unmanaged<SelectStatement>?
let sqliteStatement: SQLiteStatement?
var statement: SelectStatement? {
return statementRef?.takeUnretainedValue()
}
/// The number of columns in the row.
public let count: Int
@@ -89,6 +94,15 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl
self.count = Int(sqlite3_column_count(sqliteStatement))
}
/// Creates a row that maps an SQLite statement. Further calls to
/// sqlite3_step() modify the row.
init(sqliteStatement: SQLiteStatement) {
self.sqliteStatement = sqliteStatement
self.statementRef = nil
self.impl = SQLiteStatementRowImpl(sqliteStatement: sqliteStatement)
self.count = Int(sqlite3_column_count(sqliteStatement))
}
/// Creates a row that contain a copy of the current state of the
/// SQLite statement. Further calls to sqlite3_step() do not modify the row.
///
@@ -123,7 +137,12 @@ extension Row {
///
/// This method is case-insensitive.
public func hasColumn(_ columnName: String) -> Bool {
return impl.index(ofColumn: columnName) != nil
return index(ofColumn: columnName) != nil
}
@inline(__always)
func index(ofColumn name: String) -> Int? {
return impl.index(ofColumn: name)
}
}
@@ -131,6 +150,12 @@ extension Row {
// MARK: - Extracting Values
/// Fatal errors if index is out of bounds
@inline(__always)
private func checkIndex(_ index: Int, file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(index >= 0 && index < count, "row index out of range", file: file, line: line)
}
/// Returns true if and only if one column contains a non-null value, or if
/// the row was fetched with a row adapter that defines a scoped row that
/// contains a non-null value.
@@ -143,7 +168,7 @@ extension Row {
/// let row = try Row.fetchOne(db, "SELECT NULL, NULL")!
/// row.containsNonNullValue // false
public var containsNonNullValue: Bool {
for i in (0..<count) where !hasNull(atIndex: i) {
for i in (0..<count) where !impl.hasNull(atUncheckedIndex: i) {
return true
}
@@ -163,7 +188,7 @@ extension Row {
/// in performance-critical code because it can avoid decoding database
/// values.
public func hasNull(atIndex index: Int) -> Bool {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
checkIndex(index)
return impl.hasNull(atUncheckedIndex: index)
}
@@ -173,7 +198,7 @@ extension Row {
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
public subscript(_ index: Int) -> DatabaseValueConvertible? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
checkIndex(index)
return impl.databaseValue(atUncheckedIndex: index).storage.value
}
@@ -186,8 +211,8 @@ extension Row {
/// value is converted to the requested type `Value`. Should this conversion
/// fail, a fatal error is raised.
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.value(atUncheckedIndex: index)
checkIndex(index)
return Value.decodeIfPresent(from: self, atUncheckedIndex: index)
}
/// Returns the value at given index, converted to the requested type.
@@ -203,11 +228,8 @@ extension Row {
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
if let sqliteStatement = sqliteStatement { // fast path
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
}
return impl.fastValue(atUncheckedIndex: index)
checkIndex(index)
return Value.fastDecodeIfPresent(from: self, atUncheckedIndex: index)
}
/// Returns the value at given index, converted to the requested type.
@@ -218,8 +240,8 @@ extension Row {
/// This method crashes if the fetched SQLite value is NULL, or if the
/// SQLite value can not be converted to `Value`.
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.value(atUncheckedIndex: index)
checkIndex(index)
return Value.decode(from: self, atUncheckedIndex: index)
}
/// Returns the value at given index, converted to the requested type.
@@ -234,11 +256,8 @@ extension Row {
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
if let sqliteStatement = sqliteStatement { // fast path
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
}
return impl.fastValue(atUncheckedIndex: index)
checkIndex(index)
return Value.fastDecode(from: self, atUncheckedIndex: index)
}
/// Returns Int64, Double, String, Data or nil, depending on the value
@@ -256,7 +275,7 @@ extension Row {
// if row["foo"] != nil { ... }
//
// Without this method, the code above would not compile.
guard let index = impl.index(ofColumn: columnName) else {
guard let index = index(ofColumn: columnName) else {
return nil
}
return impl.databaseValue(atUncheckedIndex: index).storage.value
@@ -271,10 +290,10 @@ extension Row {
/// nil. Otherwise the SQLite value is converted to the requested type
/// `Value`. Should this conversion fail, a fatal error is raised.
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value? {
guard let index = impl.index(ofColumn: columnName) else {
guard let index = index(ofColumn: columnName) else {
return nil
}
return impl.value(atUncheckedIndex: index)
return Value.decodeIfPresent(from: self, atUncheckedIndex: index)
}
/// Returns the value at given column, converted to the requested type.
@@ -290,13 +309,10 @@ extension Row {
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value? {
guard let index = impl.index(ofColumn: columnName) else {
guard let index = index(ofColumn: columnName) else {
return nil
}
if let sqliteStatement = sqliteStatement { // fast path
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
}
return impl.fastValue(atUncheckedIndex: index)
return Value.fastDecodeIfPresent(from: self, atUncheckedIndex: index)
}
/// Returns the value at given column, converted to the requested type.
@@ -309,11 +325,14 @@ extension Row {
/// This method crashes if the fetched SQLite value is NULL, or if the
/// SQLite value can not be converted to `Value`.
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
guard let index = impl.index(ofColumn: columnName) else {
// Programmer error
fatalError("no such column: \(columnName)")
guard let index = index(ofColumn: columnName) else {
// No such column
fatalConversionError(
to: Value.self,
from: nil,
conversionContext: ValueConversionContext(self).atColumn(columnName))
}
return impl.value(atUncheckedIndex: index)
return Value.decode(from: self, atUncheckedIndex: index)
}
/// Returns the value at given column, converted to the requested type.
@@ -330,14 +349,14 @@ extension Row {
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
guard let index = impl.index(ofColumn: columnName) else {
// Programmer error
fatalError("no such column: \(columnName)")
guard let index = index(ofColumn: columnName) else {
// No such column
fatalConversionError(
to: Value.self,
from: nil,
conversionContext: ValueConversionContext(self).atColumn(columnName))
}
if let sqliteStatement = sqliteStatement { // fast path
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
}
return impl.fastValue(atUncheckedIndex: index)
return Value.fastDecode(from: self, atUncheckedIndex: index)
}
/// Returns Int64, Double, String, NSData or nil, depending on the value
@@ -420,7 +439,7 @@ extension Row {
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
public func dataNoCopy(atIndex index: Int) -> Data? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
checkIndex(index)
return impl.dataNoCopy(atUncheckedIndex: index)
}
@@ -436,7 +455,7 @@ extension Row {
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
public func dataNoCopy(named columnName: String) -> Data? {
guard let index = impl.index(ofColumn: columnName) else {
guard let index = index(ofColumn: columnName) else {
return nil
}
return impl.dataNoCopy(atUncheckedIndex: index)
@@ -595,12 +614,22 @@ public final class RowCursor : Cursor {
self.statement = statement
self.row = try Row(statement: statement).adapted(with: adapter, layout: statement)
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
statement.reset(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? statement.reset()
}
/// :nodoc:
public func next() throws -> Row? {
if done { return nil }
if done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
}
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
@@ -679,8 +708,11 @@ extension Row {
/// - returns: An optional row.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? {
// The cursor reuses a single mutable row. Return an immutable copy.
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next().map { $0.copy() }
let cursor = try fetchCursor(statement, arguments: arguments, adapter: adapter)
// Keep cursor alive until we can copy the fetched row
return try withExtendedLifetime(cursor) {
try cursor.next().map { $0.copy() }
}
}
}
@@ -911,7 +943,7 @@ extension Row {
/// Accesses the (ColumnName, DatabaseValue) pair at given index.
public subscript(position: RowIndex) -> (String, DatabaseValue) {
let index = position.index
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
checkIndex(index)
return (
impl.columnName(atUncheckedIndex: index),
impl.databaseValue(atUncheckedIndex: index))
@@ -962,12 +994,22 @@ extension Row {
// Hashable
extension Row {
/// The hash value
#if swift(>=4.2)
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(count)
for (column, dbValue) in self {
hasher.combine(column)
hasher.combine(dbValue)
}
}
#else
/// :nodoc:
public var hashValue: Int {
return columnNames.reduce(0) { (acc, column) in acc ^ column.hashValue } ^
databaseValues.reduce(0) { (acc, dbValue) in acc ^ dbValue.hashValue }
}
#endif
}
// CustomStringConvertible & CustomDebugStringConvertible
@@ -1178,15 +1220,14 @@ protocol RowImpl {
var count: Int { get }
var isFetched: Bool { get }
var scopes: Row.ScopesView { get }
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value?
func hasNull(atUncheckedIndex index:Int) -> Bool
func dataNoCopy(atUncheckedIndex index:Int) -> Data?
func columnName(atUncheckedIndex index: Int) -> String
func hasNull(atUncheckedIndex index:Int) -> Bool
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ type: Value.Type, atUncheckedIndex index: Int) -> Value
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ type: Value.Type, atUncheckedIndex index: Int) -> Value?
func dataNoCopy(atUncheckedIndex index:Int) -> Data?
// This method MUST be case-insensitive, and returns the index of the
// leftmost column that matches *name*.
/// Returns the index of the leftmost column that matches *name* (case-insensitive)
func index(ofColumn name: String) -> Int?
// row.impl is guaranteed to be self.
@@ -1197,42 +1238,59 @@ protocol RowImpl {
extension RowImpl {
func copiedRow(_ row: Row) -> Row {
return row
// unless customized, assume unsafe and unadapted row
return Row(impl: ArrayRowImpl(columns: row.map { $0 }))
}
func unscopedRow(_ row: Row) -> Row {
// unless customized, assume unadapted row (see AdaptedRowImpl for customization)
return row
}
func unadaptedRow(_ row: Row) -> Row {
// unless customized, assume unadapted row (see AdaptedRowImpl for customization)
return row
}
var scopes: Row.ScopesView {
// unless customized, assume unuscoped row (see AdaptedRowImpl for customization)
return Row.ScopesView()
}
func hasNull(atUncheckedIndex index:Int) -> Bool {
// unless customized, use slow check (see StatementRowImpl and AdaptedRowImpl for customization)
return databaseValue(atUncheckedIndex: index).isNull
}
func value<Value: DatabaseValueConvertible>(atUncheckedIndex index: Int) -> Value {
return databaseValue(atUncheckedIndex: index).losslessConvert()
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int) -> Value
{
// unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization)
return Value.decode(
from: databaseValue(atUncheckedIndex: index),
conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index))
}
func value<Value: DatabaseValueConvertible>(atUncheckedIndex index: Int) -> Value? {
return databaseValue(atUncheckedIndex: index).losslessConvert()
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int) -> Value?
{
// unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization)
return Value.decodeIfPresent(
from: databaseValue(atUncheckedIndex: index),
conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index))
}
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value {
return databaseValue(atUncheckedIndex: index).losslessConvert()
}
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value? {
return databaseValue(atUncheckedIndex: index).losslessConvert()
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
// unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization)
return Data.decodeIfPresent(
from: databaseValue(atUncheckedIndex: index),
conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index))
}
}
// TODO: merge with StatementCopyRowImpl eventually?
/// See Row.init(dictionary:)
private struct ArrayRowImpl : RowImpl {
let columns: [(String, DatabaseValue)]
@@ -1249,10 +1307,6 @@ private struct ArrayRowImpl : RowImpl {
return false
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
return databaseValue(atUncheckedIndex: index).losslessConvert()
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return columns[index].1
}
@@ -1261,15 +1315,18 @@ private struct ArrayRowImpl : RowImpl {
return columns[index].0
}
// This method MUST be case-insensitive, and returns the index of the
// leftmost column that matches *name*.
func index(ofColumn name: String) -> Int? {
let lowercaseName = name.lowercased()
return columns.index { (column, _) in column.lowercased() == lowercaseName }
}
func copiedRow(_ row: Row) -> Row {
return row
}
}
// TODO: merge with ArrayRowImpl eventually?
/// See Row.init(copiedFromStatementRef:sqliteStatement:)
private struct StatementCopyRowImpl : RowImpl {
let dbValues: ContiguousArray<DatabaseValue>
@@ -1289,10 +1346,6 @@ private struct StatementCopyRowImpl : RowImpl {
return true
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
return databaseValue(atUncheckedIndex: index).losslessConvert()
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return dbValues[index]
}
@@ -1301,12 +1354,14 @@ private struct StatementCopyRowImpl : RowImpl {
return columnNames[index]
}
// This method MUST be case-insensitive, and returns the index of the
// leftmost column that matches *name*.
func index(ofColumn name: String) -> Int? {
let lowercaseName = name.lowercased()
return columnNames.index { $0.lowercased() == lowercaseName }
}
func copiedRow(_ row: Row) -> Row {
return row
}
}
@@ -1319,7 +1374,7 @@ private struct StatementRowImpl : RowImpl {
init(sqliteStatement: SQLiteStatement, statementRef: Unmanaged<SelectStatement>) {
self.statementRef = statementRef
self.sqliteStatement = sqliteStatement
// Optimize row["..."]
// Optimize row[columnName]
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement)).map { String(cString: sqlite3_column_name(sqliteStatement, Int32($0))).lowercased() }
self.lowercaseColumnIndexes = Dictionary(
lowercaseColumnNames
@@ -1337,7 +1392,7 @@ private struct StatementRowImpl : RowImpl {
}
func hasNull(atUncheckedIndex index:Int) -> Bool {
// Avoid extracting values, because this modifies the statement.
// Avoid extracting values, because this modifies the SQLite statement.
return sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL
}
@@ -1356,20 +1411,24 @@ private struct StatementRowImpl : RowImpl {
return DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
}
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value {
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int) -> Value
{
return Value.fastDecode(from: sqliteStatement, index: Int32(index))
}
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value? {
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int) -> Value?
{
return Value.fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index))
}
func columnName(atUncheckedIndex index: Int) -> String {
return statementRef.takeUnretainedValue().columnNames[index]
}
// This method MUST be case-insensitive, and returns the index of the
// leftmost column that matches *name*.
func index(ofColumn name: String) -> Int? {
if let index = lowercaseColumnIndexes[name] {
return index
@@ -1382,6 +1441,29 @@ private struct StatementRowImpl : RowImpl {
}
}
// This one is not optimized at all, since it is only used in fatal conversion errors, so far
private struct SQLiteStatementRowImpl : RowImpl {
let sqliteStatement: SQLiteStatement
var count: Int { return Int(sqlite3_column_count(sqliteStatement)) }
var isFetched: Bool { return true }
func columnName(atUncheckedIndex index: Int) -> String {
return String(cString: sqlite3_column_name(sqliteStatement, Int32(index)))
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
}
func index(ofColumn name: String) -> Int? {
let name = name.lowercased()
for index in 0..<count where columnName(atUncheckedIndex: index).lowercased() == name {
return index
}
return nil
}
}
/// See Row.init()
private struct EmptyRowImpl : RowImpl {
var count: Int {
@@ -1397,11 +1479,6 @@ private struct EmptyRowImpl : RowImpl {
fatalError("row index out of range")
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
// Programmer error
fatalError("row index out of range")
}
func columnName(atUncheckedIndex index: Int) -> String {
// Programmer error
fatalError("row index out of range")
@@ -1410,4 +1487,8 @@ private struct EmptyRowImpl : RowImpl {
func index(ofColumn name: String) -> Int? {
return nil
}
func copiedRow(_ row: Row) -> Row {
return row
}
}
+11 -5
View File
@@ -501,16 +501,22 @@ struct AdaptedRowImpl : RowImpl {
return base.impl.databaseValue(atUncheckedIndex: mappedIndex)
}
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value {
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int) -> Value
{
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return base.impl.fastValue(atUncheckedIndex: mappedIndex)
return Value.fastDecode(from: base, atUncheckedIndex: mappedIndex)
}
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value? {
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int) -> Value?
{
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return base.impl.fastValue(atUncheckedIndex: mappedIndex)
return Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex)
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex)
+5 -6
View File
@@ -22,7 +22,7 @@ import Dispatch
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
/// dispatch queue.
final class SchedulingWatchdog {
private static let specificKey = DispatchSpecificKey<SchedulingWatchdog>()
private static let watchDogKey = DispatchSpecificKey<SchedulingWatchdog>()
private(set) var allowedDatabases: [Database]
var databaseObservationBroker: DatabaseObservationBroker?
@@ -30,11 +30,10 @@ final class SchedulingWatchdog {
allowedDatabases = [database]
}
static func makeSerializedQueue(allowingDatabase database: Database, label: String) -> DispatchQueue {
let queue = DispatchQueue(label: label)
static func allowDatabase(_ database: Database, onQueue queue: DispatchQueue) {
precondition(queue.getSpecific(key: watchDogKey) == nil)
let watchdog = SchedulingWatchdog(allowedDatabase: database)
queue.setSpecific(key: specificKey, value: watchdog)
return queue
queue.setSpecific(key: watchDogKey, value: watchdog)
}
func inheritingAllowedDatabases<T>(from other: SchedulingWatchdog, execute body: () throws -> T) rethrows -> T {
@@ -49,7 +48,7 @@ final class SchedulingWatchdog {
}
static var current: SchedulingWatchdog? {
return DispatchQueue.getSpecific(key: specificKey)
return DispatchQueue.getSpecific(key: watchDogKey)
}
func allows(_ db: Database) -> Bool {
+4 -3
View File
@@ -16,7 +16,7 @@ final class SerializedDatabase {
/// The dispatch queue
private let queue: DispatchQueue
init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache, label: String) throws {
init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache, defaultLabel: String, purpose: String? = nil) throws {
// According to https://www.sqlite.org/threadsafe.html
//
// > SQLite support three different threading modes:
@@ -37,9 +37,10 @@ final class SerializedDatabase {
var config = configuration
config.threadingMode = .multiThread
db = try Database(path: path, configuration: config, schemaCache: schemaCache)
queue = SchedulingWatchdog.makeSerializedQueue(allowingDatabase: db, label: label)
self.path = path
self.db = try Database(path: path, configuration: config, schemaCache: schemaCache)
self.queue = configuration.makeDispatchQueue(defaultLabel: defaultLabel, purpose: purpose)
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
try queue.sync {
try db.setup()
}
+36 -94
View File
@@ -54,9 +54,10 @@ public class Statement {
var sqliteStatement: SQLiteStatement? = nil
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
#if GRDBCUSTOMSQLITE
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd)
#else
// TODO: use sqlite3_prepare_v3 if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *)
let code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
#endif
@@ -82,14 +83,11 @@ public class Statement {
sqlite3_finalize(sqliteStatement)
}
final func reset() {
// It looks like sqlite3_reset() does not access the file system.
// This function call should thus succeed, unless a GRDB bug, or a
// programmer error (reusing a failed statement): there is no point
// throwing any error.
final func reset() throws {
SchedulingWatchdog.preconditionValidQueue(database)
let code = sqlite3_reset(sqliteStatement)
guard code == SQLITE_OK else {
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql)
}
}
@@ -135,7 +133,7 @@ public class Statement {
_arguments = arguments
argumentsNeedValidation = false
reset()
try! reset()
clearBindings()
var valuesIterator = arguments.values.makeIterator()
@@ -158,7 +156,7 @@ public class Statement {
argumentsNeedValidation = false
// Apply
reset()
try reset()
clearBindings()
for (index, dbValue) in zip(Int32(1)..., bindings) {
bind(dbValue, at: index)
@@ -356,27 +354,27 @@ public final class SelectStatement : Statement {
/// Creates a cursor over the statement. This cursor does not produce any
/// value, and is only intended to give access to the sqlite3_step()
/// low-level function.
func cursor(arguments: StatementArguments? = nil) -> StatementCursor {
func makeCursor(arguments: StatementArguments? = nil) -> StatementCursor {
return StatementCursor(statement: self, arguments: arguments)
}
/// Utility function for cursors
func cursorReset(arguments: StatementArguments? = nil) {
SchedulingWatchdog.preconditionValidQueue(database)
func reset(withArguments arguments: StatementArguments? = nil) {
prepare(withArguments: arguments)
reset()
try! reset()
}
}
// Hide AuthorizedStatement from Jazzy
extension SelectStatement: AuthorizedStatement { }
// TODO: remove public qualifier, or expose SelectStatement.makeCursor()
/// A cursor that iterates a database statement without producing any value.
/// For example:
///
/// try dbQueue.read { db in
/// let statement = db.makeSelectStatement("SELECT * FROM player")
/// let cursor: StatementCursor = statement.cursor()
/// let cursor: StatementCursor = statement.makeCursor()
/// }
public final class StatementCursor: Cursor {
public let statement: SelectStatement
@@ -387,12 +385,22 @@ public final class StatementCursor: Cursor {
fileprivate init(statement: SelectStatement, arguments: StatementArguments? = nil) {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
statement.reset(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? statement.reset()
}
/// :nodoc:
public func next() throws -> Void? {
if done { return nil }
if done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
}
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
@@ -474,7 +482,7 @@ public final class UpdateStatement : Statement {
public func execute(arguments: StatementArguments? = nil) throws {
SchedulingWatchdog.preconditionValidQueue(database)
prepare(withArguments: arguments)
reset()
try reset()
database.updateStatementWillExecute(self)
while true {
@@ -580,13 +588,21 @@ extension UpdateStatement: AuthorizedStatement { }
///
/// ## Mixed Arguments
///
/// When a statement consumes a mix of named and positional arguments, it
/// prefers named arguments over positional ones. For example:
/// It is possible to mix named and positional arguments. Yet this is usually
/// confusing, and it is best to avoid this practice:
///
/// let sql = "SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar"
/// let row = try Row.fetchOne(db, sql, arguments: [1, 2, "bar"] + ["foo": "foo"])!
/// var arguments: StatementArguments = [1, 2, "bar"] + ["foo": "foo"]
/// let row = try Row.fetchOne(db, sql, arguments: arguments)!
/// print(row)
/// // Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"]
///
/// Mixed arguments exist as a support for requests like the following:
///
/// let players = try Player
/// .filter(sql: "team = :team", arguments: ["team": "Blue"])
/// .filter(sql: "score > ?", arguments: [1000])
/// .fetchAll(db)
public struct StatementArguments: CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {
private(set) var values: [DatabaseValue] = []
private(set) var namedValues: [String: DatabaseValue] = [:]
@@ -904,77 +920,3 @@ extension StatementArguments {
return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]"
}
}
/// A thread-unsafe statement cache
struct StatementCache {
unowned let db: Database
private var selectStatements: [String: SelectStatement] = [:]
private var updateStatements: [String: UpdateStatement] = [:]
init(database: Database) {
self.db = database
}
mutating func selectStatement(_ sql: String) throws -> SelectStatement {
if let statement = selectStatements[sql] {
return statement
}
#if GRDBCUSTOMSQLITE
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
// > planner that the prepared statement will be retained for a long
// > time and probably reused many times.
//
// This looks like a perfect match for cached statements.
//
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
let statement = try db.makeSelectStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement = try db.makeSelectStatement(sql)
#endif
selectStatements[sql] = statement
return statement
}
mutating func updateStatement(_ sql: String) throws -> UpdateStatement {
if let statement = updateStatements[sql] {
return statement
}
#if GRDBCUSTOMSQLITE
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
// > planner that the prepared statement will be retained for a long
// > time and probably reused many times.
//
// This looks like a perfect match for cached statements.
//
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
let statement = try db.makeUpdateStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement = try db.makeUpdateStatement(sql)
#endif
updateStatements[sql] = statement
return statement
}
mutating func clear() {
updateStatements = [:]
selectStatements = [:]
}
mutating func remove(_ statement: SelectStatement) {
if let index = selectStatements.index(where: { $0.1 === statement }) {
selectStatements.remove(at: index)
}
}
mutating func remove(_ statement: UpdateStatement) {
if let index = updateStatements.index(where: { $0.1 === statement }) {
updateStatements.remove(at: index)
}
}
}
+8 -8
View File
@@ -49,18 +49,18 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
switch actionCode {
case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE,
SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX:
SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX,
SQLITE_DROP_VIEW, SQLITE_DROP_TEMP_VIEW,
SQLITE_DROP_TRIGGER, SQLITE_DROP_TEMP_TRIGGER:
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:
case SQLITE_ALTER_TABLE, SQLITE_DETACH,
SQLITE_CREATE_INDEX, SQLITE_CREATE_TABLE,
SQLITE_CREATE_TEMP_INDEX, SQLITE_CREATE_TEMP_TABLE,
SQLITE_CREATE_TEMP_TRIGGER, SQLITE_CREATE_TEMP_VIEW,
SQLITE_CREATE_TRIGGER, SQLITE_CREATE_VIEW:
invalidatesDatabaseSchemaCache = true
return SQLITE_OK
+57 -54
View File
@@ -50,27 +50,6 @@ public protocol StatementColumnConvertible {
init(sqliteStatement: SQLiteStatement, index: Int32)
}
extension StatementColumnConvertible {
@inline(__always)
static func losslessConvert(sqliteStatement: SQLiteStatement, index: Int32) -> Self? {
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
return nil
}
return self.init(sqliteStatement: sqliteStatement, index: index)
}
@inline(__always)
static func losslessConvert(sqliteStatement: SQLiteStatement, index: Int32) -> Self {
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
// Programmer error
fatalError("could not convert database value NULL to \(Self.self)")
}
return self.init(sqliteStatement: sqliteStatement, index: index)
}
}
/// A cursor of database values extracted from a single column.
/// For example:
///
@@ -80,7 +59,7 @@ extension StatementColumnConvertible {
/// print(name)
/// }
/// }
public final class ColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
private let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let columnIndex: Int32
@@ -88,28 +67,35 @@ public final class ColumnCursor<Value: DatabaseValueConvertible & StatementColum
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
// We'll read from leftmost column at index 0, unless adapter mangles columns
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
if let adapter = adapter {
// adapter may redefine the index of the leftmost column
self.columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
} else {
self.columnIndex = 0
}
statement.reset(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? statement.reset()
}
/// :nodoc:
public func next() throws -> Value? {
if done { return nil }
if done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
}
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
var error = "could not convert database value NULL to \(Value.self) with statement `\(statement.sql)`"
if !statement.arguments.isEmpty {
error += " arguments \(statement.arguments)"
}
fatalError(error)
}
return Value(sqliteStatement: sqliteStatement, index: columnIndex)
return Value.fastDecode(from: sqliteStatement, index: columnIndex)
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
@@ -117,6 +103,9 @@ public final class ColumnCursor<Value: DatabaseValueConvertible & StatementColum
}
}
@available(*, deprecated, renamed: "FastDatabaseValueCursor")
public typealias ColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> = FastDatabaseValueCursor<Value>
/// A cursor of optional database values extracted from a single column.
/// For example:
///
@@ -126,7 +115,7 @@ public final class ColumnCursor<Value: DatabaseValueConvertible & StatementColum
/// print(email ?? "<NULL>")
/// }
/// }
public final class NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
public final class FastNullableDatabaseValueCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
private let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let columnIndex: Int32
@@ -134,24 +123,35 @@ public final class NullableColumnCursor<Value: DatabaseValueConvertible & Statem
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
// We'll read from leftmost column at index 0, unless adapter mangles columns
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
if let adapter = adapter {
// adapter may redefine the index of the leftmost column
self.columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
} else {
self.columnIndex = 0
}
statement.reset(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? statement.reset()
}
/// :nodoc:
public func next() throws -> Value?? {
if done { return nil }
if done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
}
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
return .some(nil)
}
return Value(sqliteStatement: sqliteStatement, index: columnIndex)
return Value.fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: columnIndex)
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
@@ -159,6 +159,9 @@ public final class NullableColumnCursor<Value: DatabaseValueConvertible & Statem
}
}
@available(*, deprecated, renamed: "FastNullableDatabaseValueCursor")
public typealias NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> = FastNullableDatabaseValueCursor<Value>
/// Types that adopt both DatabaseValueConvertible and
/// StatementColumnConvertible can be efficiently initialized from
/// database values.
@@ -188,8 +191,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> ColumnCursor<Self> {
return try ColumnCursor(statement: statement, arguments: arguments, adapter: adapter)
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> {
return try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of values fetched from a prepared statement.
@@ -220,7 +223,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
// fetchOne returns nil if there is no row, or if there is a row with a null value
let cursor = try NullableColumnCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
let cursor = try FastNullableDatabaseValueCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
return try cursor.next() ?? nil
}
}
@@ -248,7 +251,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> ColumnCursor<Self> {
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> {
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
}
@@ -305,7 +308,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - request: A FetchRequest.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> ColumnCursor<Self> {
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> FastDatabaseValueCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
@@ -361,7 +364,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - parameter db: A database connection.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder> {
public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor<RowDecoder> {
return try RowDecoder.fetchCursor(db, self)
}
@@ -427,8 +430,8 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor<Wrapped> {
return try NullableColumnCursor(statement: statement, arguments: arguments, adapter: adapter)
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> {
return try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of optional values fetched from a prepared statement.
@@ -470,7 +473,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor<Wrapped> {
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> {
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
}
@@ -512,7 +515,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - request: A FetchRequest.
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> NullableColumnCursor<Wrapped> {
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> FastNullableDatabaseValueCursor<Wrapped> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
@@ -553,7 +556,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
/// - parameter db: A database connection.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> NullableColumnCursor<RowDecoder._Wrapped> {
public func fetchCursor(_ db: Database) throws -> FastNullableDatabaseValueCursor<RowDecoder._Wrapped> {
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
}
+1 -1
View File
@@ -1,4 +1,4 @@
#if !os(Linux)
#if canImport(CoreGraphics)
import CoreGraphics
/// CGFloat adopts DatabaseValueConvertible
+10 -4
View File
@@ -8,8 +8,8 @@ import Foundation
/// Data is convertible to and from DatabaseValue.
extension Data : DatabaseValueConvertible, StatementColumnConvertible {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) {
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
self.init(bytes: bytes, count: count) // copy bytes
} else {
self.init()
@@ -24,9 +24,15 @@ extension Data : DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a Data initialized from *dbValue*, if it contains
/// a Blob.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Data? {
guard case .blob(let data) = dbValue.storage else {
switch dbValue.storage {
case .blob(let data):
return data
case .string(let string):
// Implicit conversion from string to blob, just as SQLite does
// See https://www.sqlite.org/c3ref/column_blob.html
return string.data(using: .utf8)
default:
return nil
}
return data
}
}
@@ -76,14 +76,14 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
guard let cString = sqlite3_column_text(sqliteStatement, index) else {
fatalError("could not convert database value \(DatabaseValue(sqliteStatement: sqliteStatement, index: index)) to DatabaseDateComponents")
fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
}
let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen
let optionalComponents = cString.withMemoryRebound(to: Int8.self, capacity: length + 1 /* trailing \0 */) { cString in
SQLiteDateParser().components(cString: cString, length: length)
}
guard let components = optionalComponents else {
fatalError("could not convert database value \(String(cString: cString)) to DatabaseDateComponents")
fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
}
self.dateComponents = components.dateComponents
self.format = components.format
+3 -5
View File
@@ -125,17 +125,15 @@ extension Date: StatementColumnConvertible {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_INTEGER, SQLITE_FLOAT:
self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, Int32(index)))
self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, index))
case SQLITE_TEXT:
let databaseDateComponents = DatabaseDateComponents(sqliteStatement: sqliteStatement, index: index)
guard let date = Date(databaseDateComponents: databaseDateComponents) else {
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
fatalError("could not convert database value \(dbValue) to Date")
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
}
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
default:
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
fatalError("could not convert database value \(dbValue) to Date")
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
}
}
}
+68 -8
View File
@@ -1,10 +1,13 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
#if !os(Linux)
/// NSUUID adopts DatabaseValueConvertible
extension NSUUID : DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
extension NSUUID: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16)
return uuidBytes.withUnsafeMutableBufferPointer { buffer in
@@ -13,15 +16,72 @@ extension NSUUID : DatabaseValueConvertible {
}
}
/// Returns an NSUUID initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
guard let data = NSData.fromDatabaseValue(dbValue), data.length == 16 else {
switch dbValue.storage {
case .blob(let data) where data.count == 16:
// The code below works in debug configuration, but crashes in
// release configuration (Xcode 9.4.1)
// return data.withUnsafeBytes {
// self.init(uuidBytes: $0)
// }
// Workaround (involves a useless copy)
let buffer = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: 16)
_ = data.copyBytes(to: buffer)
let uuid = self.init(uuidBytes: UnsafePointer(buffer.baseAddress!))
buffer.deallocate()
return uuid
case .string(let string):
return self.init(uuidString: string)
default:
return nil
}
return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self))
}
}
}
#endif
/// UUID adopts DatabaseValueConvertible
extension UUID : DatabaseValueConvertible { }
extension UUID: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
var uuid_t = uuid
return withUnsafeBytes(of: &uuid_t) {
Data(bytes: $0.baseAddress!, count: $0.count).databaseValue
}
}
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UUID? {
switch dbValue.storage {
case .blob(let data) where data.count == 16:
return data.withUnsafeBytes {
UUID(uuid: $0.pointee)
}
case .string(let string):
return UUID(uuidString: string)
default:
return nil
}
}
}
extension UUID: StatementColumnConvertible {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_TEXT:
let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
guard let uuid = UUID(uuidString: string) else {
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
}
self.init(uuid: uuid.uuid)
case SQLITE_BLOB:
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
let blob = sqlite3_column_blob(sqliteStatement, index) else
{
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
}
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
default:
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
}
}
}
@@ -15,20 +15,117 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode(_ type: Bool.Type) throws -> Bool { return dbValue.losslessConvert() }
func decode(_ type: Int.Type) throws -> Int { return dbValue.losslessConvert() }
func decode(_ type: Int8.Type) throws -> Int8 { return dbValue.losslessConvert() }
func decode(_ type: Int16.Type) throws -> Int16 { return dbValue.losslessConvert() }
func decode(_ type: Int32.Type) throws -> Int32 { return dbValue.losslessConvert() }
func decode(_ type: Int64.Type) throws -> Int64 { return dbValue.losslessConvert() }
func decode(_ type: UInt.Type) throws -> UInt { return dbValue.losslessConvert() }
func decode(_ type: UInt8.Type) throws -> UInt8 { return dbValue.losslessConvert() }
func decode(_ type: UInt16.Type) throws -> UInt16 { return dbValue.losslessConvert() }
func decode(_ type: UInt32.Type) throws -> UInt32 { return dbValue.losslessConvert() }
func decode(_ type: UInt64.Type) throws -> UInt64 { return dbValue.losslessConvert() }
func decode(_ type: Float.Type) throws -> Float { return dbValue.losslessConvert() }
func decode(_ type: Double.Type) throws -> Double { return dbValue.losslessConvert() }
func decode(_ type: String.Type) throws -> String { return dbValue.losslessConvert() }
func decode(_ type: Bool.Type) throws -> Bool {
if let result = Bool.fromDatabaseValue(dbValue) {
return result
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
}
func decode(_ type: Int.Type) throws -> Int {
if let result = Int.fromDatabaseValue(dbValue) {
return result
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
}
func decode(_ type: Int8.Type) throws -> Int8 {
if let result = Int8.fromDatabaseValue(dbValue) {
return result
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
}
func decode(_ type: Int16.Type) throws -> Int16 {
if let result = Int16.fromDatabaseValue(dbValue) {
return result
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
}
func decode(_ type: Int32.Type) throws -> Int32 {
if let result = Int32.fromDatabaseValue(dbValue) {
return result
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
}
func decode(_ type: Int64.Type) throws -> Int64 {
if let result = Int64.fromDatabaseValue(dbValue) {
return result
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
}
func decode(_ type: UInt.Type) throws -> UInt {
if let result = UInt.fromDatabaseValue(dbValue) {
return result
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
}
func decode(_ type: UInt8.Type) throws -> UInt8 {
if let result = UInt8.fromDatabaseValue(dbValue) {
return result
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
}
func decode(_ type: UInt16.Type) throws -> UInt16 {
if let result = UInt16.fromDatabaseValue(dbValue) {
return result
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
}
func decode(_ type: UInt32.Type) throws -> UInt32 {
if let result = UInt32.fromDatabaseValue(dbValue) {
return result
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
}
func decode(_ type: UInt64.Type) throws -> UInt64 {
if let result = UInt64.fromDatabaseValue(dbValue) {
return result
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
}
func decode(_ type: Float.Type) throws -> Float {
if let result = Float.fromDatabaseValue(dbValue) {
return result
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
}
func decode(_ type: Double.Type) throws -> Double {
if let result = Double.fromDatabaseValue(dbValue) {
return result
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
}
func decode(_ type: String.Type) throws -> String {
if let result = String.fromDatabaseValue(dbValue) {
return result
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
}
/// Decodes a single value of the given type.
///
@@ -41,7 +138,11 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows custom database decoding, such as decoding Date from
// String, for example.
return type.fromDatabaseValue(dbValue) as! T
if let result = type.fromDatabaseValue(dbValue) {
return result as! T
} else {
throw DecodingError.dataCorruptedError(in: self, debugDescription: "value mismatch")
}
} else {
return try T(from: DatabaseValueDecoder(dbValue: dbValue, codingPath: codingPath))
}
@@ -105,7 +105,7 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
if let v = Int(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to Int")
fatalConversionError(to: Int.self, sqliteStatement: sqliteStatement, index: index)
}
}
@@ -133,7 +133,7 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
if let v = Int8(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to Int8")
fatalConversionError(to: Int8.self, sqliteStatement: sqliteStatement, index: index)
}
}
@@ -161,7 +161,7 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
if let v = Int16(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to Int16")
fatalConversionError(to: Int16.self, sqliteStatement: sqliteStatement, index: index)
}
}
@@ -189,7 +189,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
if let v = Int32(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to Int32")
fatalConversionError(to: Int32.self, sqliteStatement: sqliteStatement, index: index)
}
}
@@ -249,7 +249,7 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
if let v = UInt(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt")
fatalConversionError(to: UInt.self, sqliteStatement: sqliteStatement, index: index)
}
}
@@ -277,7 +277,7 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
if let v = UInt8(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt8")
fatalConversionError(to: UInt8.self, sqliteStatement: sqliteStatement, index: index)
}
}
@@ -305,7 +305,7 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
if let v = UInt16(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt16")
fatalConversionError(to: UInt16.self, sqliteStatement: sqliteStatement, index: index)
}
}
@@ -333,7 +333,7 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
if let v = UInt32(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt32")
fatalConversionError(to: UInt32.self, sqliteStatement: sqliteStatement, index: index)
}
}
@@ -361,7 +361,7 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
if let v = UInt64(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt64")
fatalConversionError(to: UInt64.self, sqliteStatement: sqliteStatement, index: index)
}
}
@@ -445,7 +445,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
self = String(cString: sqlite3_column_text(sqliteStatement, Int32(index))!)
self = String(cString: sqlite3_column_text(sqliteStatement, index)!)
}
/// Returns a value that can be stored in the database.
@@ -456,6 +456,10 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a String initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> String? {
switch dbValue.storage {
case .blob(let data):
// Implicit conversion from blob to string, just as SQLite does
// See https://www.sqlite.org/c3ref/column_blob.html
return String(data: data, encoding: .utf8)
case .string(let string):
return string
default:
+64
View File
@@ -130,6 +130,70 @@
}
static func api(_ db: Database) -> UnsafePointer<fts5_api> {
// Access to FTS5 is one of the rare SQLite api which was broken in
// SQLite 3.20.0+, for security reasons:
//
// Starting SQLite 3.20.0+, we need to use the new sqlite3_bind_pointer api.
// The previous way to access FTS5 does not work any longer.
//
// So let's see which SQLite version we are linked against:
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// GRDB is linked against SQLCipher or a custom SQLite build: SQLite 3.20.0 or more.
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
#else
// GRDB is linked against the system SQLite.
//
// Do we use SQLite 3.19.3 (iOS 11.4), or SQLite 3.24.0 (iOS 12.0)?
// We need to check for available(iOS 12.0, OSX 10.14, watchOS 5.0, *).
//
// This test requires the Swift 4.2 compiler.
//
// It does not need the Swift 4.2 language, though: the Swift 4.2
// compiler running in Swift 4.0 compatibility mode is OK.
//
// On top of that, we want to preserve compatibility with Xcode 9.3+.
//
// So let's check exactly which compiler version we are using.
//
// Fortunately, this horribly complex check has been solved
// by @hartbit: see https://forums.swift.org/t/compiler-version-directive/11952
// and https://github.com/hartbit/swift-evolution/blob/compiler-directive/proposals/XXXX-compiler-version-directive.md
#if swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
// SQLite 3.24.0 or more
// setup: Xcode 10.0, SWIFT_VERSION = 4.0, iOS 12
// setup: Xcode 10.0, SWIFT_VERSION = 4.2, iOS 12
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
} else {
// SQLite 3.19.3 or less
// setup: Xcode 10.0, SWIFT_VERSION = 4.0, iOS 11
// setup: Xcode 10.0, SWIFT_VERSION = 4.2, iOS 11
return api_v1(db)
}
#else
// SQLite 3.19.3 or less
// setup: Xcode 9.4.1, iOS 11
return api_v1(db)
#endif
#endif
}
private static func api_v1(_ db: Database) -> UnsafePointer<fts5_api> {
guard let data = try! Data.fetchOne(db, "SELECT fts5()") else {
fatalError("FTS5 is not available")
}
return data.withUnsafeBytes { $0.pointee }
}
// Technique given by Jordan Rose:
// https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4
private static func api_v2(
_ db: Database,
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, Int32, UInt32, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> Int32,
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, Int32, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> Int32)
-> UnsafePointer<fts5_api>
{
let sqliteConnection = db.sqliteConnection
var statement: SQLiteStatement? = nil
var api: UnsafePointer<fts5_api>? = nil
-15
View File
@@ -150,19 +150,4 @@
}
}
}
extension DatabasePool {
// MARK: - Custom FTS5 Tokenizers
/// Add a custom FTS5 tokenizer.
///
/// class MyTokenizer : FTS5CustomTokenizer { ... }
/// dbPool.add(tokenizer: MyTokenizer.self)
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
writeWithoutTransaction { db in
db.add(tokenizer: Tokenizer.self)
}
}
}
#endif
+1 -1
View File
@@ -75,7 +75,7 @@
}
}
try db.makeSelectStatement("SELECT * FROM document WHERE document MATCH ?")
.cursor(arguments: [rawPattern])
.makeCursor(arguments: [rawPattern])
.next() // error on next() for invalid patterns
}
} catch let error as DatabaseError {
+2
View File
@@ -184,6 +184,7 @@ public typealias TransactionObserverType = TransactionObserver
@available(*, unavailable, renamed:"Column")
public typealias SQLColumn = Column
/// :nodoc:
extension SQLSpecificExpressible {
@available(*, unavailable, renamed:"capitalized")
public var capitalizedString: SQLExpression { get { return capitalized } }
@@ -195,6 +196,7 @@ extension SQLSpecificExpressible {
public var uppercaseString: SQLExpression { get { return uppercased } }
}
/// :nodoc:
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
extension SQLSpecificExpressible {
@available(*, unavailable, renamed:"localizedCapitalized")
@@ -52,14 +52,14 @@ public protocol Association: DerivableRequest {
var request: AssociationRequest<RowDecoder> { get }
/// :nodoc:
func joinCondition(_ db: Database) throws -> JoinCondition
var joinCondition: JoinCondition { get }
/// :nodoc:
func mapRequest(_ transform: (AssociationRequest<RowDecoder>) -> AssociationRequest<RowDecoder>) -> Self
}
extension Association {
/// Creates an association with a new set of selected columns.
/// Creates an association which selects *selection*.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
@@ -211,16 +211,30 @@ extension Association {
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public typealias JoinCondition = (_ leftAlias: TableAlias, _ rightAlias: TableAlias) -> SQLExpression?
/// Turns a ForeignKeyRequest into a JoinCondition
struct ForeignKeyJoinConditionRequest {
/// The condition that links two joined tables.
///
/// We only support one kind of join condition, today: foreign keys.
///
/// SELECT ...
/// FROM book
/// JOIN author ON author.id = book.authorId
/// <--the join condition--->
///
/// When we eventually add support for new ways to join tables, JoinCondition
/// is the type we'll need to update.
///
/// The Equatable conformance is used when we merge associations. Two
/// associations can be merged if and only if their join conditions
/// are equal:
///
/// let request = Book
/// .include(required: Book.author)
/// .include(required: Book.author)
public struct JoinCondition: Equatable {
var foreignKeyRequest: ForeignKeyRequest
var originIsLeft: Bool
func fetch(_ db: Database) throws -> JoinCondition {
func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression? {
let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping
let columnMapping: [(left: Column, right: Column)]
if originIsLeft {
@@ -228,11 +242,10 @@ struct ForeignKeyJoinConditionRequest {
} else {
columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) }
}
return { (leftAlias, rightAlias) in
return columnMapping
.map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) }
.joined(operator: .and)
}
return columnMapping
.map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) }
.joined(operator: .and)
}
}
@@ -296,7 +309,7 @@ extension Association where OriginRowDecoder: MutablePersistableRecord {
.filter { db in
// Build a join condition: `association.recordId = record.id`
// We still need to replace `record.id` with the actual record id.
guard let joinCondition = try self.joinCondition(db)(recordAlias, associationAlias) else {
guard let joinExpression = try self.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) else {
fatalError("Can't request from record without join condition")
}
@@ -306,7 +319,7 @@ extension Association where OriginRowDecoder: MutablePersistableRecord {
let container = PersistenceContainer(record)
// Replace `record.id` with 123
return joinCondition.resolvedExpression(inContext: [recordAlias: container])
return joinExpression.resolvedExpression(inContext: [recordAlias: container])
}
// We just added a condition qualified with associationAlias. Don't
@@ -0,0 +1,469 @@
import Foundation
/// An AssociationAggregate is able to compute aggregated values from a
/// population of associated records.
///
/// For example:
///
/// struct Author: TableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// let bookCount = Author.books.count // AssociationAggregate<Author>
///
/// Association aggregates can be used in the `annotated(with:)` and
/// `having(_:)` request methods:
///
/// let request = Author.annotated(with: bookCount)
/// let request = Author.having(bookCount >= 10)
public struct AssociationAggregate<RowDecoder> {
let prepare: (QueryInterfaceRequest<RowDecoder>) -> (request: QueryInterfaceRequest<RowDecoder>, expression: SQLExpression)
var alias: String?
init(_ prepare: @escaping (QueryInterfaceRequest<RowDecoder>) -> (request: QueryInterfaceRequest<RowDecoder>, expression: SQLExpression)) {
self.prepare = prepare
}
}
extension AssociationAggregate {
/// Returns an aggregate that is selected in a column with the given name.
///
/// For example:
///
/// let aggregate = Author.books.count.aliased("foo")
/// let request = Author.annotated(with: aggregate)
/// if let row = try Row.fetchOne(db, request) {
/// let bookCount: Int = row["foo"]
/// }
public func aliased(_ name: String) -> AssociationAggregate<RowDecoder> {
var aggregate = self
aggregate.alias = name
return aggregate
}
/// Returns an aggregate that is selected in a column named like the given
/// coding key.
///
/// For example:
///
/// struct AuthorInfo: Decodable, FetchableRecord {
/// var author: Author
/// var bookCount: Int
///
/// static func fetchAll(_ db: Database) throws -> [AuthorInfo] {
/// let aggregate = Author.books.count.aliased(CodingKeys.bookCount)
/// let request = Author.annotated(with: aggregate)
/// return try AuthorInfo.fetchAll(db, request)
/// }
/// }
public func aliased(_ key: CodingKey) -> AssociationAggregate<RowDecoder> {
return aliased(key.stringValue)
}
}
// MARK: - Logical Operators (AND, OR, NOT)
/// :nodoc:
public prefix func ! <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = aggregate.prepare(request)
return (request: request, expression: !expression)
}
}
/// :nodoc:
public func && <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression && rExpression)
}
}
/// :nodoc:
public func && <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression && rhs)
}
}
/// :nodoc:
public func && <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs && expression)
}
}
/// :nodoc:
public func || <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression || rExpression)
}
}
/// :nodoc:
public func || <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression || rhs)
}
}
/// :nodoc:
public func || <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs || expression)
}
}
// MARK: - Egality and Identity Operators (=, <>, IS, IS NOT)
/// :nodoc:
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression == rExpression)
}
}
/// :nodoc:
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression == rhs)
}
}
/// :nodoc:
public func == <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs == expression)
}
}
/// :nodoc:
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression == rhs)
}
}
/// :nodoc:
public func == <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs == expression)
}
}
/// :nodoc:
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression != rExpression)
}
}
/// :nodoc:
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression != rhs)
}
}
/// :nodoc:
public func != <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs != expression)
}
}
/// :nodoc:
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression != rhs)
}
}
/// :nodoc:
public func != <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs != expression)
}
}
/// :nodoc:
public func === <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression === rExpression)
}
}
/// :nodoc:
public func === <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression === rhs)
}
}
/// :nodoc:
public func === <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs === expression)
}
}
/// :nodoc:
public func !== <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression !== rExpression)
}
}
/// :nodoc:
public func !== <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression !== rhs)
}
}
/// :nodoc:
public func !== <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs !== expression)
}
}
// MARK: - Comparison Operators (<, >, <=, >=)
/// :nodoc:
public func <= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression <= rExpression)
}
}
/// :nodoc:
public func <= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression <= rhs)
}
}
/// :nodoc:
public func <= <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs <= expression)
}
}
/// :nodoc:
public func < <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression < rExpression)
}
}
/// :nodoc:
public func < <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression < rhs)
}
}
/// :nodoc:
public func < <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs < expression)
}
}
/// :nodoc:
public func > <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression > rExpression)
}
}
/// :nodoc:
public func > <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression > rhs)
}
}
/// :nodoc:
public func > <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs > expression)
}
}
/// :nodoc:
public func >= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression >= rExpression)
}
}
/// :nodoc:
public func >= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression >= rhs)
}
}
/// :nodoc:
public func >= <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs >= expression)
}
}
// MARK: - Arithmetic Operators (+, -, *, /)
/// :nodoc:
public prefix func - <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = aggregate.prepare(request)
return (request: request, expression:-expression)
}
}
/// :nodoc:
public func + <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression + rExpression)
}
}
/// :nodoc:
public func + <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression + rhs)
}
}
/// :nodoc:
public func + <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs + expression)
}
}
/// :nodoc:
public func - <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression - rExpression)
}
}
/// :nodoc:
public func - <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression - rhs)
}
}
/// :nodoc:
public func - <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs - expression)
}
}
/// :nodoc:
public func * <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression * rExpression)
}
}
/// :nodoc:
public func * <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression * rhs)
}
}
/// :nodoc:
public func * <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs * expression)
}
}
/// :nodoc:
public func / <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression / rExpression)
}
}
/// :nodoc:
public func / <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression / rhs)
}
}
/// :nodoc:
public func / <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs / expression)
}
}
@@ -3,7 +3,7 @@ struct AssociationQuery {
var selection: [SQLSelectable]
var filterPromise: DatabasePromise<SQLExpression?>
var ordering: QueryOrdering
var joins: [AssociationJoin]
var joins: OrderedDictionary<String, AssociationJoin>
var alias: TableAlias? {
return source.alias
@@ -13,7 +13,7 @@ struct AssociationQuery {
extension AssociationQuery {
init(_ query: QueryInterfaceQuery) {
GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries")
GRDBPrecondition(query.groupByExpressions.isEmpty, "Can't join aggregated queries")
GRDBPrecondition(query.groupPromise == nil, "Can't join aggregated queries")
GRDBPrecondition(query.havingExpression == nil, "Can't join aggregated queries")
GRDBPrecondition(query.limit == nil, "Can't join limited queries")
@@ -59,9 +59,17 @@ extension AssociationQuery {
return query
}
func joining(_ join: AssociationJoin) -> AssociationQuery {
func appendingJoin(_ join: AssociationJoin, forKey key: String) -> AssociationQuery {
var query = self
query.joins.append(join)
if let existingJoin = query.joins.removeValue(forKey: key) {
guard let mergedJoin = existingJoin.merged(with: join) else {
// can't merge
fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.")
}
query.joins.append(value: mergedJoin, forKey: key)
} else {
query.joins.append(value: join, forKey: key)
}
return query
}
@@ -82,7 +90,7 @@ extension AssociationQuery {
query.selection = selection.map { $0.qualifiedSelectable(with: alias) }
query.filterPromise = filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) }
query.ordering = ordering.qualified(with: alias)
query.joins = joins.map { $0.finalizedJoin }
query.joins = joins.mapValues { $0.finalizedJoin }
return query
}
@@ -94,21 +102,21 @@ extension AssociationQuery {
aliases.append(alias)
}
return joins.reduce(into: aliases) {
$0.append(contentsOf: $1.finalizedAliases)
$0.append(contentsOf: $1.value.finalizedAliases)
}
}
/// precondition: self is the result of finalizedQuery
var finalizedSelection: [SQLSelectable] {
return joins.reduce(into: selection) {
$0.append(contentsOf: $1.finalizedSelection)
$0.append(contentsOf: $1.value.finalizedSelection)
}
}
/// precondition: self is the result of finalizedQuery
var finalizedOrdering: QueryOrdering {
return joins.reduce(ordering) {
$0.appending($1.finalizedOrdering)
$0.appending($1.value.finalizedOrdering)
}
}
@@ -120,10 +128,9 @@ extension AssociationQuery {
var endIndex = startIndex + selectionWidth
var scopes: [String: RowAdapter] = [:]
for join in joins {
if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [join.key]) {
GRDBPrecondition(scopes[join.key] == nil, "The association key \"\((keyPath + [join.key]).joined(separator: "."))\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.")
scopes[join.key] = joinAdapter
for (key, join) in joins {
if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [key]) {
scopes[key] = joinAdapter
endIndex = joinEndIndex
}
}
@@ -136,3 +143,51 @@ extension AssociationQuery {
return (adapter: adapter.addingScopes(scopes), endIndex: endIndex)
}
}
extension AssociationQuery {
/// Returns nil if queries can't be merged (conflict in source, joins...)
func merged(with other: AssociationQuery) -> AssociationQuery? {
guard let mergedSource = source.merged(with: other.source) else {
// can't merge
return nil
}
let mergedFilterPromise = filterPromise.map { (db, expression) in
let otherExpression = try other.filterPromise.resolve(db)
let expressions = [expression, otherExpression].compactMap { $0 }
if expressions.isEmpty {
return nil
}
return expressions.joined(operator: .and)
}
var mergedJoins: OrderedDictionary<String, AssociationJoin> = [:]
for (key, join) in joins {
if let otherJoin = other.joins[key] {
guard let mergedJoin = join.merged(with: otherJoin) else {
// can't merge
return nil
}
mergedJoins.append(value: mergedJoin, forKey: key)
} else {
mergedJoins.append(value: join, forKey: key)
}
}
for (key, join) in other.joins where mergedJoins[key] == nil {
mergedJoins.append(value: join, forKey: key)
}
// replace selection unless empty
let mergedSelection = other.selection.isEmpty ? selection : other.selection
// replace ordering unless empty
let mergedOrdering = other.ordering.isEmpty ? ordering : other.ordering
return AssociationQuery(
source: mergedSource,
selection: mergedSelection,
filterPromise: mergedFilterPromise,
ordering: mergedOrdering,
joins: mergedJoins)
}
}
@@ -42,9 +42,8 @@ extension AssociationRequest {
{
let join = AssociationJoin(
joinOperator: joinOperator,
query: association.request.query,
key: association.key,
joinConditionPromise: DatabasePromise(association.joinCondition))
return AssociationRequest(query: query.joining(join))
joinCondition: association.joinCondition,
query: association.request.query)
return AssociationRequest(query: query.appendingJoin(join, forKey: association.key))
}
}
@@ -59,8 +59,6 @@
///
/// See ForeignKey for more information.
public struct BelongsToAssociation<Origin, Destination>: Association {
fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest
/// :nodoc:
public typealias OriginRowDecoder = Origin
@@ -69,6 +67,9 @@ public struct BelongsToAssociation<Origin, Destination>: Association {
public var key: String
/// :nodoc:
public let joinCondition: JoinCondition
/// :nodoc:
public var request: AssociationRequest<Destination>
@@ -78,11 +79,6 @@ public struct BelongsToAssociation<Origin, Destination>: Association {
return association
}
/// :nodoc:
public func joinCondition(_ db: Database) throws -> JoinCondition {
return try joinConditionRequest.fetch(db)
}
/// :nodoc:
public func mapRequest(_ transform: (AssociationRequest<Destination>) -> AssociationRequest<Destination>) -> BelongsToAssociation<Origin, Destination> {
var association = self
@@ -166,13 +162,13 @@ extension TableRecord {
destinationTable: Destination.databaseTableName,
foreignKey: foreignKey)
let joinConditionRequest = ForeignKeyJoinConditionRequest(
let joinCondition = JoinCondition(
foreignKeyRequest: foreignKeyRequest,
originIsLeft: true)
return BelongsToAssociation(
joinConditionRequest: joinConditionRequest,
key: key ?? Destination.databaseTableName,
joinCondition: joinCondition,
request: AssociationRequest(Destination.all()))
}
}
@@ -5,7 +5,7 @@
///
/// When the schema does not define any foreign key, we can still infer complete
/// mappings from partial information and primary keys.
struct ForeignKeyRequest {
struct ForeignKeyRequest: Equatable {
let originTable: String
let destinationTable: String
let originColumns: [String]?
@@ -59,8 +59,6 @@
///
/// See ForeignKey for more information.
public struct HasManyAssociation<Origin, Destination>: Association {
fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest
/// :nodoc:
public typealias OriginRowDecoder = Origin
@@ -69,6 +67,9 @@ public struct HasManyAssociation<Origin, Destination>: Association {
public var key: String
/// :nodoc:
public let joinCondition: JoinCondition
/// :nodoc:
public var request: AssociationRequest<Destination>
@@ -78,11 +79,6 @@ public struct HasManyAssociation<Origin, Destination>: Association {
return association
}
/// :nodoc:
public func joinCondition(_ db: Database) throws -> JoinCondition {
return try joinConditionRequest.fetch(db)
}
/// :nodoc:
public func mapRequest(_ transform: (AssociationRequest<Destination>) -> AssociationRequest<Destination>) -> HasManyAssociation<Origin, Destination> {
var association = self
@@ -97,6 +93,95 @@ extension HasManyAssociation: TableRequest where Destination: TableRecord {
public var databaseTableName: String { return Destination.databaseTableName }
}
extension HasManyAssociation where Origin: TableRecord, Destination: TableRecord {
private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate<Origin> {
return AssociationAggregate { request in
let tableAlias = TableAlias()
let request = request
.joining(optional: self.aliased(tableAlias))
.groupByPrimaryKey()
let expression = tableAlias[expression]
return (request: request, expression: expression)
}
}
/// The number of associated records.
///
/// For example:
///
/// Team.annotated(with: Team.players.count())
public var count: AssociationAggregate<Origin> {
return makeAggregate(SQLExpressionCountDistinct(Column.rowID)).aliased("\(key)Count")
}
/// An aggregate that is true if there exists no associated records.
///
/// For example:
///
/// Team.having(Team.players.isEmpty())
/// Team.having(!Team.players.isEmpty())
/// Team.having(Team.players.isEmpty() == false)
public var isEmpty: AssociationAggregate<Origin> {
return makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID)))
}
/// The average value of the given expression in associated records.
///
/// For example:
///
/// Team.annotated(with: Team.players.average(Column("score")))
public func average(_ expression: SQLExpressible) -> AssociationAggregate<Origin> {
let aggregate = makeAggregate(SQLExpressionFunction(.avg, arguments: expression))
if let column = expression as? ColumnExpression {
return aggregate.aliased("average\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// The maximum value of the given expression in associated records.
///
/// For example:
///
/// Team.annotated(with: Team.players.max(Column("score")))
public func max(_ expression: SQLExpressible) -> AssociationAggregate<Origin> {
let aggregate = makeAggregate(SQLExpressionFunction(.max, arguments: expression))
if let column = expression as? ColumnExpression {
return aggregate.aliased("max\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// The minimum value of the given expression in associated records.
///
/// For example:
///
/// Team.annotated(with: Team.players.min(Column("score")))
public func min(_ expression: SQLExpressible) -> AssociationAggregate<Origin> {
let aggregate = makeAggregate(SQLExpressionFunction(.min, arguments: expression))
if let column = expression as? ColumnExpression {
return aggregate.aliased("min\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// The sum of the given expression in associated records.
///
/// For example:
///
/// Team.annotated(with: Team.players.min(Column("score")))
public func sum(_ expression: SQLExpressible) -> AssociationAggregate<Origin> {
let aggregate = makeAggregate(SQLExpressionFunction(.sum, arguments: expression))
if let column = expression as? ColumnExpression {
return aggregate.aliased("\(key)\(column.name.uppercasingFirstCharacter)Sum")
} else {
return aggregate
}
}
}
extension TableRecord {
/// Creates a "Has many" association between Self and the
/// destination type.
@@ -166,13 +251,13 @@ extension TableRecord {
destinationTable: databaseTableName,
foreignKey: foreignKey)
let joinConditionRequest = ForeignKeyJoinConditionRequest(
let joinCondition = JoinCondition(
foreignKeyRequest: foreignKeyRequest,
originIsLeft: false)
return HasManyAssociation(
joinConditionRequest: joinConditionRequest,
key: key ?? Destination.databaseTableName,
joinCondition: joinCondition,
request: AssociationRequest(Destination.all()))
}
}
@@ -61,8 +61,6 @@
///
/// See ForeignKey for more information.
public struct HasOneAssociation<Origin, Destination> : Association {
fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest
/// :nodoc:
public typealias OriginRowDecoder = Origin
@@ -71,6 +69,9 @@ public struct HasOneAssociation<Origin, Destination> : Association {
public var key: String
/// :nodoc:
public let joinCondition: JoinCondition
/// :nodoc:
public var request: AssociationRequest<Destination>
@@ -80,11 +81,6 @@ public struct HasOneAssociation<Origin, Destination> : Association {
return association
}
/// :nodoc:
public func joinCondition(_ db: Database) throws -> JoinCondition {
return try joinConditionRequest.fetch(db)
}
/// :nodoc:
public func mapRequest(_ transform: (AssociationRequest<Destination>) -> AssociationRequest<Destination>) -> HasOneAssociation<Origin, Destination> {
var association = self
@@ -168,13 +164,13 @@ extension TableRecord {
destinationTable: databaseTableName,
foreignKey: foreignKey)
let joinConditionRequest = ForeignKeyJoinConditionRequest(
let joinCondition = JoinCondition(
foreignKeyRequest: foreignKeyRequest,
originIsLeft: false)
return HasOneAssociation(
joinConditionRequest: joinConditionRequest,
key: key ?? Destination.databaseTableName,
joinCondition: joinCondition,
request: AssociationRequest(Destination.all()))
}
}
+92 -28
View File
@@ -21,28 +21,28 @@ struct QueryInterfaceQuery {
var selection: [SQLSelectable]
var isDistinct: Bool
var filterPromise: DatabasePromise<SQLExpression?>
var groupByExpressions: [SQLExpression]
var groupPromise: DatabasePromise<[SQLExpression]>?
var ordering: QueryOrdering
var havingExpression: SQLExpression?
var limit: SQLLimit?
var joins: [AssociationJoin]
var joins: OrderedDictionary<String, AssociationJoin>
init(
source: SQLSource,
selection: [SQLSelectable] = [],
isDistinct: Bool = false,
filterPromise: DatabasePromise<SQLExpression?> = DatabasePromise(value: nil),
groupByExpressions: [SQLExpression] = [],
groupPromise: DatabasePromise<[SQLExpression]>? = nil,
ordering: QueryOrdering = QueryOrdering(),
havingExpression: SQLExpression? = nil,
limit: SQLLimit? = nil,
joins: [AssociationJoin] = [])
joins: OrderedDictionary<String, AssociationJoin> = [:])
{
self.source = source
self.selection = selection
self.isDistinct = isDistinct
self.filterPromise = filterPromise
self.groupByExpressions = groupByExpressions
self.groupPromise = groupPromise
self.ordering = ordering
self.havingExpression = havingExpression
self.limit = limit
@@ -70,6 +70,12 @@ extension QueryInterfaceQuery {
return query
}
func annotated(with selection: [SQLSelectable]) -> QueryInterfaceQuery {
var query = self
query.selection.append(contentsOf: selection)
return query
}
func distinct() -> QueryInterfaceQuery {
var query = self
query.isDistinct = true
@@ -88,9 +94,9 @@ extension QueryInterfaceQuery {
return query
}
func group(_ expressions: [SQLExpressible]) -> QueryInterfaceQuery {
func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceQuery {
var query = self
query.groupByExpressions = expressions.map { $0.sqlExpression }
query.groupPromise = DatabasePromise { db in try expressions(db).map { $0.sqlExpression } }
return query
}
@@ -130,9 +136,17 @@ extension QueryInterfaceQuery {
return query
}
func joining(_ join: AssociationJoin) -> QueryInterfaceQuery {
func appendingJoin(_ join: AssociationJoin, forKey key: String) -> QueryInterfaceQuery {
var query = self
query.joins.append(join)
if let existingJoin = query.joins.removeValue(forKey: key) {
guard let mergedJoin = existingJoin.merged(with: join) else {
// can't merge
fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.")
}
query.joins.append(value: mergedJoin, forKey: key)
} else {
query.joins.append(value: join, forKey: key)
}
return query
}
@@ -152,11 +166,11 @@ extension QueryInterfaceQuery {
query.source = source.qualified(with: alias)
query.selection = query.selection.map { $0.qualifiedSelectable(with: alias) }
query.filterPromise = query.filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) }
query.groupByExpressions = query.groupByExpressions.map { $0.qualifiedExpression(with: alias) }
query.groupPromise = query.groupPromise?.map { [alias] (_, exprs) in exprs.map { $0.qualifiedExpression(with: alias) } }
query.ordering = query.ordering.qualified(with: alias)
query.havingExpression = query.havingExpression?.qualifiedExpression(with: alias)
query.joins = query.joins.map { $0.finalizedJoin }
query.joins = query.joins.mapValues { $0.finalizedJoin }
return query
}
@@ -168,21 +182,21 @@ extension QueryInterfaceQuery {
aliases.append(alias)
}
return joins.reduce(into: aliases) {
$0.append(contentsOf: $1.finalizedAliases)
$0.append(contentsOf: $1.value.finalizedAliases)
}
}
/// precondition: self is the result of finalizedQuery
var finalizedSelection: [SQLSelectable] {
return joins.reduce(into: selection) {
$0.append(contentsOf: $1.finalizedSelection)
$0.append(contentsOf: $1.value.finalizedSelection)
}
}
/// precondition: self is the result of finalizedQuery
var finalizedOrdering: QueryOrdering {
return joins.reduce(ordering) {
$0.appending($1.finalizedOrdering)
$0.appending($1.value.finalizedOrdering)
}
}
@@ -198,10 +212,9 @@ extension QueryInterfaceQuery {
var endIndex = selectionWidth
var scopes: [String: RowAdapter] = [:]
for join in joins {
if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: [join.key]) {
GRDBPrecondition(scopes[join.key] == nil, "The association key \"\(join.key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.")
scopes[join.key] = joinAdapter
for (key, join) in joins {
if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: [key]) {
scopes[key] = joinAdapter
endIndex = joinEndIndex
}
}
@@ -230,7 +243,7 @@ extension QueryInterfaceQuery {
sql += try " FROM " + source.sourceSQL(db, &context)
for join in joins {
for (_, join) in joins {
sql += try " " + join.joinSQL(db, &context, leftAlias: alias!, isRequiredAllowed: true)
}
@@ -238,9 +251,9 @@ extension QueryInterfaceQuery {
sql += " WHERE " + filter.expressionSQL(&context)
}
if !groupByExpressions.isEmpty {
if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty {
sql += " GROUP BY "
sql += groupByExpressions.map { $0.expressionSQL(&context) }
sql += groupExpressions.map { $0.expressionSQL(&context) }
.joined(separator: ", ")
}
@@ -271,7 +284,7 @@ extension QueryInterfaceQuery {
/// precondition: self is the result of finalizedQuery
func makeDeleteStatement(_ db: Database) throws -> UpdateStatement {
guard groupByExpressions.isEmpty else {
if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty {
// Programmer error
fatalError("Can't delete query with GROUP BY clause")
}
@@ -363,7 +376,7 @@ extension QueryInterfaceQuery {
}
private var countQuery: QueryInterfaceQuery {
guard groupByExpressions.isEmpty && limit == nil else {
guard groupPromise == nil && limit == nil else {
// SELECT ... GROUP BY ...
// SELECT ... LIMIT ...
return trivialCountQuery
@@ -458,10 +471,9 @@ enum AssociationJoinOperator {
struct AssociationJoin {
var joinOperator: AssociationJoinOperator
var joinCondition: JoinCondition
var query: AssociationQuery
var key: String
var joinConditionPromise: DatabasePromise<JoinCondition>
var finalizedJoin: AssociationJoin {
var join = self
join.query = query.finalizedQuery
@@ -504,19 +516,45 @@ struct AssociationJoin {
let rightAlias = query.alias!
let filters = try [
joinConditionPromise.resolve(db)(leftAlias, rightAlias),
joinCondition.sqlExpression(db, leftAlias: leftAlias, rightAlias: rightAlias),
query.filterPromise.resolve(db)
].compactMap { $0 }
if !filters.isEmpty {
sql += " ON " + filters.joined(operator: .and).expressionSQL(&context)
}
for join in query.joins {
for (_, join) in query.joins {
sql += try " " + join.joinSQL(db, &context, leftAlias: rightAlias, isRequiredAllowed: isRequiredAllowed)
}
return sql
}
/// Returns nil if joins can't be merged (conflict in condition, query...)
func merged(with other: AssociationJoin) -> AssociationJoin? {
guard joinCondition == other.joinCondition else {
// can't merge
return nil
}
guard let mergedQuery = query.merged(with: other.query) else {
// can't merge
return nil
}
let mergedJoinOperator: AssociationJoinOperator
switch (joinOperator, other.joinOperator) {
case (.required, _), (_, .required):
mergedJoinOperator = .required
default:
mergedJoinOperator = .optional
}
return AssociationJoin(
joinOperator: mergedJoinOperator,
joinCondition: joinCondition,
query: mergedQuery)
}
}
// MARK: - SQLSource
@@ -561,6 +599,32 @@ enum SQLSource {
return .query(query.qualified(with: alias))
}
}
/// Returns nil if sources can't be merged (conflict in tables, aliases...)
func merged(with other: SQLSource) -> SQLSource? {
switch (self, other) {
case let (.table(tableName: tableName, alias: alias), .table(tableName: otherTableName, alias: otherAlias)):
guard tableName == otherTableName else {
// can't merge
return nil
}
switch (alias, otherAlias) {
case (nil, nil):
return .table(tableName: tableName, alias: nil)
case let (alias?, nil), let (nil, alias?):
return .table(tableName: tableName, alias: alias)
case let (alias?, otherAlias?):
guard let mergedAlias = alias.merge(with: otherAlias) else {
// can't merge
return nil
}
return .table(tableName: tableName, alias: mergedAlias)
}
default:
// can't merge
return nil
}
}
}
struct SQLLimit {
@@ -5,10 +5,9 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
{
let join = AssociationJoin(
joinOperator: joinOperator,
query: association.request.query,
key: association.key,
joinConditionPromise: DatabasePromise(association.joinCondition))
return QueryInterfaceRequest(query: query.joining(join))
joinCondition: association.joinCondition,
query: association.request.query)
return QueryInterfaceRequest(query: query.appendingJoin(join, forKey: association.key))
}
// MARK: - Associations
@@ -40,6 +39,52 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
public func joining<A: Association>(required association: A) -> QueryInterfaceRequest<RowDecoder> where A.OriginRowDecoder == RowDecoder {
return joining(.required, association.select([]))
}
// MARK: - Association Aggregates
private func annotated(with aggregate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest<RowDecoder> {
let (request, expression) = aggregate.prepare(self)
if let alias = aggregate.alias {
return request.annotated(with: [expression.aliased(alias)])
} else {
return request.annotated(with: [expression])
}
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: Player.books.count)
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> QueryInterfaceRequest<RowDecoder> {
return annotated(with: aggregates)
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: [Player.books.count])
public func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> QueryInterfaceRequest<RowDecoder> {
return aggregates.reduce(self) { request, aggregate in
request.annotated(with: aggregate)
}
}
/// Creates a request which appends the provided aggregate *predicate* to
/// the eventual set of already applied predicates.
///
/// // SELECT player.*
/// // FROM player LEFT JOIN book ...
/// // HAVING COUNT(DISTINCT book.rowid) = 0
/// var request = Player.all()
/// request = request.having(Player.books.isEmpty)
public func having(_ predicate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest<RowDecoder> {
let (request, expression) = predicate.prepare(self)
return request.having(expression)
}
}
extension MutablePersistableRecord {
@@ -92,4 +137,39 @@ extension TableRecord {
public static func joining<A: Association>(required association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self {
return all().joining(required: association)
}
// MARK: - Association Aggregates
/// Creates a request with *aggregates* appended to the selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.annotated(with: Player.books.count)
public static func annotated(with aggregates: AssociationAggregate<Self>...) -> QueryInterfaceRequest<Self> {
return all().annotated(with: aggregates)
}
/// Creates a request with *aggregates* appended to the selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.annotated(with: [Player.books.count])
public static func annotated(with aggregates: [AssociationAggregate<Self>]) -> QueryInterfaceRequest<Self> {
return all().annotated(with: aggregates)
}
/// Creates a request with the provided aggregate *predicate*.
///
/// // SELECT player.*
/// // FROM player LEFT JOIN book ...
/// // HAVING COUNT(DISTINCT book.rowid) = 0
/// var request = Player.all()
/// request = request.having(Player.books.isEmpty)
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public static func having(_ predicate: AssociationAggregate<Self>) -> QueryInterfaceRequest<Self> {
return all().having(predicate)
}
}
@@ -47,7 +47,7 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest {
// MARK: Request Derivation
/// Creates a request with a new set of selected columns.
/// Creates a request which selects *selection*.
///
/// // SELECT id, email FROM player
/// var request = Player.all()
@@ -63,6 +63,53 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest {
return QueryInterfaceRequest(query: query.select(selection))
}
/// Creates a request which selects *selection*, and fetches values of
/// type *type*.
///
/// try dbQueue.read { db in
/// // SELECT max(score) FROM player
/// let request = Player.all().select([max(Column("score"))], as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
return QueryInterfaceRequest<RowDecoder>(query: query.select(selection))
}
/// Creates a request which selects *selection*, and fetches values of
/// type *type*.
///
/// try dbQueue.read { db in
/// // SELECT max(score) FROM player
/// let request = Player.all().select(max(Column("score")), as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public func select<RowDecoder>(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
return select(selection, as: type)
}
/// Creates a request which selects *sql*, and fetches values of
/// type *type*.
///
/// try dbQueue.read { db in
/// // SELECT max(score) FROM player
/// let request = Player.all().select(sql: "max(score)", as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public func select<RowDecoder>(sql: String, arguments: StatementArguments? = nil, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
return select(SQLSelectionLiteral(sql, arguments: arguments), as: type)
}
/// Creates a request which appends *selection*.
///
/// // SELECT id, email, name FROM player
/// var request = Player.all()
/// request = request
/// .select([Column("id"), Column("email")])
/// .annotated(with: [Column("name")])
public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest<T> {
return QueryInterfaceRequest(query: query.annotated(with: selection))
}
/// Creates a request which returns distinct rows.
///
/// // SELECT DISTINCT * FROM player
@@ -86,8 +133,8 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest {
return QueryInterfaceRequest(query: query.filter(predicate))
}
/// Creates a request grouped according to *expressions*.
public func group(_ expressions: [SQLExpressible]) -> QueryInterfaceRequest<T> {
/// Creates a request grouped according to *expressions promise*.
public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest<T> {
return QueryInterfaceRequest(query: query.group(expressions))
}
@@ -256,6 +303,42 @@ extension TableRecord {
return all().select(sql: sql, arguments: arguments)
}
/// Creates a request which selects *selection*, and fetches values of
/// type *type*.
///
/// try dbQueue.read { db in
/// // SELECT max(score) FROM player
/// let request = Player.select([max(Column("score"))], as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public static func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
return all().select(selection, as: type)
}
/// Creates a request which selects *selection*, and fetches values of
/// type *type*.
///
/// try dbQueue.read { db in
/// // SELECT max(score) FROM player
/// let request = Player.select(max(Column("score")), as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public static func select<RowDecoder>(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
return all().select(selection, as: type)
}
/// Creates a request which selects *sql*, and fetches values of
/// type *type*.
///
/// try dbQueue.read { db in
/// // SELECT max(score) FROM player
/// let request = Player.select(sql: "max(score)", as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public static func select<RowDecoder>(sql: String, arguments: StatementArguments? = nil, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
return all().select(sql: sql, arguments: arguments, as: type)
}
/// Creates a request with the provided *predicate*.
///
/// // SELECT * FROM player WHERE email = 'arthur@example.com'
+7 -3
View File
@@ -1,9 +1,6 @@
/// QueryOrdering provides the order clause to QueryInterfaceQuery
/// and AssociationQuery.
struct QueryOrdering {
private var elements: [Element] = []
var isReversed: Bool
private enum Element {
case orderingTerms((Database) throws -> [SQLOrderingTerm])
case queryOrdering(QueryOrdering)
@@ -36,6 +33,13 @@ struct QueryOrdering {
}
}
private var elements: [Element] = []
var isReversed: Bool
var isEmpty: Bool {
return elements.isEmpty
}
private init(elements: [Element], isReversed: Bool) {
self.elements = elements
self.isReversed = isReversed
+49 -5
View File
@@ -1,8 +1,12 @@
// MARK: - SelectionRequest
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The protocol for all requests that can refine their selection.
///
/// :nodoc:
public protocol SelectionRequest {
/// Creates a request with a new set of selected columns.
/// Creates a request which selects *selection*.
///
/// // SELECT id, email FROM player
/// var request = Player.all()
@@ -17,8 +21,9 @@ public protocol SelectionRequest {
func select(_ selection: [SQLSelectable]) -> Self
}
/// :nodoc:
extension SelectionRequest {
/// Creates a request with a new set of selected columns.
/// Creates a request which selects *selection*.
///
/// // SELECT id, email FROM player
/// var request = Player.all()
@@ -34,7 +39,7 @@ extension SelectionRequest {
return select(selection)
}
/// Creates a request with a new set of selected columns.
/// Creates a request which selects *sql*.
///
/// // SELECT id, email FROM player
/// var request = Player.all()
@@ -53,7 +58,11 @@ extension SelectionRequest {
// MARK: - FilteredRequest
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The protocol for all requests that can be filtered.
///
/// :nodoc:
public protocol FilteredRequest {
/// Creates a request with the provided *predicate promise* added to the
/// eventual set of already applied predicates.
@@ -64,6 +73,7 @@ public protocol FilteredRequest {
func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self
}
/// :nodoc:
extension FilteredRequest {
/// Creates a request with the provided *predicate* added to the
/// eventual set of already applied predicates.
@@ -97,7 +107,11 @@ extension FilteredRequest {
// MARK: - TableRequest {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The protocol for all requests that feed from a database table
///
/// :nodoc:
public protocol TableRequest {
/// The name of the database table
var databaseTableName: String { get }
@@ -122,6 +136,7 @@ public protocol TableRequest {
func aliased(_ alias: TableAlias) -> Self
}
/// :nodoc:
extension TableRequest where Self: FilteredRequest {
/// Creates a request with the provided primary key *predicate*.
@@ -202,6 +217,7 @@ extension TableRequest where Self: FilteredRequest {
}
}
/// :nodoc:
extension TableRequest where Self: OrderedRequest {
/// Creates a request ordered by primary key.
public func orderByPrimaryKey() -> Self {
@@ -212,19 +228,40 @@ extension TableRequest where Self: OrderedRequest {
}
}
/// :nodoc:
extension TableRequest where Self: AggregatingRequest {
/// Creates a request grouped by primary key.
public func groupByPrimaryKey() -> Self {
let tableName = self.databaseTableName
return group { db in
try db.primaryKey(tableName).columns.map { Column($0) }
}
}
}
// MARK: - AggregatingRequest
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The protocol for all requests that can aggregate.
///
/// :nodoc:
public protocol AggregatingRequest {
/// Creates a request grouped according to *expressions*.
func group(_ expressions: [SQLExpressible]) -> Self
/// Creates a request grouped according to *expressions promise*.
func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self
/// Creates a request with the provided *predicate* added to the
/// eventual set of already applied predicates.
func having(_ predicate: SQLExpressible) -> Self
}
/// :nodoc:
extension AggregatingRequest {
/// Creates a request grouped according to *expressions*.
public func group(_ expressions: [SQLExpressible]) -> Self {
return group { _ in expressions }
}
/// Creates a request grouped according to *expressions*.
public func group(_ expressions: SQLExpressible...) -> Self {
return group(expressions)
@@ -254,7 +291,11 @@ extension AggregatingRequest {
// MARK: - OrderedRequest
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The protocol for all requests that be ordered.
///
/// :nodoc:
public protocol OrderedRequest {
/// Creates a request with the provided *orderings promise*.
///
@@ -285,6 +326,7 @@ public protocol OrderedRequest {
func reversed() -> Self
}
/// :nodoc:
extension OrderedRequest {
/// Creates a request with the provided *orderings*.
///
@@ -352,6 +394,8 @@ extension OrderedRequest {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The base protocol for all requests that can be refined.
///
/// :nodoc:
public protocol DerivableRequest: SelectionRequest, FilteredRequest, OrderedRequest {
associatedtype RowDecoder
}
@@ -7,6 +7,8 @@
///
/// // SELECT * FROM player WHERE email = 'arthur@example.com' COLLATE NOCASE
/// Player.filter(email == "arthur@example.com")
///
/// :nodoc:
public struct SQLCollatedExpression {
/// The tainted expression
public let expression: SQLExpression
@@ -48,6 +50,7 @@ public struct SQLCollatedExpression {
}
}
/// :nodoc:
extension SQLCollatedExpression : SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
+1
View File
@@ -21,6 +21,7 @@ public protocol SQLCollection {
// MARK: Default Implementations
/// :nodoc:
extension SQLCollection {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -30,7 +30,7 @@ extension SQLExpression {
///
/// SQLExpressionLiteral("1 + 2")
///
/// The SQL literal may contain `?` and colon-prefixed tokens:
/// The SQL literal may contain `?` and colon-prefixed arguments:
///
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
/// SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
@@ -42,7 +42,7 @@ public struct SQLExpressionLiteral : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Eventual arguments that feed the `?` and colon-prefixed tokens in the
/// Eventual arguments that feed the `?` and colon-prefixed arguments in the
/// SQL literal
public let arguments: StatementArguments?
@@ -121,20 +121,6 @@ public struct SQLUnaryOperator : Hashable {
self.sql = sql
self.needsRightSpace = needsRightSpace
}
/// The hash value
///
/// :nodoc:
public var hashValue: Int {
return sql.hashValue
}
/// Equality operator
///
/// :nodoc:
public static func == (lhs: SQLUnaryOperator, rhs: SQLUnaryOperator) -> Bool {
return lhs.sql == rhs.sql
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -227,15 +213,17 @@ public struct SQLBinaryOperator : Hashable {
return SQLBinaryOperator(negatedSQL, negated: sql)
}
/// The hash value
#if !swift(>=4.2)
/// :nodoc:
public var hashValue: Int {
return sql.hashValue
return sql.hashValue ^ (negatedSQL?.hashValue ?? 0)
}
/// Equality operator
/// :nodoc:
public static func == (lhs: SQLBinaryOperator, rhs: SQLBinaryOperator) -> Bool {
return lhs.sql == rhs.sql
return lhs.sql == rhs.sql && lhs.negatedSQL == rhs.negatedSQL
}
#endif
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -728,6 +716,42 @@ struct SQLExpressionCountDistinct : SQLExpression {
}
}
// MARK: - SQLExpressionIsEmpty
/// This one helps generating `COUNT(...) = 0` or `COUNT(...) > 0` while letting
/// the user using the not `!` logical operator, or comparisons with booleans
/// such as `== true` or `== false`.
struct SQLExpressionIsEmpty : SQLExpression {
var countExpression: SQLExpression
var isEmpty: Bool
// countExpression should be a counting expression
init(_ countExpression: SQLExpression, isEmpty: Bool = true) {
self.countExpression = countExpression
self.isEmpty = isEmpty
}
var negated: SQLExpression {
return SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty)
}
func expressionSQL(_ context: inout SQLGenerationContext) -> String {
if isEmpty {
return "(" + countExpression.expressionSQL(&context) + " = 0)"
} else {
return "(" + countExpression.expressionSQL(&context) + " > 0)"
}
}
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
return SQLExpressionIsEmpty(countExpression.qualifiedExpression(with: alias), isEmpty: isEmpty)
}
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
return SQLExpressionIsEmpty(countExpression.resolvedExpression(inContext: context), isEmpty: isEmpty)
}
}
// MARK: - TableMatchExpression
struct TableMatchExpression: SQLExpression {
+44 -3
View File
@@ -1,5 +1,9 @@
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLGenerationContext is responsible for preventing SQL injection and
/// disambiguating table names when GRDB generates SQL queries.
///
/// :nodoc:
public struct SQLGenerationContext {
private(set) var arguments: StatementArguments?
private var resolvedNames: [TableAlias: String]
@@ -176,15 +180,45 @@ public class TableAlias: Hashable {
func becomeProxy(of base: TableAlias) {
switch impl {
case .undefined(let userName):
case let .undefined(userName):
if let userName = userName {
// rename
assert(base.userName == nil || base.userName == userName)
base.setUserName(userName)
}
self.impl = .proxy(base)
case let .table(tableName: tableName, userName: userName):
assert(tableName == base.tableName)
if let userName = userName {
// rename
assert(base.userName == nil || base.userName == userName)
base.setUserName(userName)
}
self.impl = .proxy(base)
case let .proxy(selfBase):
selfBase.becomeProxy(of: base)
}
}
/// Returns nil if aliases can't be merged (conflict in tables, aliases...)
func merge(with other: TableAlias) -> TableAlias? {
let root = self.root
let otherRoot = other.root
switch (root.impl, otherRoot.impl) {
case let (.table(tableName: tableName, userName: userName), .table(tableName: otherTableName, userName: otherUserName)):
guard tableName == otherTableName else {
// can't merge
return nil
}
if let userName = userName, let otherUserName = otherUserName, userName != otherUserName {
// can't merge
return nil
}
root.becomeProxy(of: otherRoot)
return otherRoot
default:
// Likely a GRDB bug
fatalError("Not implemented")
// can't merge
return nil
}
}
@@ -231,10 +265,17 @@ public class TableAlias: Hashable {
return expression.qualifiedExpression(with: self)
}
#if swift(>=4.2)
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(root))
}
#else
/// :nodoc:
public var hashValue: Int {
return ObjectIdentifier(root).hashValue
}
#endif
/// :nodoc:
public static func == (lhs: TableAlias, rhs: TableAlias) -> Bool {
@@ -1,5 +1,6 @@
// MARK: - SQL Ordering Support
/// :nodoc:
extension SQLSpecificExpressible {
/// Returns a value that can be used as an argument to QueryInterfaceRequest.order()
@@ -20,6 +21,7 @@ extension SQLSpecificExpressible {
// MARK: - SQL Selection Support
/// :nodoc:
extension SQLSpecificExpressible {
/// Returns a value that can be used as an argument to QueryInterfaceRequest.select()
@@ -28,11 +30,19 @@ extension SQLSpecificExpressible {
public func aliased(_ name: String) -> SQLSelectable {
return SQLAliasedExpression(sqlExpression, name: name)
}
/// Returns a value that can be used as an argument to QueryInterfaceRequest.select()
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public func aliased(_ key: CodingKey) -> SQLSelectable {
return aliased(key.stringValue)
}
}
// MARK: - SQL Collations Support
/// :nodoc:
extension SQLSpecificExpressible {
/// Returns a collated expression.
@@ -146,6 +146,7 @@ public func sum(_ value: SQLSpecificExpressible) -> SQLExpression {
// MARK: - Swift String functions
/// :nodoc:
extension SQLSpecificExpressible {
/// Returns an SQL expression that applies the Swift's built-in
/// capitalized String property. It is NULL for non-String arguments.
@@ -178,6 +179,7 @@ extension SQLSpecificExpressible {
}
}
/// :nodoc:
extension SQLSpecificExpressible {
/// Returns an SQL expression that applies the Swift's built-in
/// localizedCapitalized String property. It is NULL for non-String arguments.
@@ -789,6 +789,7 @@ extension SQLBinaryOperator {
static let like = SQLBinaryOperator("LIKE")
}
/// :nodoc:
extension SQLSpecificExpressible {
/// An SQL expression with the `LIKE` SQL operator.
+24
View File
@@ -216,6 +216,30 @@ extension Database {
public func drop(index name: String) throws {
try execute("DROP INDEX \(name.quotedDatabaseIdentifier)")
}
/// Delete and recreate from scratch all indices that use this collation.
///
/// This method is useful when the definition of a collation sequence
/// has changed.
///
/// See https://www.sqlite.org/lang_reindex.html
///
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func reindex(collation: Database.CollationName) throws {
try execute("REINDEX \(collation.rawValue)")
}
/// Delete and recreate from scratch all indices that use this collation.
///
/// This method is useful when the definition of a collation sequence
/// has changed.
///
/// See https://www.sqlite.org/lang_reindex.html
///
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func reindex(collation: DatabaseCollation) throws {
try reindex(collation: Database.CollationName(collation.name))
}
}
/// The TableDefinition class lets you define table columns and constraints.
+422 -257
View File
@@ -1,275 +1,440 @@
private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
let decoder: RowDecoder
init(decoder: RowDecoder) {
self.decoder = decoder
}
var codingPath: [CodingKey] { return decoder.codingPath }
/// All the keys the `Decoder` has for this container.
///
/// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type.
var allKeys: [Key] {
let row = decoder.row
let columnNames = Set(row.columnNames)
let scopeNames = Set(row.scopesTree.names)
return columnNames.union(scopeNames).compactMap { Key(stringValue: $0) }
}
/// Returns whether the `Decoder` contains a value associated with the given key.
///
/// The value associated with the given key may be a null value as appropriate for the data format.
///
/// - parameter key: The key to search for.
/// - returns: Whether the `Decoder` has an entry for the given key.
func contains(_ key: Key) -> Bool {
let row = decoder.row
return row.hasColumn(key.stringValue) || (row.scopesTree[key.stringValue] != nil)
}
/// Decodes a null value for the given key.
///
/// - parameter key: The key that the decoded value is associated with.
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
func decodeNil(forKey key: Key) throws -> Bool {
let row = decoder.row
return row[key.stringValue] == nil && (row.scopesTree[key.stringValue] == nil)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return decoder.row[key.stringValue] }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return decoder.row[key.stringValue] }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return decoder.row[key.stringValue] }
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return decoder.row[key.stringValue] }
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return decoder.row[key.stringValue] }
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return decoder.row[key.stringValue] }
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return decoder.row[key.stringValue] }
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return decoder.row[key.stringValue] }
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return decoder.row[key.stringValue] }
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return decoder.row[key.stringValue] }
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return decoder.row[key.stringValue] }
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return decoder.row[key.stringValue] }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return decoder.row[key.stringValue] }
func decode(_ type: String.Type, forKey key: Key) throws -> String { return decoder.row[key.stringValue] }
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns nil if the container does not have a value
/// associated with key, or if the value is null. The difference between
/// these states can be distinguished with a contains(_:) call.
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable {
let row = decoder.row
// Column?
if row.hasColumn(key.stringValue) {
let dbValue: DatabaseValue = row[key.stringValue]
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
return type.fromDatabaseValue(dbValue) as! T?
} else if dbValue.isNull {
return nil
} else {
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
}
}
// Scope?
if let scopedRow = row.scopesTree[key.stringValue], scopedRow.containsNonNullValue {
if let type = T.self as? FetchableRecord.Type {
// Prefer FetchableRecord decoding over Decodable.
// This allows custom row decoding
return (type.init(row: scopedRow) as! T)
} else {
return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key]))
}
}
return nil
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
let row = decoder.row
// Column?
if row.hasColumn(key.stringValue) {
let dbValue: DatabaseValue = row[key.stringValue]
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
return type.fromDatabaseValue(dbValue) as! T
} else {
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
}
}
// Scope?
if let scopedRow = row.scopesTree[key.stringValue] {
if let type = T.self as? FetchableRecord.Type {
// Prefer FetchableRecord decoding over Decodable.
// This allows custom row decoding
return type.init(row: scopedRow) as! T
} else {
return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key]))
}
}
// Base row
if let type = T.self as? FetchableRecord.Type {
// Prefer FetchableRecord decoding over Decodable.
// This allows custom row decoding
return type.init(row: row) as! T
} else {
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
}
}
/// Returns the data stored for the given key as represented in a container keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - parameter key: The key that the nested container is associated with.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container.
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
fatalError("not implemented")
}
/// Returns the data stored for the given key as represented in an unkeyed container.
///
/// - parameter key: The key that the nested container is associated with.
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container.
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
throw DecodingError.typeMismatch(
UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
}
/// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key.
///
/// Equivalent to calling `superDecoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the default `super` key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the default `super` key.
public func superDecoder() throws -> Decoder {
return decoder
}
/// Returns a `Decoder` instance for decoding `super` from the container associated with the given key.
///
/// - parameter key: The key to decode `super` for.
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
public func superDecoder(forKey key: Key) throws -> Decoder {
return decoder
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension FetchableRecord where Self: Decodable {
public init(row: Row) {
let decoder = RowDecoder<Self>(row: row, codingPath: [])
try! self.init(from: decoder)
}
}
private struct RowSingleValueDecodingContainer: SingleValueDecodingContainer {
let row: Row
// MARK: - RowDecoder
/// The decoder that decodes a record from a database row
private struct RowDecoder<Record: FetchableRecord>: Decoder {
var row: Row
var codingPath: [CodingKey]
let column: CodingKey
/// Decodes a null value.
///
/// - returns: Whether the encountered value was null.
func decodeNil() -> Bool {
return row[column.stringValue] == nil
}
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode(_ type: Bool.Type) throws -> Bool { return row[column.stringValue] }
func decode(_ type: Int.Type) throws -> Int { return row[column.stringValue] }
func decode(_ type: Int8.Type) throws -> Int8 { return row[column.stringValue] }
func decode(_ type: Int16.Type) throws -> Int16 { return row[column.stringValue] }
func decode(_ type: Int32.Type) throws -> Int32 { return row[column.stringValue] }
func decode(_ type: Int64.Type) throws -> Int64 { return row[column.stringValue] }
func decode(_ type: UInt.Type) throws -> UInt { return row[column.stringValue] }
func decode(_ type: UInt8.Type) throws -> UInt8 { return row[column.stringValue] }
func decode(_ type: UInt16.Type) throws -> UInt16 { return row[column.stringValue] }
func decode(_ type: UInt32.Type) throws -> UInt32 { return row[column.stringValue] }
func decode(_ type: UInt64.Type) throws -> UInt64 { return row[column.stringValue] }
func decode(_ type: Float.Type) throws -> Float { return row[column.stringValue] }
func decode(_ type: Double.Type) throws -> Double { return row[column.stringValue] }
func decode(_ type: String.Type) throws -> String { return row[column.stringValue] }
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
return type.fromDatabaseValue(row[column.stringValue]) as! T
} else {
return try T(from: RowDecoder(row: row, codingPath: [column]))
}
}
}
private struct RowDecoder: Decoder {
let row: Row
init(row: Row, codingPath: [CodingKey]) {
self.row = row
self.codingPath = codingPath
}
// Decoder
let codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey : Any] { return [:] }
var userInfo: [CodingUserInfoKey: Any] { return Record.databaseDecodingUserInfo }
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
return KeyedDecodingContainer(RowKeyedDecodingContainer<Key>(decoder: self))
return KeyedDecodingContainer(KeyedContainer<Key>(decoder: self))
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
throw DecodingError.typeMismatch(
UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
fatalError("unkeyed decoding from database row is not supported")
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
// Asked for a value type: column name required
guard let codingKey = codingPath.last else {
throw DecodingError.typeMismatch(
RowDecoder.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "single value decoding requires a coding key"))
guard let key = codingPath.last else {
fatalError("single value decoding from database row is not supported")
}
guard let index = row.index(ofColumn: key.stringValue) else {
// Don't use DecodingError.keyNotFound:
// We need to specifically recognize missing columns in order to
// provide correct feedback.
throw MissingColumnError(column: key.stringValue)
}
// TODO: test
// See DatabaseValueConversionErrorTests.testDecodableFetchableRecord2
return ColumnDecoder<Record>(row: row, columnIndex: index, codingPath: codingPath)
}
struct KeyedContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
let decoder: RowDecoder
var codingPath: [CodingKey] { return decoder.codingPath }
init(decoder: RowDecoder) {
self.decoder = decoder
}
var allKeys: [Key] {
let row = decoder.row
let columnNames = Set(row.columnNames)
let scopeNames = Set(row.scopesTree.names)
return columnNames.union(scopeNames).compactMap { Key(stringValue: $0) }
}
func contains(_ key: Key) -> Bool {
let row = decoder.row
return row.hasColumn(key.stringValue) || (row.scopesTree[key.stringValue] != nil)
}
func decodeNil(forKey key: Key) throws -> Bool {
let row = decoder.row
return row[key.stringValue] == nil && (row.scopesTree[key.stringValue] == nil)
}
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return decoder.row[key.stringValue] }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return decoder.row[key.stringValue] }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return decoder.row[key.stringValue] }
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return decoder.row[key.stringValue] }
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return decoder.row[key.stringValue] }
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return decoder.row[key.stringValue] }
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return decoder.row[key.stringValue] }
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return decoder.row[key.stringValue] }
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return decoder.row[key.stringValue] }
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return decoder.row[key.stringValue] }
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return decoder.row[key.stringValue] }
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return decoder.row[key.stringValue] }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return decoder.row[key.stringValue] }
func decode(_ type: String.Type, forKey key: Key) throws -> String { return decoder.row[key.stringValue] }
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable {
let row = decoder.row
let keyName = key.stringValue
// Column?
if let index = row.index(ofColumn: keyName) {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Date.self {
return Record.databaseDateDecodingStrategy.decodeIfPresent(fromRow: row, columnAtIndex: index) as! T?
} else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type {
return type.fastDecodeIfPresent(from: row, atUncheckedIndex: index) as! T?
} else if let type = T.self as? DatabaseValueConvertible.Type {
return type.decodeIfPresent(from: row, atUncheckedIndex: index) as! T?
} else if row.impl.hasNull(atUncheckedIndex: index) {
return nil
} else {
return try decode(type, fromRow: row, columnAtIndex: index, key: key)
}
}
// Scope? (beware left joins, and check if scoped row contains non-null values)
if let scopedRow = row.scopesTree[keyName], scopedRow.containsNonNullValue {
return try decode(type, fromRow: scopedRow, codingPath: codingPath + [key])
}
// Key is not a column, and not a scope.
return nil
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
let row = decoder.row
let keyName = key.stringValue
// Column?
if let index = row.index(ofColumn: keyName) {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Date.self {
return Record.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: index) as! T
} else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type {
return type.fastDecode(from: row, atUncheckedIndex: index) as! T
} else if let type = T.self as? DatabaseValueConvertible.Type {
return type.decode(from: row, atUncheckedIndex: index) as! T
} else {
return try decode(type, fromRow: row, columnAtIndex: index, key: key)
}
}
// Scope?
if let scopedRow = row.scopesTree[keyName] {
return try decode(type, fromRow: scopedRow, codingPath: codingPath + [key])
}
// Key is not a column, and not a scope.
//
// Should be throw an error? Well... The use case is the following:
//
// // SELECT book.*, author.* FROM book
// // JOIN author ON author.id = book.authorId
// let request = Book.including(required: Book.author)
//
// Rows loaded from this request don't have any "book" key:
//
// let row = try Row.fetchOne(db, request)!
// print(row.debugDescription)
// // ▿ [id:1 title:"Moby-Dick" authorId:2]
// // unadapted: [id:1 title:"Moby-Dick" authorId:2 id:2 name:"Melville"]
// // author: [id:2 name:"Melville"]
//
// And yet we have to decode the "book" key when we decode the
// BookInfo type below:
//
// struct BookInfo {
// var book: Book // <- decodes from the "book" key
// var author: Author
// }
// let infos = try BookInfos.fetchAll(db, request)
//
// Our current strategy is to assume that a missing key (such as
// "book", which is not the name of a column, and not the name of a
// scope) has to be decoded right from the base row.
//
// Yeah, there may be better ways to handle this.
return try decode(type, fromRow: row, codingPath: codingPath + [key])
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
fatalError("not implemented")
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
throw DecodingError.typeMismatch(
UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
}
func superDecoder() throws -> Decoder {
// Not sure
return decoder
}
func superDecoder(forKey key: Key) throws -> Decoder {
fatalError("not implemented")
}
// Helper methods
@inline(__always)
private func decode<T>(_ type: T.Type, fromRow row: Row, codingPath: [CodingKey]) throws -> T where T: Decodable {
if let type = T.self as? FetchableRecord.Type {
// Prefer FetchableRecord decoding over Decodable.
return type.init(row: row) as! T
} else {
do {
let decoder = RowDecoder(row: row, codingPath: codingPath)
return try T(from: decoder)
} catch let error as MissingColumnError {
// Support for DatabaseValueConversionErrorTests.testDecodableFetchableRecord2
fatalConversionError(
to: type,
from: nil,
conversionContext: ValueConversionContext(row).atColumn(error.column))
}
}
}
@inline(__always)
private func decode<T>(_ type: T.Type, fromRow row: Row, columnAtIndex index: Int, key: Key) throws -> T where T: Decodable {
do {
// This decoding will fail for types that decode from keyed
// or unkeyed containers, because we're decoding a single
// value here (string, int, double, data, null). If such an
// error happens, we'll switch to JSON decoding.
let columnDecoder = ColumnDecoder<Record>(
row: row,
columnIndex: index,
codingPath: codingPath + [key])
return try T(from: columnDecoder)
} catch is JSONRequiredError {
// Decode from JSON
guard let data = row.dataNoCopy(atIndex: index) else {
fatalConversionError(to: T.self, from: row[index], conversionContext: ValueConversionContext(row).atColumn(index))
}
return try Record
.databaseJSONDecoder(for: key.stringValue)
.decode(type.self, from: data)
}
}
return RowSingleValueDecodingContainer(row: row, codingPath: codingPath, column: codingKey)
}
}
extension FetchableRecord where Self: Decodable {
/// Initializes a record from `row`.
public init(row: Row) {
try! self.init(from: RowDecoder(row: row, codingPath: []))
// MARK: - ColumnDecoder
/// The decoder that decodes from a database column
private struct ColumnDecoder<Record: FetchableRecord>: Decoder {
var row: Row
var columnIndex: Int
var codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey: Any] { return Record.databaseDecodingUserInfo }
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
// We need to switch to JSON decoding
throw JSONRequiredError()
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
// We need to switch to JSON decoding
throw JSONRequiredError()
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
return self
}
}
extension ColumnDecoder: SingleValueDecodingContainer {
func decodeNil() -> Bool {
return row.hasNull(atIndex: columnIndex)
}
func decode(_ type: Bool.Type ) throws -> Bool { return row[columnIndex] }
func decode(_ type: Int.Type ) throws -> Int { return row[columnIndex] }
func decode(_ type: Int8.Type ) throws -> Int8 { return row[columnIndex] }
func decode(_ type: Int16.Type ) throws -> Int16 { return row[columnIndex] }
func decode(_ type: Int32.Type ) throws -> Int32 { return row[columnIndex] }
func decode(_ type: Int64.Type ) throws -> Int64 { return row[columnIndex] }
func decode(_ type: UInt.Type ) throws -> UInt { return row[columnIndex] }
func decode(_ type: UInt8.Type ) throws -> UInt8 { return row[columnIndex] }
func decode(_ type: UInt16.Type) throws -> UInt16 { return row[columnIndex] }
func decode(_ type: UInt32.Type) throws -> UInt32 { return row[columnIndex] }
func decode(_ type: UInt64.Type) throws -> UInt64 { return row[columnIndex] }
func decode(_ type: Float.Type ) throws -> Float { return row[columnIndex] }
func decode(_ type: Double.Type) throws -> Double { return row[columnIndex] }
func decode(_ type: String.Type) throws -> String { return row[columnIndex] }
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Date.self {
return Record.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: columnIndex) as! T
} else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type {
return type.fastDecode(from: row, atUncheckedIndex: columnIndex) as! T
} else if let type = T.self as? DatabaseValueConvertible.Type {
return type.decode(from: row, atUncheckedIndex: columnIndex) as! T
} else {
return try T(from: self)
}
}
}
/// The error that triggers JSON decoding
private struct JSONRequiredError: Error { }
/// The error for missing columns
private struct MissingColumnError: Error {
var column: String
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
fileprivate var iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
return formatter
}()
private extension DatabaseDateDecodingStrategy {
@inline(__always)
func decodeIfPresent(fromRow row: Row, columnAtIndex index: Int) -> Date? {
if let sqliteStatement = row.sqliteStatement {
return decodeIfPresent(
sqliteStatement: sqliteStatement,
index: Int32(index))
} else {
return decodeIfPresent(
from: row[index],
conversionContext: ValueConversionContext(row).atColumn(index))
}
}
@inline(__always)
func decode(fromRow row: Row, columnAtIndex index: Int) -> Date {
if let sqliteStatement = row.sqliteStatement {
return decode(
sqliteStatement: sqliteStatement,
index: Int32(index))
} else {
return decode(
from: row[index],
conversionContext: ValueConversionContext(row).atColumn(index))
}
}
@inline(__always)
func decode(sqliteStatement: SQLiteStatement, index: Int32) -> Date {
switch self {
case .deferredToDate:
return Date(sqliteStatement: sqliteStatement, index: index)
case .timeIntervalSinceReferenceDate:
let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index)
return Date(timeIntervalSinceReferenceDate: timeInterval)
case .timeIntervalSince1970:
let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index)
return Date(timeIntervalSince1970: timeInterval)
case .millisecondsSince1970:
let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index)
return Date(timeIntervalSince1970: timeInterval / 1000.0)
case .iso8601:
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
let string = String(sqliteStatement: sqliteStatement, index: index)
guard let date = iso8601Formatter.date(from: string) else {
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
}
return date
} else {
fatalError("ISO8601DateFormatter is unavailable on this platform.")
}
case .formatted(let formatter):
let string = String(sqliteStatement: sqliteStatement, index: index)
guard let date = formatter.date(from: string) else {
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
}
return date
case .custom(let format):
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
guard let date = format(dbValue) else {
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
}
return date
}
}
@inline(__always)
func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32) -> Date? {
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
return nil
}
return decode(sqliteStatement: sqliteStatement, index: index)
}
@inline(__always)
func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date {
if let date = dateFromDatabaseValue(dbValue) {
return date
} else {
fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext())
}
}
@inline(__always)
func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date? {
if dbValue.isNull {
return nil
} else if let date = dateFromDatabaseValue(dbValue) {
return date
} else {
fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext())
}
}
// Returns nil if decoding fails
@inline(__always)
private func dateFromDatabaseValue(_ dbValue: DatabaseValue) -> Date? {
switch self {
case .deferredToDate:
return Date.fromDatabaseValue(dbValue)
case .timeIntervalSinceReferenceDate:
return TimeInterval
.fromDatabaseValue(dbValue)
.map { Date(timeIntervalSinceReferenceDate: $0) }
case .timeIntervalSince1970:
return TimeInterval
.fromDatabaseValue(dbValue)
.map { Date(timeIntervalSince1970: $0) }
case .millisecondsSince1970:
return TimeInterval
.fromDatabaseValue(dbValue)
.map { Date(timeIntervalSince1970: $0 / 1000.0) }
case .iso8601:
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return String
.fromDatabaseValue(dbValue)
.flatMap { iso8601Formatter.date(from: $0) }
} else {
fatalError("ISO8601DateFormatter is unavailable on this platform.")
}
case .formatted(let formatter):
return String
.fromDatabaseValue(dbValue)
.flatMap { formatter.date(from: $0) }
case .custom(let format):
return format(dbValue)
}
}
}
+205 -30
View File
@@ -1,3 +1,4 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
@@ -24,46 +25,113 @@
/// FetchableRecord is adopted by Record.
public protocol FetchableRecord {
// MARK: - Row Decoding
/// Creates a record from `row`.
///
/// For performance reasons, the row argument may be reused during the
/// iteration of a fetch query. If you want to keep the row for later use,
/// make sure to store a copy: `self.row = row.copy()`.
init(row: Row)
// MARK: - Customizing the Format of Database Columns
/// When the FetchableRecord type also adopts the standard Decodable
/// protocol, you can use this dictionary to customize the decoding process
/// from database rows.
///
/// For example:
///
/// // A key that holds a decoder's name
/// let decoderName = CodingUserInfoKey(rawValue: "decoderName")!
///
/// // A FetchableRecord + Decodable record
/// struct Player: FetchableRecord, Decodable {
/// // Customize the decoder name when decoding a database row
/// static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "Database"]
///
/// init(from decoder: Decoder) throws {
/// // Print the decoder name
/// print(decoder.userInfo[decoderName])
/// ...
/// }
/// }
///
/// // prints "Database"
/// let player = try Player.fetchOne(db, ...)
///
/// // prints "JSON"
/// let decoder = JSONDecoder()
/// decoder.userInfo = [decoderName: "JSON"]
/// let player = try decoder.decode(Player.self, from: ...)
static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { get }
/// When the FetchableRecord type also adopts the standard Decodable
/// protocol, this method controls the decoding process of nested properties
/// from JSON database columns.
///
/// The default implementation returns a JSONDecoder with the
/// following properties:
///
/// - dataDecodingStrategy: .base64
/// - dateDecodingStrategy: .millisecondsSince1970
/// - nonConformingFloatDecodingStrategy: .throw
///
/// You can override those defaults:
///
/// struct Achievement: Decodable {
/// var name: String
/// var date: Date
/// }
///
/// struct Player: Decodable, FetchableRecord {
/// // stored in a JSON column
/// var achievements: [Achievement]
///
/// static func databaseJSONDecoder(for column: String) -> JSONDecoder {
/// let decoder = JSONDecoder()
/// decoder.dateDecodingStrategy = .iso8601
/// return decoder
/// }
/// }
static func databaseJSONDecoder(for column: String) -> JSONDecoder
/// When the FetchableRecord type also adopts the standard Decodable
/// protocol, this property controls the decoding of date properties.
///
/// Default value is .deferredToDate
///
/// For example:
///
/// struct Player: FetchableRecord, Decodable {
/// static let databaseDateDecodingStrategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970
///
/// var name: String
/// var registrationDate: Date // decoded from epoch timestamp
/// }
static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get }
}
/// A cursor of records. For example:
///
/// struct Player : FetchableRecord { ... }
/// try dbQueue.read { db in
/// let players: RecordCursor<Player> = try Player.fetchCursor(db, "SELECT * FROM player")
/// }
public final class RecordCursor<Record: FetchableRecord> : Cursor {
private let statement: SelectStatement
private let row: Row // Reused for performance
private let sqliteStatement: SQLiteStatement
private var done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
self.row = try Row(statement: statement).adapted(with: adapter, layout: statement)
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
extension FetchableRecord {
public static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] {
return [:]
}
/// :nodoc:
public func next() throws -> Record? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
return Record(row: row)
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
}
/// Returns a JSONDecoder with the following properties:
///
/// - dataDecodingStrategy: .base64
/// - dateDecodingStrategy: .millisecondsSince1970
/// - nonConformingFloatDecodingStrategy: .throw
public static func databaseJSONDecoder(for column: String) -> JSONDecoder {
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64
decoder.dateDecodingStrategy = .millisecondsSince1970
decoder.nonConformingFloatDecodingStrategy = .throw
return decoder
}
public static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy {
return .deferredToDate
}
}
@@ -241,6 +309,8 @@ extension FetchableRecord {
}
}
// MARK: - FetchRequest
extension FetchRequest where RowDecoder: FetchableRecord {
// MARK: Fetching Records
@@ -289,3 +359,108 @@ extension FetchRequest where RowDecoder: FetchableRecord {
return try RowDecoder.fetchOne(db, self)
}
}
// MARK: - RecordCursor
/// A cursor of records. For example:
///
/// struct Player : FetchableRecord { ... }
/// try dbQueue.read { db in
/// let players: RecordCursor<Player> = try Player.fetchCursor(db, "SELECT * FROM player")
/// }
public final class RecordCursor<Record: FetchableRecord> : Cursor {
private let statement: SelectStatement
private let row: Row // Reused for performance
private let sqliteStatement: SQLiteStatement
private var done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
self.row = try Row(statement: statement).adapted(with: adapter, layout: statement)
self.sqliteStatement = statement.sqliteStatement
statement.reset(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? statement.reset()
}
/// :nodoc:
public func next() throws -> Record? {
if done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
}
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
return Record(row: row)
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
}
}
}
// MARK: - DatabaseDateDecodingStrategy
/// DatabaseDateDecodingStrategy specifies how FetchableRecord types that also
/// adopt the standard Decodable protocol decode their date properties.
///
/// For example:
///
/// struct Player: FetchableRecord, Decodable {
/// static let databaseDateDecodingStrategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970
///
/// var name: String
/// var registrationDate: Date // decoded from epoch timestamp
/// }
public enum DatabaseDateDecodingStrategy {
/// The strategy that uses formatting from the Date structure.
///
/// It decodes numeric values as a nunber of seconds since Epoch
/// (midnight UTC on January 1st, 1970).
///
/// It decodes strings in the following formats, assuming UTC time zone.
/// Missing components are assumed to be zero:
///
/// - `YYYY-MM-DD`
/// - `YYYY-MM-DD HH:MM`
/// - `YYYY-MM-DD HH:MM:SS`
/// - `YYYY-MM-DD HH:MM:SS.SSS`
/// - `YYYY-MM-DDTHH:MM`
/// - `YYYY-MM-DDTHH:MM:SS`
/// - `YYYY-MM-DDTHH:MM:SS.SSS`
case deferredToDate
/// Decodes numeric values as a number of seconds between the date and
/// midnight UTC on 1 January 2001
case timeIntervalSinceReferenceDate
/// Decodes numeric values as a number of seconds between the date and
/// midnight UTC on 1 January 1970
case timeIntervalSince1970
/// Decodes numeric values as a number of milliseconds between the date and
/// midnight UTC on 1 January 1970
case millisecondsSince1970
/// Decodes dates according to the ISO 8601 standards
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
case iso8601
/// Decodes a String, according to the provided formatter
case formatted(DateFormatter)
/// Decodes according to the user-provided function.
///
/// If the database value does not contain a suitable value, the function
/// must return nil (GRDB will interpret this nil result as a conversion
/// error, and react accordingly).
case custom((DatabaseValue) -> Date?)
}
+28 -49
View File
@@ -580,62 +580,41 @@ private func makeFetchFunction<Record, T>(
// Should controller become strong at any point before callbacks are
// called, such unowned reference would have an opportunity to crash.
return { [weak controller] observer in
// Return if observer has been invalidated
guard observer.isValid else { return }
// Return if fetched records controller has been deallocated
guard let request = controller?.request, let databaseWriter = controller?.databaseWriter else { return }
// Return if observer has been invalidated, or if fetched records
// controller has been deallocated
guard observer.isValid,
let request = controller?.request,
let databaseWriter = controller?.databaseWriter
else { return }
willProcessTransaction()
// Fetch items.
//
// This method is called from the database writer's serialized
// queue, so that we can fetch items before other writes have the
// opportunity to modify the database.
//
// However, we don't have to block the writer queue for all the
// duration of the fetch. We just need to block the writer queue
// until we can perform a fetch in isolation. This is the role of
// the readFromCurrentState method (see below).
//
// However, our fetch will last for an unknown duration. And since
// we release the writer queue early, the next database modification
// will triggers this callback while our fetch is, maybe, still
// running. This next callback will also perform its own fetch, that
// will maybe end before our own fetch.
//
// We have to make sure that our fetch is processed *before* the
// next fetch: let's immediately dispatch the processing task in our
// serialized FIFO queue, but have it wait for our fetch to
// complete, with a semaphore:
let semaphore = DispatchSemaphore(value: 0)
var result: Result<(fetchedItems: [Item<Record>], fetchedAlongside: T)>? = nil
do {
try databaseWriter.readFromCurrentState { db in
result = Result { try (
fetchedItems: request.fetchAll(db),
fetchedAlongside: fetchAlongside(db)) }
semaphore.signal()
}
} catch {
result = .failure(error)
semaphore.signal()
// Perform a concurrent read so that writer dispatch queue is released
// as soon as possible.
let future = databaseWriter.concurrentRead { db in
try (fetchedItems: request.fetchAll(db),
fetchedAlongside: fetchAlongside(db))
}
// Process the fetched items
// Dispatch processing immediately on observer.queue in order to
// process fetched values in the same order as transactions:
observer.queue.async { [weak observer] in
// Wait for the fetch to complete:
_ = semaphore.wait(timeout: .distantFuture)
// Return if observer has been deallocated or invalidated
guard let observer = observer,
observer.isValid
else { return }
// Return if observer has been invalidated
guard let strongObserver = observer else { return }
guard strongObserver.isValid else { return }
completion(result!.map { (fetchedItems, fetchedAlongside) in
(fetchedItems: fetchedItems, fetchedAlongside: fetchedAlongside, observer: strongObserver)
})
do {
// Wait for concurrent read to complete
let values = try future.wait()
completion(.success((
fetchedItems: values.fetchedItems,
fetchedAlongside: values.fetchedAlongside,
observer: observer)))
} catch {
completion(.failure(error))
}
}
}
}
+351 -193
View File
@@ -1,213 +1,371 @@
private struct PersistableRecordKeyedEncodingContainer<Key: CodingKey> : KeyedEncodingContainerProtocol {
let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void
init(encode: @escaping (_ value: DatabaseValueConvertible?, _ key: String) -> Void) {
self.encode = encode
import Foundation
extension MutablePersistableRecord where Self: Encodable {
public func encode(to container: inout PersistenceContainer) {
let persistenceContainer = PersistenceContainer()
let encoder = RecordEncoder<Self>(persistenceContainer: persistenceContainer)
try! encode(to: encoder)
container = encoder.persistenceContainer
}
/// The path of coding keys taken to get to this point in encoding.
/// A `nil` value indicates an unkeyed container.
}
// MARK: - RecordEncoder
/// The encoder that encodes a record into GRDB's PersistenceContainer
private class RecordEncoder<Record: MutablePersistableRecord>: Encoder {
var codingPath: [CodingKey] { return [] }
var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo }
private var _persistenceContainer: PersistenceContainer
var persistenceContainer: PersistenceContainer { return _persistenceContainer }
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
mutating func encode(_ value: Bool, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Int, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Int8, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Int16, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Int32, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Int64, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: UInt, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: UInt8, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: UInt16, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: UInt32, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: UInt64, forKey key: Key) throws { encode(value, key.stringValue) }
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) }
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
mutating func encode<T>(_ value: T, forKey key: Key) throws where T : Encodable {
if T.self is DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible encoding over Decodable.
// This allows us to encode Date as String, for example.
encode((value as! DatabaseValueConvertible), key.stringValue)
} else {
try value.encode(to: PersistableRecordEncoder(codingPath: [key], encode: encode))
}
init(persistenceContainer: PersistenceContainer) {
_persistenceContainer = persistenceContainer
}
// 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.
/// - parameter key: The key to encode the container for.
/// - returns: A new keyed encoding container.
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
fatalError("Not implemented")
}
/// Stores an unkeyed encoding container for the given key and returns it.
///
/// - parameter key: The key to encode the container for.
/// - returns: A new unkeyed encoding container.
mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
fatalError("Not implemented")
}
/// Stores a new nested container for the default `super` key and returns a new `Encoder` instance for encoding `super` into that container.
///
/// Equivalent to calling `superEncoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
mutating func superEncoder() -> Encoder {
fatalError("Not implemented")
}
/// Stores a new nested container for the given key and returns a new `Encoder` instance for encoding `super` into that container.
///
/// - parameter key: The key to encode `super` for.
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
mutating func superEncoder(forKey key: Key) -> Encoder {
fatalError("Not implemented")
}
}
private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer {
let key: CodingKey
let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void
var codingPath: [CodingKey] { return [key] }
/// Encodes a null value.
///
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)` call.
func encodeNil() throws { encode(nil, key.stringValue) }
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)` call.
func encode(_ value: Bool) throws { encode(value, key.stringValue) }
func encode(_ value: Int) throws { encode(value, key.stringValue) }
func encode(_ value: Int8) throws { encode(value, key.stringValue) }
func encode(_ value: Int16) throws { encode(value, key.stringValue) }
func encode(_ value: Int32) throws { encode(value, key.stringValue) }
func encode(_ value: Int64) throws { encode(value, key.stringValue) }
func encode(_ value: UInt) throws { encode(value, key.stringValue) }
func encode(_ value: UInt8) throws { encode(value, key.stringValue) }
func encode(_ value: UInt16) throws { encode(value, key.stringValue) }
func encode(_ value: UInt32) throws { encode(value, key.stringValue) }
func encode(_ value: UInt64) throws { encode(value, key.stringValue) }
func encode(_ value: Float) throws { encode(value, key.stringValue) }
func encode(_ value: Double) throws { encode(value, key.stringValue) }
func encode(_ value: String) throws { encode(value, key.stringValue) }
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)` call.
func encode<T>(_ value: T) throws where T : Encodable {
if let dbValueConvertible = value as? DatabaseValueConvertible {
// Prefer DatabaseValueConvertible encoding over Decodable.
// This allows us to encode Date as String, for example.
encode(dbValueConvertible.databaseValue, key.stringValue)
} else {
try value.encode(to: PersistableRecordEncoder(codingPath: [key], encode: encode))
}
}
}
private struct PersistableRecordEncoder : Encoder {
/// The path of coding keys taken to get to this point in encoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey]
/// Any contextual information set by the user for encoding.
var userInfo: [CodingUserInfoKey : Any] = [:]
let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void
init(codingPath: [CodingKey], encode: @escaping (_ value: DatabaseValueConvertible?, _ key: String) -> Void) {
self.codingPath = codingPath
self.encode = encode
}
/// Returns an encoding container appropriate for holding multiple values keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - returns: A new keyed encoding container.
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {
// Asked for a keyed type: top level required
guard codingPath.isEmpty else {
fatalError("unkeyed encoding is not supported")
}
return KeyedEncodingContainer(PersistableRecordKeyedEncodingContainer<Key>(encode: encode))
let container = KeyedContainer<Key>(recordEncoder: self)
return KeyedEncodingContainer(container)
}
/// Returns an encoding container appropriate for holding multiple unkeyed values.
///
/// - returns: A new empty unkeyed container.
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
func unkeyedContainer() -> UnkeyedEncodingContainer {
fatalError("unkeyed encoding is not supported")
}
/// Returns an encoding container appropriate for holding a single primitive value.
///
/// - returns: A new empty single value container.
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
func singleValueContainer() -> SingleValueEncodingContainer {
return DatabaseValueEncodingContainer(key: codingPath.last!, encode: encode)
// @itaiferber on https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/11
//
// > Encoding a value into a single-value container is equivalent to
// > encoding the value directly into the encoder, with the primary
// > difference being the above: encoding into the encoder writes the
// > contents of a type into the encoder, while encoding to a
// > single-value container gives the encoder a chance to intercept the
// > type as a whole.
//
// Wait for somebody hitting this fatal error so that we can write a
// meaningful regression test.
fatalError("single value encoding is not supported")
}
private struct KeyedContainer<Key: CodingKey> : KeyedEncodingContainerProtocol {
var recordEncoder: RecordEncoder
var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo }
init(recordEncoder: RecordEncoder) {
self.recordEncoder = recordEncoder
}
var codingPath: [CodingKey] { return [] }
func encode(_ value: Bool, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Int, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Int8, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Int16, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Int32, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Int64, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: UInt, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: UInt8, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: UInt16, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: UInt32, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: UInt64, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Float, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Double, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: String, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode<T>(_ value: T, forKey key: Key) throws where T : Encodable {
try recordEncoder.encode(value, forKey: key)
}
func encodeNil(forKey key: Key) throws { recordEncoder.persist(nil, forKey: key) }
func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: Int?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: Float?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: Double?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: String?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent<T>(_ value: T?, forKey key: Key) throws where T : Encodable {
if let value = value {
try recordEncoder.encode(value, forKey: key)
} else {
recordEncoder.persist(nil, forKey: key)
}
}
func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
fatalError("Not implemented")
}
func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
fatalError("Not implemented")
}
func superEncoder() -> Encoder {
fatalError("Not implemented")
}
func superEncoder(forKey key: Key) -> Encoder {
fatalError("Not implemented")
}
}
/// Helper methods
@inline(__always)
fileprivate func persist(_ value: DatabaseValueConvertible?, forKey key: CodingKey) {
_persistenceContainer[key.stringValue] = value
}
@inline(__always)
fileprivate func encode<T>(_ value: T, forKey key: CodingKey) throws where T : Encodable {
if let date = value as? Date {
persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key)
} else if let uuid = value as? UUID {
persist(Record.databaseUUIDEncodingStrategy.encode(uuid), forKey: key)
} else if let value = value as? DatabaseValueConvertible {
// Prefer DatabaseValueConvertible encoding over Decodable.
persist(value.databaseValue, forKey: key)
} else {
do {
// This encoding will fail for types that encode into keyed
// or unkeyed containers, because we're encoding a single
// value here (string, int, double, data, null). If such an
// error happens, we'll switch to JSON encoding.
let encoder = ColumnEncoder(recordEncoder: self, key: key)
try value.encode(to: encoder)
if encoder.requiresJSON {
// Here we handle empty arrays and dictionaries.
throw JSONRequiredError()
}
} catch is JSONRequiredError {
// Encode to JSON
let jsonData = try Record.databaseJSONEncoder(for: key.stringValue).encode(value)
// Store JSON String in the database for easier debugging and
// database inspection. Thanks to SQLite weak typing, we won't
// have any trouble decoding this string into data when we
// eventually perform JSON decoding.
// TODO: possible optimization: avoid this conversion to string, and store raw data bytes as an SQLite string
let jsonString = String(data: jsonData, encoding: .utf8)! // force unwrap because json data is guaranteed to convert to String
persist(jsonString, forKey: key)
}
}
}
}
extension MutablePersistableRecord where Self: Encodable {
public func encode(to container: inout PersistenceContainer) {
// The inout container parameter won't enter an escaping closure since
// SE-0035: https://github.com/apple/swift-evolution/blob/master/proposals/0035-limit-inout-capture.md
//
// So let's use it in a non-escaping closure:
func encode(_ encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void) {
withoutActuallyEscaping(encode) { escapableEncode in
let encoder = PersistableRecordEncoder(codingPath: [], encode: escapableEncode)
try! self.encode(to: encoder)
}
// MARK: - ColumnEncoder
/// The encoder that encodes into a database column
private class ColumnEncoder<Record: MutablePersistableRecord>: Encoder {
var recordEncoder: RecordEncoder<Record>
var key: CodingKey
var codingPath: [CodingKey] { return [key] }
var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo }
var requiresJSON = false
init(recordEncoder: RecordEncoder<Record>, key: CodingKey) {
self.recordEncoder = recordEncoder
self.key = key
}
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
// Keyed values require JSON encoding: we need to throw
// JSONRequiredError. Since we can't throw right from here, let's
// delegate the job to a dedicated container.
requiresJSON = true
let container = JSONRequiredEncoder<Record>.KeyedContainer<Key>(codingPath: codingPath)
return KeyedEncodingContainer(container)
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
// Keyed values require JSON encoding: we need to throw
// JSONRequiredError. Since we can't throw right from here, let's
// delegate the job to a dedicated container.
requiresJSON = true
return JSONRequiredEncoder<Record>(codingPath: codingPath)
}
func singleValueContainer() -> SingleValueEncodingContainer {
return self
}
}
extension ColumnEncoder: SingleValueEncodingContainer {
func encodeNil() throws { recordEncoder.persist(nil, forKey: key) }
func encode(_ value: Bool ) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Int ) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Int8 ) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Int16 ) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Int32 ) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Int64 ) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: UInt ) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: UInt8 ) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: UInt16) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: UInt32) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: UInt64) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Float ) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Double) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: String) throws { recordEncoder.persist(value, forKey: key) }
func encode<T>(_ value: T) throws where T : Encodable {
try recordEncoder.encode(value, forKey: key)
}
}
// MARK: - JSONRequiredEncoder
/// The error that triggers JSON encoding
private struct JSONRequiredError: Error { }
/// The encoder that always ends up with a JSONRequiredError
private struct JSONRequiredEncoder<Record: MutablePersistableRecord>: Encoder {
var codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo }
init(codingPath: [CodingKey]) {
self.codingPath = codingPath
}
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
let container = KeyedContainer<Key>(codingPath: codingPath)
return KeyedEncodingContainer(container)
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
return self
}
func singleValueContainer() -> SingleValueEncodingContainer {
return self
}
struct KeyedContainer<KeyType: CodingKey>: KeyedEncodingContainerProtocol {
var codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo }
func encodeNil(forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Bool, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Int, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Int8, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Int16, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Int32, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Int64, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: UInt, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: UInt8, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: UInt16, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: UInt32, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: UInt64, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Float, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Double, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: String, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode<T>(_ value: T, forKey key: KeyType) throws where T : Encodable { throw JSONRequiredError() }
func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: KeyType) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
let container = KeyedContainer<NestedKey>(codingPath: codingPath + [key])
return KeyedEncodingContainer(container)
}
encode { (value, key) in
container[key] = value
func nestedUnkeyedContainer(forKey key: KeyType) -> UnkeyedEncodingContainer {
return JSONRequiredEncoder(codingPath: codingPath)
}
func superEncoder() -> Encoder {
return JSONRequiredEncoder(codingPath: codingPath)
}
func superEncoder(forKey key: KeyType) -> Encoder {
return JSONRequiredEncoder(codingPath: codingPath)
}
}
}
extension JSONRequiredEncoder: SingleValueEncodingContainer {
func encodeNil() throws { throw JSONRequiredError() }
func encode(_ value: Bool ) throws { throw JSONRequiredError() }
func encode(_ value: Int ) throws { throw JSONRequiredError() }
func encode(_ value: Int8 ) throws { throw JSONRequiredError() }
func encode(_ value: Int16 ) throws { throw JSONRequiredError() }
func encode(_ value: Int32 ) throws { throw JSONRequiredError() }
func encode(_ value: Int64 ) throws { throw JSONRequiredError() }
func encode(_ value: UInt ) throws { throw JSONRequiredError() }
func encode(_ value: UInt8 ) throws { throw JSONRequiredError() }
func encode(_ value: UInt16) throws { throw JSONRequiredError() }
func encode(_ value: UInt32) throws { throw JSONRequiredError() }
func encode(_ value: UInt64) throws { throw JSONRequiredError() }
func encode(_ value: Float ) throws { throw JSONRequiredError() }
func encode(_ value: Double) throws { throw JSONRequiredError() }
func encode(_ value: String) throws { throw JSONRequiredError() }
func encode<T>(_ value: T) throws where T : Encodable { throw JSONRequiredError() }
}
extension JSONRequiredEncoder: UnkeyedEncodingContainer {
var count: Int { return 0 }
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
let container = KeyedContainer<NestedKey>(codingPath: codingPath)
return KeyedEncodingContainer(container)
}
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
return self
}
mutating func superEncoder() -> Encoder {
return self
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
fileprivate var iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
return formatter
}()
private extension DatabaseDateEncodingStrategy {
@inline(__always)
func encode(_ date: Date) -> DatabaseValueConvertible? {
switch self {
case .deferredToDate:
return date.databaseValue
case .timeIntervalSinceReferenceDate:
return date.timeIntervalSinceReferenceDate
case .timeIntervalSince1970:
return date.timeIntervalSince1970
case .millisecondsSince1970:
return Int64(floor(1000.0 * date.timeIntervalSince1970))
case .secondsSince1970:
return Int64(floor(date.timeIntervalSince1970))
case .iso8601:
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return iso8601Formatter.string(from: date)
} else {
fatalError("ISO8601DateFormatter is unavailable on this platform.")
}
case .formatted(let formatter):
return formatter.string(from: date)
case .custom(let format):
return format(date)
}
}
}
private extension DatabaseUUIDEncodingStrategy {
@inline(__always)
func encode(_ uuid: UUID) -> DatabaseValueConvertible? {
switch self {
case .deferredToUUID:
return uuid.databaseValue
case .string:
return uuid.uuidString
}
}
}
+294 -21
View File
@@ -1,3 +1,5 @@
import Foundation
extension Database.ConflictResolution {
var invalidatesLastInsertedRowID: Bool {
switch self {
@@ -320,6 +322,127 @@ public protocol MutablePersistableRecord : TableRecord {
/// - returns: Whether the primary key matches a row in the database.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
func exists(_ db: Database) throws -> Bool
// MARK: - Customizing the Format of Database Columns
/// When the PersistableRecord type also adopts the standard Encodable
/// protocol, you can use this dictionary to customize the encoding process
/// into database rows.
///
/// For example:
///
/// // A key that holds a encoder's name
/// let encoderName = CodingUserInfoKey(rawValue: "encoderName")!
///
/// // A PersistableRecord + Encodable record
/// struct Player: PersistableRecord, Encodable {
/// // Customize the encoder name when encoding a database row
/// static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [encoderName: "Database"]
///
/// func encode(to encoder: Encoder) throws {
/// // Print the encoder name
/// print(encoder.userInfo[encoderName])
/// ...
/// }
/// }
///
/// let player = Player(...)
///
/// // prints "Database"
/// try player.insert(db)
///
/// // prints "JSON"
/// let encoder = JSONEncoder()
/// encoder.userInfo = [encoderName: "JSON"]
/// let data = try encoder.encode(player)
static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { get }
/// When the PersistableRecord type also adopts the standard Encodable
/// protocol, this method controls the encoding process of nested properties
/// into JSON database columns.
///
/// The default implementation returns a JSONEncoder with the
/// following properties:
///
/// - dataEncodingStrategy: .base64
/// - dateEncodingStrategy: .millisecondsSince1970
/// - nonConformingFloatEncodingStrategy: .throw
/// - outputFormatting: .sortedKeys (iOS 11.0+, macOS 10.13+, watchOS 4.0+)
///
/// You can override those defaults:
///
/// struct Achievement: Encodable {
/// var name: String
/// var date: Date
/// }
///
/// struct Player: Encodable, PersistableRecord {
/// // stored in a JSON column
/// var achievements: [Achievement]
///
/// static func databaseJSONEncoder(for column: String) -> JSONEncoder {
/// let encoder = JSONEncoder()
/// encoder.dateEncodingStrategy = .iso8601
/// return encoder
/// }
/// }
static func databaseJSONEncoder(for column: String) -> JSONEncoder
/// When the PersistableRecord type also adopts the standard Encodable
/// protocol, this property controls the encoding of date properties.
///
/// Default value is .deferredToDate
///
/// For example:
///
/// struct Player: PersistableRecord, Encodable {
/// static let databaseDateEncodingStrategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970
///
/// var name: String
/// var registrationDate: Date // encoded as an epoch timestamp
/// }
static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get }
/// When the PersistableRecord type also adopts the standard Encodable
/// protocol, this property controls the encoding of UUID properties.
///
/// Default value is .deferredToUUID
///
/// For example:
///
/// struct Player: PersistableProtocol, Encodable {
/// static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .string
///
/// // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
/// var uuid: UUID
/// }
static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get }
}
extension MutablePersistableRecord {
public static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] {
return [:]
}
public static func databaseJSONEncoder(for column: String) -> JSONEncoder {
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.dateEncodingStrategy = .millisecondsSince1970
encoder.nonConformingFloatEncodingStrategy = .throw
if #available(watchOS 4.0, OSX 10.13, iOS 11.0, *) {
// guarantee some stability in order to ease record comparison
encoder.outputFormatting = .sortedKeys
}
return encoder
}
public static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy {
return .deferredToDate
}
public static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy {
return .deferredToUUID
}
}
extension MutablePersistableRecord {
@@ -398,28 +521,62 @@ extension MutablePersistableRecord {
try update(db, columns: Set(columns.map { $0.name }))
}
/// If the record has differences from the other record, executes an UPDATE
/// statement so that those changes and only those changes are saved in
/// the database.
/// If the record has any difference from the other record, executes an
/// UPDATE statement so that those differences and only those difference are
/// saved in the database.
///
/// This method is guaranteed to have saved the eventual changes in the
/// This method is guaranteed to have saved the eventual differences in the
/// database if it returns without error.
///
/// For example:
///
/// if let oldPlayer = try Player.fetchOne(db, key: 42) {
/// var newPlayer = oldPlayer
/// newPlayer.score += 10
/// newPlayer.hasAward = true
/// try newPlayer.updateChanges(db, from: oldRecord)
/// }
///
/// - parameter db: A database connection.
/// - parameter columns: The columns to update.
/// - parameter record: The comparison record.
/// - returns: Whether the record had changes.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
/// - SeeAlso: updateChanges(_:with:)
@discardableResult
public func updateChanges(_ db: Database, from record: MutablePersistableRecord) throws -> Bool {
return try updateChanges(db, from: PersistenceContainer(record))
}
/// Mutates the record according to the provided closure, and then, if the
/// record has any difference from its previous version, executes an
/// UPDATE statement so that those differences and only those difference are
/// saved in the database.
///
/// This method is guaranteed to have saved the eventual differences in the
/// database if it returns without error.
///
/// For example:
///
/// if var player = try Player.fetchOne(db, key: 42) {
/// try player.updateChanges(db) {
/// $0.score += 10
/// $0.hasAward = true
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter change: A closure that modifies the record.
/// - returns: Whether the record had changes.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
@discardableResult
public func updateChanges(_ db: Database, from record: MutablePersistableRecord) throws -> Bool {
let changedColumns = Set(databaseChanges(from: record).keys)
if changedColumns.isEmpty {
return false
} else {
try update(db, columns: changedColumns)
return true
}
public mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool {
let container = PersistenceContainer(self)
try change(&self)
return try updateChanges(db, from: container)
}
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
@@ -451,7 +608,7 @@ extension MutablePersistableRecord {
/// Returns a boolean indicating whether this record and the other record
/// have the same database representation.
public func databaseEquals(_ record: Self) -> Bool {
return databaseChangesIterator(from: record).next() == nil
return databaseChangesIterator(from: PersistenceContainer(record)).next() == nil
}
/// A dictionary of values changed from the other record.
@@ -463,16 +620,15 @@ extension MutablePersistableRecord {
/// same set of columns in their `encode(to:)` method, only the columns
/// defined by the receiver record are considered.
public func databaseChanges(from record: MutablePersistableRecord) -> [String: DatabaseValue] {
return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: record))
return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: PersistenceContainer(record)))
}
fileprivate func databaseChangesIterator(from record: MutablePersistableRecord) -> AnyIterator<(String, DatabaseValue)> {
let oldContainer = PersistenceContainer(record)
private func databaseChangesIterator(from container: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> {
var newValueIterator = PersistenceContainer(self).makeIterator()
return AnyIterator {
// Loop until we find a change, or exhaust columns:
while let (column, newValue) = newValueIterator.next() {
let oldValue = oldContainer[caseInsensitive: column]
let oldValue = container[caseInsensitive: column]
let oldDbValue = oldValue?.databaseValue ?? .null
let newDbValue = newValue?.databaseValue ?? .null
if newDbValue != oldDbValue {
@@ -483,6 +639,17 @@ extension MutablePersistableRecord {
}
}
@discardableResult
fileprivate func updateChanges(_ db: Database, from container: PersistenceContainer) throws -> Bool {
let changes = databaseChangesIterator(from: container)
let changedColumns: Set<String> = changes.reduce(into: []) { $0.insert($1.0) }
if changedColumns.isEmpty {
return false
}
try update(db, columns: changedColumns)
return true
}
// MARK: - CRUD Internals
/// Return true if record has a non-null primary key
@@ -598,7 +765,42 @@ extension MutablePersistableRecord {
}
return try Row.fetchOne(statement) != nil
}
}
extension MutablePersistableRecord where Self: AnyObject {
// MARK: - Record Comparison
/// Mutates the record according to the provided closure, and then, if the
/// record has any difference from its previous version, executes an
/// UPDATE statement so that those differences and only those difference are
/// saved in the database.
///
/// This method is guaranteed to have saved the eventual differences in the
/// database if it returns without error.
///
/// For example:
///
/// if let player = try Player.fetchOne(db, key: 42) {
/// try player.updateChanges(db) {
/// $0.score += 10
/// $0.hasAward = true
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter change: A closure that modifies the record.
/// - returns: Whether the record had changes.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
@discardableResult
public func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool {
let container = PersistenceContainer(self)
try change(self)
return try updateChanges(db, from: container)
}
}
extension MutablePersistableRecord {
@@ -806,7 +1008,6 @@ extension PersistableRecord {
try performSave(db)
}
// MARK: - Immutable CRUD Internals
/// Don't invoke this method directly: it is an internal method for types
@@ -853,7 +1054,77 @@ extension PersistableRecord {
try insert(db)
}
}
}
// MARK: - DatabaseDateEncodingStrategy
/// DatabaseDateEncodingStrategy specifies how PersistableRecord types that also
/// adopt the standard Encodable protocol encode their date properties.
///
/// For example:
///
/// struct Player: PersistableRecord, Encodable {
/// static let databaseDateEncodingStrategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970
///
/// var name: String
/// var registrationDate: Date // encoded as an epoch timestamp
/// }
public enum DatabaseDateEncodingStrategy {
/// The strategy that uses formatting from the Date structure.
///
/// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the
/// UTC time zone.
case deferredToDate
/// Encodes a Double: the number of seconds between the date and
/// midnight UTC on 1 January 2001
case timeIntervalSinceReferenceDate
/// Encodes a Double: the number of seconds between the date and
/// midnight UTC on 1 January 1970
case timeIntervalSince1970
/// Encodes an Int64: the number of seconds between the date and
/// midnight UTC on 1 January 1970
case secondsSince1970
/// Encodes an Int64: the number of milliseconds between the date and
/// midnight UTC on 1 January 1970
case millisecondsSince1970
/// Encodes dates according to the ISO 8601 and RFC 3339 standards
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
case iso8601
/// Encodes a String, according to the provided formatter
case formatted(DateFormatter)
/// Encodes the result of the user-provided function
case custom((Date) -> DatabaseValueConvertible?)
}
// MARK: - DatabaseUUIDEncodingStrategy
/// DatabaseUUIDEncodingStrategy specifies how FetchableRecord types that also
/// adopt the standard Encodable protocol encode their UUID properties.
///
/// For example:
///
/// struct Player: PersistableProtocol, Encodable {
/// static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .string
///
/// // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
/// var uuid: UUID
/// }
public enum DatabaseUUIDEncodingStrategy {
/// The strategy that uses formatting from the UUID type.
///
/// It encodes UUIDs as 16-bytes data blobs.
case deferredToUUID
/// Encodes UUIDs as strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
case string
}
// MARK: - DAO
@@ -992,8 +1263,9 @@ private struct InsertQuery: Hashable {
let tableName: String
let insertedColumns: [String]
// TODO: remove when Swift can generate it
#if !swift(>=4.2)
var hashValue: Int { return tableName.hashValue }
#endif
}
extension InsertQuery {
@@ -1025,8 +1297,9 @@ private struct UpdateQuery: Hashable {
let updatedColumns: [String]
let conditionColumns: [String]
// TODO: remove when Swift can generate it
#if !swift(>=4.2)
var hashValue: Int { return tableName.hashValue }
#endif
}
extension UpdateQuery {
+10
View File
@@ -0,0 +1,10 @@
import Foundation
extension String {
var uppercasingFirstCharacter: String {
guard let first = first else {
return self
}
return String(first).uppercased() + dropFirst()
}
}
+67
View File
@@ -0,0 +1,67 @@
struct OrderedDictionary<Key: Hashable, Value> {
private var keys: [Key]
private var values: [Key: Value]
init() {
self.keys = []
self.values = [:]
}
subscript(_ key: Key) -> Value? {
return values[key]
}
mutating func append(value: Value, forKey key: Key) {
guard values.updateValue(value, forKey: key) == nil else {
fatalError("key is already defined")
}
keys.append(key)
}
@discardableResult
mutating func removeValue(forKey key: Key) -> Value? {
guard let value = values.removeValue(forKey: key) else {
return nil
}
let index = keys.index { $0 == key }!
keys.remove(at: index)
return value
}
func mapValues<T>(_ transform: (Value) throws -> T) rethrows -> OrderedDictionary<Key, T> {
var result = OrderedDictionary<Key, T>()
for key in keys {
let value = values[key]!
try result.append(value: transform(value), forKey: key)
}
return result
}
}
extension OrderedDictionary: Collection {
typealias Index = Int
var startIndex: Int {
return 0
}
var endIndex: Int {
return keys.count
}
func index(after i: Int) -> Int {
return i + 1
}
subscript(position: Int) -> (key: Key, value: Value) {
let key = keys[position]
return (key: key, value: values[key]!)
}
}
extension OrderedDictionary: ExpressibleByDictionaryLiteral {
init(dictionaryLiteral elements: (Key, Value)...) {
self.keys = elements.map { $0.0 }
self.values = Dictionary(uniqueKeysWithValues: elements)
}
}
+9
View File
@@ -37,4 +37,13 @@ enum Result<Value> {
return .failure(error)
}
}
func unwrap() throws -> Value {
switch self {
case .success(let value):
return value
case .failure(let error):
throw error
}
}
}
+12
View File
@@ -46,6 +46,7 @@ extension Optional : _OptionalProtocol {
// MARK: - Internal
/// Reserved for GRDB: do not use.
@inline(__always)
func GRDBPrecondition(_ condition: @autoclosure() -> Bool, _ message: @autoclosure() -> String = "", file: StaticString = #file, line: UInt = #line) {
/// Custom precondition function which aims at solving
/// https://bugs.swift.org/browse/SR-905 and
@@ -69,3 +70,14 @@ extension Array {
}
}
extension DispatchQueue {
private static var mainKey: DispatchSpecificKey<()> = {
let key = DispatchSpecificKey<()>()
DispatchQueue.main.setSpecific(key: key, value: ())
return key
}()
static var isMain: Bool {
return DispatchQueue.getSpecific(key: mainKey) != nil
}
}
@@ -0,0 +1,273 @@
extension ValueObservation where Reducer == Void {
public static func combine<R1: ValueReducer, R2: ValueReducer>(
_ o1: ValueObservation<R1>,
_ o2: ValueObservation<R2>)
-> ValueObservation<AnyValueReducer<
(R1.Fetched, R2.Fetched),
(R1.Value, R2.Value)>>
{
return ValueObservation<AnyValueReducer<
(R1.Fetched, R2.Fetched),
(R1.Value, R2.Value)>>(
tracking: { try DatabaseRegion.union(
o1.observedRegion($0),
o2.observedRegion($0)) },
reducer: { try _combine(
o1.makeReducer($0),
o2.makeReducer($0)) })
}
public static func combine<R1: ValueReducer, R2: ValueReducer, R3: ValueReducer>(
_ o1: ValueObservation<R1>,
_ o2: ValueObservation<R2>,
_ o3: ValueObservation<R3>)
-> ValueObservation<AnyValueReducer<
(R1.Fetched, R2.Fetched, R3.Fetched),
(R1.Value, R2.Value, R3.Value)>>
{
return ValueObservation<AnyValueReducer<
(R1.Fetched, R2.Fetched, R3.Fetched),
(R1.Value, R2.Value, R3.Value)>>(
tracking: { try DatabaseRegion.union(
o1.observedRegion($0),
o2.observedRegion($0),
o3.observedRegion($0)) },
reducer: { try _combine(
o1.makeReducer($0),
o2.makeReducer($0),
o3.makeReducer($0)) })
}
public static func combine<R1: ValueReducer, R2: ValueReducer, R3: ValueReducer, R4: ValueReducer>(
_ o1: ValueObservation<R1>,
_ o2: ValueObservation<R2>,
_ o3: ValueObservation<R3>,
_ o4: ValueObservation<R4>)
-> ValueObservation<AnyValueReducer<
(R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched),
(R1.Value, R2.Value, R3.Value, R4.Value)>>
{
return ValueObservation<AnyValueReducer<
(R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched),
(R1.Value, R2.Value, R3.Value, R4.Value)>>(
tracking: { try DatabaseRegion.union(
o1.observedRegion($0),
o2.observedRegion($0),
o3.observedRegion($0),
o4.observedRegion($0)) },
reducer: { try _combine(
o1.makeReducer($0),
o2.makeReducer($0),
o3.makeReducer($0),
o4.makeReducer($0)) })
}
public static func combine<R1: ValueReducer, R2: ValueReducer, R3: ValueReducer, R4: ValueReducer, R5: ValueReducer>(
_ o1: ValueObservation<R1>,
_ o2: ValueObservation<R2>,
_ o3: ValueObservation<R3>,
_ o4: ValueObservation<R4>,
_ o5: ValueObservation<R5>)
-> ValueObservation<AnyValueReducer<
(R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched),
(R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)>>
{
return ValueObservation<AnyValueReducer<
(R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched),
(R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)>>(
tracking: { try DatabaseRegion.union(
o1.observedRegion($0),
o2.observedRegion($0),
o3.observedRegion($0),
o4.observedRegion($0),
o5.observedRegion($0)) },
reducer: { try _combine(
o1.makeReducer($0),
o2.makeReducer($0),
o3.makeReducer($0),
o4.makeReducer($0),
o5.makeReducer($0)) })
}
}
private func _combine<R1: ValueReducer, R2: ValueReducer>(
_ r1: R1,
_ r2: R2)
-> AnyValueReducer<
(R1.Fetched, R2.Fetched),
(R1.Value, R2.Value)>
{
var r1 = r1
var r2 = r2
var prev1: R1.Value?
var prev2: R2.Value?
func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched) {
return try (
r1.fetch(db),
r2.fetch(db))
}
func value(tuple: (R1.Fetched, R2.Fetched)) -> (R1.Value, R2.Value)? {
let v1 = r1.value(tuple.0)
let v2 = r2.value(tuple.1)
defer {
if let v1 = v1 { prev1 = v1 }
if let v2 = v2 { prev2 = v2 }
}
if v1 != nil || v2 != nil,
let c1 = v1 ?? prev1,
let c2 = v2 ?? prev2
{
return (c1, c2)
} else {
return nil
}
}
return AnyValueReducer(fetch: fetch, value: value)
}
private func _combine<R1: ValueReducer, R2: ValueReducer, R3: ValueReducer>(
_ r1: R1,
_ r2: R2,
_ r3: R3)
-> AnyValueReducer<
(R1.Fetched, R2.Fetched, R3.Fetched),
(R1.Value, R2.Value, R3.Value)>
{
var r1 = r1
var r2 = r2
var r3 = r3
var prev1: R1.Value?
var prev2: R2.Value?
var prev3: R3.Value?
func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched) {
return try (
r1.fetch(db),
r2.fetch(db),
r3.fetch(db))
}
func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched)) -> (R1.Value, R2.Value, R3.Value)? {
let v1 = r1.value(tuple.0)
let v2 = r2.value(tuple.1)
let v3 = r3.value(tuple.2)
defer {
if let v1 = v1 { prev1 = v1 }
if let v2 = v2 { prev2 = v2 }
if let v3 = v3 { prev3 = v3 }
}
if v1 != nil || v2 != nil || v3 != nil,
let c1 = v1 ?? prev1,
let c2 = v2 ?? prev2,
let c3 = v3 ?? prev3
{
return (c1, c2, c3)
} else {
return nil
}
}
return AnyValueReducer(fetch: fetch, value: value)
}
private func _combine<R1: ValueReducer, R2: ValueReducer, R3: ValueReducer, R4: ValueReducer>(
_ r1: R1,
_ r2: R2,
_ r3: R3,
_ r4: R4)
-> AnyValueReducer<
(R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched),
(R1.Value, R2.Value, R3.Value, R4.Value)>
{
var r1 = r1
var r2 = r2
var r3 = r3
var r4 = r4
var prev1: R1.Value?
var prev2: R2.Value?
var prev3: R3.Value?
var prev4: R4.Value?
func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched) {
return try (
r1.fetch(db),
r2.fetch(db),
r3.fetch(db),
r4.fetch(db))
}
func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched)) -> (R1.Value, R2.Value, R3.Value, R4.Value)? {
let v1 = r1.value(tuple.0)
let v2 = r2.value(tuple.1)
let v3 = r3.value(tuple.2)
let v4 = r4.value(tuple.3)
defer {
if let v1 = v1 { prev1 = v1 }
if let v2 = v2 { prev2 = v2 }
if let v3 = v3 { prev3 = v3 }
if let v4 = v4 { prev4 = v4 }
}
if v1 != nil || v2 != nil || v3 != nil || v4 != nil,
let c1 = v1 ?? prev1,
let c2 = v2 ?? prev2,
let c3 = v3 ?? prev3,
let c4 = v4 ?? prev4
{
return (c1, c2, c3, c4)
} else {
return nil
}
}
return AnyValueReducer(fetch: fetch, value: value)
}
private func _combine<R1: ValueReducer, R2: ValueReducer, R3: ValueReducer, R4: ValueReducer, R5: ValueReducer>(
_ r1: R1,
_ r2: R2,
_ r3: R3,
_ r4: R4,
_ r5: R5)
-> AnyValueReducer<
(R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched),
(R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)>
{
var r1 = r1
var r2 = r2
var r3 = r3
var r4 = r4
var r5 = r5
var prev1: R1.Value?
var prev2: R2.Value?
var prev3: R3.Value?
var prev4: R4.Value?
var prev5: R5.Value?
func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched) {
return try (
r1.fetch(db),
r2.fetch(db),
r3.fetch(db),
r4.fetch(db),
r5.fetch(db))
}
func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched)) -> (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)? {
let v1 = r1.value(tuple.0)
let v2 = r2.value(tuple.1)
let v3 = r3.value(tuple.2)
let v4 = r4.value(tuple.3)
let v5 = r5.value(tuple.4)
defer {
if let v1 = v1 { prev1 = v1 }
if let v2 = v2 { prev2 = v2 }
if let v3 = v3 { prev3 = v3 }
if let v4 = v4 { prev4 = v4 }
if let v5 = v5 { prev5 = v5 }
}
if v1 != nil || v2 != nil || v3 != nil || v4 != nil || v5 != nil,
let c1 = v1 ?? prev1,
let c2 = v2 ?? prev2,
let c3 = v3 ?? prev3,
let c4 = v4 ?? prev4,
let c5 = v5 ?? prev5
{
return (c1, c2, c3, c4, c5)
} else {
return nil
}
}
return AnyValueReducer(fetch: fetch, value: value)
}
Loaded 100 of 227 files, more files were not shown because too many files have changed in this diff. Show more