Compare commits

...
1524 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
Gwendal Roué 0dabd36123 v3.2.0 2018-07-08 13:23:40 +02:00
Gwendal Roué 8a83ee4599 Travis: use Xcode 9.4 2018-07-08 12:22:53 +02:00
Gwendal Roué 29e720c474 DONE: #378 2018-07-08 12:17:38 +02:00
Gwendal Roué 444f5b003f Merge branch 'master' of github.com:groue/GRDB.swift into development 2018-07-08 12:17:06 +02:00
Gwendal Roué 3e60b00bab Merge pull request #381 from groue/feature/378-nuking-db-during-development
Nuking db during development
2018-07-08 06:31:30 +02:00
Gwendal Roué fc2c2658b7 DatabaseWriterTests.testEraseAndVacuum: use auto increment so we can test database erasure with internal SQLite objects 2018-07-07 17:53:36 +02:00
Gwendal Roué fdef88d150 DatabaseWriterTests.testEraseAndVacuum: add a virtual table 2018-07-07 17:51:55 +02:00
Gwendal Roué 1a84a84bd1 Typo fix 2018-07-07 17:45:15 +02:00
Gwendal Roué 22006e2251 CHANGELOG 2018-07-07 17:43:42 +02:00
Gwendal Roué 3405585d60 Typo fix 2018-07-07 17:43:37 +02:00
Gwendal Roué 91d0a453da DatabaseWriter.erase(): more robust error handling 2018-07-07 17:43:26 +02:00
Gwendal Roué d814249c5a eraseDatabaseOnSchemaChange documentation 2018-07-07 17:34:44 +02:00
Gwendal Roué fc2d5419b3 CHANGELOG 2018-07-07 17:17:23 +02:00
Gwendal Roué 3593806685 Cleanup 2018-07-07 14:49:43 +02:00
Gwendal Roué e84b539de2 DatabaseWriter.erase(): don't mess with internal SQLite objects 2018-07-07 14:42:18 +02:00
Gwendal Roué fee4486d1b DatabaseMigrator.eraseDatabaseOnSchemaChange 2018-07-07 14:23:50 +02:00
Gwendal Roué a73be9c010 Fix databaseWriter.erase() with SQLCipher 2018-07-07 12:32:40 +02:00
Gwendal Roué 0bc25f8773 Tests for DatabaseQueue and DatabasePool erase and vacuum 2018-07-06 14:03:44 +02:00
Gwendal Roué a465f16ff7 databaseWriter.erase(), databaseWriter.vacuum() 2018-07-06 13:58:55 +02:00
Gwendal Roué 86d93b11dd Easier database backup invocation 2018-07-06 13:57:55 +02:00
Gwendal Roué f8aa5b7e21 Fix typo 2018-07-05 08:38:56 +02:00
Gwendal Roué 16184ae89b More documentation about invalid value conversions 2018-07-05 08:37:57 +02:00
Gwendal Roué af2a3ea827 More documentation about invalid value conversions 2018-07-05 08:31:58 +02:00
Gwendal Roué ca7df229fa Cleanup 2018-07-03 18:44:42 +02:00
Gwendal Roué f121c6b139 TODO.md: look at #378 2018-07-02 08:15:40 +02:00
Gwendal Roué 2a6f7b7588 Fix typo 2018-06-30 11:41:11 +02:00
Gwendal Roué a87d06d609 Add @bellebethcooper to the thank you notice 2018-06-30 11:40:16 +02:00
Gwendal Roué 7c85a973dc TODO (inspired by #377) 2018-06-30 11:22:50 +02:00
Gwendal Roué 97961f4374 Merge pull request #376 from bellebethcooper/patch-1
Typo fix
2018-06-30 07:11:24 +02:00
bellebethcooper 4436badbc8 Typo fix 2018-06-30 10:31:10 +10:00
Gwendal Roué 9060048044 PULL_REQUEST_TEMPLATE.md 2018-06-28 14:03:25 +02:00
Gwendal Roué 99566225f0 TODO.md 2018-06-28 13:38:09 +02:00
Gwendal Roué b4bd25decc Fix typo in GoodPracticesForDesigningRecordTypes.md 2018-06-25 13:35:52 +02:00
Gwendal Roué 0e94c7b44e Improve GoodPracticesForDesigningRecordTypes.md 2018-06-25 13:34:38 +02:00
Gwendal Roué c750fd7b1d v3.1.0 2018-06-17 15:23:53 +02:00
Gwendal Roué 0ed4491b46 Prepare for SE-0206 "Hashable Enhancements" 2018-06-17 15:23:23 +02:00
Gwendal Roué b4a3adafb1 Merge pull request #372 from groue/sqlite3.24.0
Upgrade custom SQLite builds to 3.24.0
2018-06-17 14:34:45 +02:00
Gwendal Roué 2e953221fa CHANGELOG 2018-06-15 08:26:13 +02:00
Gwendal Roué 1886ac5cfb Upgrade custom SQLite builds to 3.24.0 2018-06-15 08:21:52 +02:00
Gwendal Roué 7ed7196c48 Merge pull request #371 from groue/queueLabels
Database can have a label
2018-06-15 05:03:10 +02:00
Gwendal Roué 38b1e41aab Final tweaks to dispatch queue labels 2018-06-14 21:10:56 +02:00
Gwendal Roué 467819bdd5 Confiiguration.label documentation 2018-06-14 20:50:06 +02:00
Gwendal Roué e81e818305 Confiiguration.label documentation 2018-06-14 20:47:43 +02:00
Gwendal Roué 342dcc5094 Confiiguration.label is used to name dispatch queues 2018-06-14 20:26:34 +02:00
Gwendal Roué 8f89a2063e CHANGELOG 2018-06-14 13:45:44 +02:00
Gwendal Roué 2e80db8aed Database dispatch queues now have labels 2018-06-14 13:36:42 +02:00
Gwendal Roué 4e7fc83ad5 Add test for FTS4 compression/decompression (addresses #369) 2018-06-14 13:32:28 +02:00
Gwendal Roué 200f12a558 TODO 2018-06-13 07:48:56 +02:00
Gwendal Roué 5c1eea4c6f TODO 2018-06-13 07:48:56 +02:00
Gwendal Roué b73771fd6c Look for open issues first 2018-06-12 10:42:10 +02:00
Gwendal Roué a47f10cf07 Link to forums 2018-06-12 10:40:43 +02:00
Gwendal Roué 75d0643642 Improve AssociationsBasics.md 2018-06-11 08:20:05 +02:00
Gwendal Roué 732e0bd34b Improve AssociationsBasics.md 2018-06-11 08:15:09 +02:00
Gwendal Roué ac2cd485c8 Mini typo in GoodPracticesForDesigningRecordTypes.md 2018-06-08 05:54:27 +02:00
Gwendal Roué b967018390 Improve GoodPracticesForDesigningRecordTypes.md 2018-06-07 20:15:45 +02:00
Gwendal Roué df16c4856f Improve GoodPracticesForDesigningRecordTypes.md 2018-06-07 20:11:01 +02:00
Gwendal Roué 4e97b80274 Improve GoodPracticesForDesigningRecordTypes.md 2018-06-07 19:58:22 +02:00
Gwendal Roué 65b3e21e65 Another typo in GoodPracticesForDesigningRecordTypes.md 2018-06-07 19:54:59 +02:00
Gwendal Roué 5b97dea3c6 Mini typo in GoodPracticesForDesigningRecordTypes.md 2018-06-07 19:50:48 +02:00
Gwendal Roué 20322640c3 New Associations demo playground, and fix a few typos in GoodPracticesForDesigningRecordTypes.md 2018-06-07 19:37:31 +02:00
Gwendal Roué 89ce13c43c Documentation tweaks 2018-06-07 18:59:47 +02:00
Gwendal Roué 27e94c211d Upgrade SPM test app to v3.0.0 2018-06-07 13:53:16 +02:00
Gwendal Roué bca4af679e No more reference to the GRDB3 branch 2018-06-07 13:28:30 +02:00
Gwendal Roué cb7f827118 GRDB2MigrationGuide.md no longer refers to GRDB3 branch 2018-06-07 13:26:48 +02:00
Gwendal Roué 1bc4299bfc Fix bug in GRDBDemoiOS 2018-06-07 12:53:24 +02:00
Gwendal Roué 79c788e571 v3.0.0 2018-06-07 12:46:38 +02:00
Gwendal Roué 0125107855 Improve "Good Practices for Designing Record Types" 2018-06-07 11:42:45 +02:00
Gwendal Roué 24694b8b23 Merge branch 'GRDB3' into development 2018-06-07 08:49:36 +02:00
Gwendal Roué 0c79224209 Family gets bigger :-) 2018-06-07 08:39:55 +02:00
Gwendal Roué a88b5dc3df Append #334 to CHANGELOG 2018-06-07 08:36:29 +02:00
Gwendal Roué f259cac51f SQLiteDateParser: tighten vsscanf format 2018-06-07 08:36:29 +02:00
Gwendal Roué fe1146134b SQLiteDateParser: fix nanosecond parsing 2018-06-07 08:36:29 +02:00
Gwendal Roué 6dd4f1c666 More DatabaseDateComponents parsing tests 2018-06-07 08:36:29 +02:00
Gwendal Roué 4415681c92 SQLiteDateParser: don't parse garbage into nanoseconds 2018-06-07 08:36:29 +02:00
Gwendal Roué 5a0425a23c SQLiteDateParser: optimize nanoseconds parsing 2018-06-07 08:36:29 +02:00
Gwendal Roué 8729085528 Add a sanity check 2018-06-07 08:36:29 +02:00
Gwendal Roué 88cbbf5c5e Add missing imports (should fix travis issues) 2018-06-07 08:36:29 +02:00
Gwendal Roué 6816bceed0 No need for useScanfStrategy any longer 2018-06-07 08:36:29 +02:00
Gwendal Roué 76dc5e6b89 Cleanup 2018-06-07 08:36:29 +02:00
Gwendal Roué ee39a52069 New DateParsingTests in GRDBOSXPerformanceTests 2018-06-07 08:36:29 +02:00
Gwendal Roué 82482bdbf7 Date adopts StatementColumnConvertible 2018-06-07 08:36:29 +02:00
Gwendal Roué 062f916607 Documentation 2018-06-07 08:36:29 +02:00
Gwendal Roué 2b73c4f348 Check useScanfStrategy in DatabaseDateComponents.init(sqliteStatement:index:)
...so that we can eventually compare gains
2018-06-07 08:36:29 +02:00
Gwendal Roué 54b2135b74 DatabaseDateComponents adopts StatementColumnConvertible
We'll need benchmarks to evaluate the gain, here
2018-06-07 08:36:29 +02:00
Gwendal Roué bf3b4e7e02 SQLiteDateParser: parse C strings
Since the goal of this PR is efficiency, we'll soon parse Date and
DatabaseDateComponents right from raw SQLite buffers.
2018-06-07 08:36:29 +02:00
Gwendal Roué ad8b80bafd (whitespace) 2018-06-07 08:36:29 +02:00
Gwendal Roué 06476bc6fe SQLiteDateParser.components(from:) is not public 2018-06-07 08:36:29 +02:00
Gwendal Roué 0616209e58 SQLiteDateParser: no more static methods 2018-06-07 08:36:29 +02:00
Gwendal Roué 415f2971e5 SQLiteDateParser: use withUnsafeMutablePointer instead of allocations
OK, not really: the nanosecond components remains in the heap.
But we may find a way to put 11 chars on the stack.
2018-06-07 08:36:29 +02:00
Gwendal Roué 3a7b2cc4a2 SQLiteDateParser: get rid of the mutex 2018-06-07 08:36:29 +02:00
Gwendal Roué 726e40984a Add SQLiteDateParser.swift to GRDBCustom and GRDBCipher
... so that all GRDB flavors can use the new technique.
GRDB has three distinct projects since #282.
2018-06-07 08:36:29 +02:00
Matt Greenfield 63a68978f0 truncate nanosecond precision to 3 sig figs 2018-06-07 08:36:29 +02:00
Matt Greenfield 13d973dde4 Revert "fix the tests to expect less nanosecond precision loss"
This reverts commit eba5df1fcc.
2018-06-07 08:36:29 +02:00
Matt Greenfield 8f5ef76e7e Revert "permit precision loss down to 3 sig figs"
This reverts commit 3bcc5b8064.
2018-06-07 08:36:29 +02:00
Matt Greenfield 36ac5fa53e truncate date/time strings that include seconds precision beyond the nanosecond scale 2018-06-07 08:36:29 +02:00
Matt Greenfield cda891ca02 permit precision loss down to 3 sig figs 2018-06-07 08:36:29 +02:00
Matt Greenfield ff4447713a fix the tests to expect less nanosecond precision loss 2018-06-07 08:36:29 +02:00
Matt Greenfield 70190e2a23 not all nanosecond fractions have 3 sig figs, so can't hard code the acceptable string lengths 2018-06-07 08:36:29 +02:00
Matt Greenfield 2682dae34b 0.123 is not the same thing as 0.000123 2018-06-07 08:36:29 +02:00
Matt Greenfield 3a1e695a39 fractions of seconds are not the same thing as integer counts of nanoseconds 2018-06-07 08:36:29 +02:00
Matt Greenfield 604f80f6fa differentiate between SS and SS.SSS formats 2018-06-07 08:36:29 +02:00
Matt Greenfield 5c0b88eb82 return correct Format for partial date/time combinations 2018-06-07 08:36:29 +02:00
Matt Greenfield 7e39fbaba0 add SQLiteDateParser to project file 2018-06-07 08:36:29 +02:00
Matt Greenfield 815424770b initial scanf() based date string parser 2018-06-07 08:36:29 +02:00
Gwendal Roué 30fcd95f1d Change podspec description 2018-06-07 08:31:57 +02:00
Gwendal Roué 4637930027 Improve "Good Practices for Designing Record Types" 2018-06-06 17:09:03 +02:00
Gwendal Roué 729ec6714c Improve "Good Practices for Designing Record Types" 2018-06-06 17:08:42 +02:00
Gwendal Roué b2683eb864 Improve "Good Practices for Designing Record Types" 2018-06-06 17:04:42 +02:00
Gwendal Roué e7bcf7c7db Funny how time you have for tweaking stuff when you're waiting for a watch app to launch... 2018-06-06 16:15:44 +02:00
Gwendal Roué d1c47c3364 Improve "Good Practices for Designing Record Types" 2018-06-06 16:12:21 +02:00
Gwendal Roué 44140cb1db README.md 2018-06-06 15:01:59 +02:00
Gwendal Roué 4bc6a77588 README.md 2018-06-06 14:02:48 +02:00
Gwendal Roué edd294550f Revert "README.md"
This reverts commit 69c2077037.
2018-06-06 13:59:52 +02:00
Gwendal Roué 69c2077037 README.md 2018-06-06 13:59:07 +02:00
Gwendal Roué b3f1997049 README.md 2018-06-06 13:57:44 +02:00
Gwendal Roué c2e624c78d README.md 2018-06-06 13:52:55 +02:00
Gwendal Roué ff69d3fbc3 Merge pull request #365 from groue/GRDB3-DelayedOrdering
Delayed Request Ordering
2018-06-06 07:44:23 +02:00
Gwendal Roué 018fac8c57 CHANGELOG.md 2018-06-05 23:07:00 +02:00
Gwendal Roué 0b1bc80c41 Document orderByPrimaryKey 2018-06-05 22:53:05 +02:00
Gwendal Roué 7e6de4fbd0 Test TableRequest.orderByPrimaryKey() 2018-06-05 22:46:24 +02:00
Gwendal Roué fa31c484da OrderedRequest now waits for the database connection before ordering is computed 2018-06-05 22:46:02 +02:00
Gwendal Roué 2556fd041f Update Makefile for Xcode 9.4 2018-06-05 22:23:43 +02:00
Gwendal Roué e915d28cb2 Fix failing tests for Database.indexes(on:) and Database.foreignKeys(on:) 2018-06-05 14:38:59 +02:00
Gwendal Roué 60eb868fa5 Failing tests for Database.indexes(on:) and Database.foreignKeys(on:) 2018-06-05 14:38:47 +02:00
Gwendal Roué 6130c6f985 Who guessed String ordering would depend on Swift version? Fix a test so that it runs in both Swift 4.1 and Swift 4.2 2018-06-05 08:03:50 +02:00
Gwendal Roué b7f44785ec The SQL statement generated by record.update(db) lists columns in the same order as in the table definition (this fixes tests made flaky by SE-0206) 2018-06-05 08:02:54 +02:00
Gwendal Roué 8b44b0af7b Fix SerializedDatabase.reentrantSync check for unsafe transactions 2018-06-04 11:59:43 +02:00
Gwendal Roué caea11fbbb Database: a couple more asserts 2018-06-04 11:58:40 +02:00
Gwendal Roué c7f018c635 GoodPracticesForDesigningRecordTypes.md 2018-06-04 07:40:12 +02:00
Gwendal Roué b8328bd3bb GoodPracticesForDesigningRecordTypes.md 2018-06-03 18:37:00 +02:00
Gwendal Roué 0dd8fce854 GoodPracticesForDesigningRecordTypes.md 2018-06-03 18:34:27 +02:00
Gwendal Roué f8b7156b48 Simplify demo application 2018-06-03 13:23:31 +02:00
Gwendal Roué cfba53e586 Associations documentatiion 2018-05-31 22:54:13 +02:00
Gwendal Roué 003020dd29 Associations documentatiion 2018-05-31 22:52:32 +02:00
Gwendal Roué f2b46963bd minor 2018-05-31 22:35:58 +02:00
Gwendal Roué 62a434f898 Associations documentatiion 2018-05-31 22:21:00 +02:00
Gwendal Roué 16af4513d6 Associations documentatiion 2018-05-31 22:11:18 +02:00
Gwendal Roué ead89420c4 Avoid undefined behavior (UnsafePointer documentation is scary) 2018-05-31 17:37:46 +02:00
Gwendal Roué 88fac9e21d Merge pull request #362 from hartbit/scanf-buffer-overflow
Fix buffer overflow in vsscanf date parsing
2018-05-31 17:11:35 +02:00
David Hart d601e06f25 Fix buffer overflow in vsscanf date parsing 2018-05-31 17:07:23 +02:00
Gwendal Roué 6cdcd97912 Associations documentation 2018-05-31 08:21:07 +02:00
Gwendal Roué 8a4fbcc725 Associations documentation: avoid explicit databaseTableName when possible 2018-05-31 08:19:49 +02:00
Gwendal Roué e9cbbe2903 Documentation 2018-05-28 14:25:08 +02:00
Gwendal Roué 366e049ddf Bring GRDBDemo to GRDB 3 2018-05-25 07:26:15 +02:00
Gwendal Roué 4e73c31662 Fix documentation typo 2018-05-24 23:05:59 +02:00
Gwendal Roué 0d2079df42 keypath-based expressions? 2018-05-24 05:56:29 +02:00
Gwendal Roué 318e7455e7 Update Package.swift for Swift 4.1 2018-05-24 05:56:03 +02:00
Gwendal Roué eb7c98c510 Fix GRDB3 SPM doc 2018-05-23 12:11:43 +02:00
Gwendal Roué ac955873f2 Improve documentation for persistable protocol choice 2018-05-23 08:36:29 +02:00
Gwendal Roué 051f0416a4 Extend the "thank you" notice 2018-05-23 08:19:40 +02:00
Gwendal Roué c96ed597ed Merge pull request #356 from pocketpixels/patch-1
Fixing type used in 'Demographics BelongsTo Country' example
2018-05-23 08:16:57 +02:00
Gwendal Roué 5ccf87802e Merge pull request #355 from groue/GRDB3-AutomaticTableName
Automatic table name generation
2018-05-23 06:27:38 +02:00
pocketpixels c93f3cda06 Fixed type used in 'Demographics BelongsTo Country' example
I am reading this for the first time, so I might be wrong, but I strongly suspect the type in the belongsTo() call should be Country?
2018-05-22 23:18:18 -04:00
Gwendal Roué 2e477feb33 TableRecord documentation 2018-05-22 23:51:19 +02:00
Gwendal Roué dcb626b32b TableRecord documentation 2018-05-22 23:48:01 +02:00
Gwendal Roué ce03deeccc Change log for default implementation for TableRecord.databaseTableName 2018-05-22 23:31:37 +02:00
Gwendal Roué 1213fa0a43 Document default implementation for TableRecord.databaseTableName 2018-05-22 23:18:33 +02:00
Gwendal Roué 76299d9302 Document default implementation for TableRecord.databaseTableName in GRDB2 Migration Guide 2018-05-22 22:58:15 +02:00
Gwendal Roué 7b59c097c6 Test for default implementation for TableRecord.databaseTableName 2018-05-22 22:43:01 +02:00
Gwendal Roué af8971bcd8 Default implementation for TableRecord.databaseTableName 2018-05-22 22:14:18 +02:00
Gwendal Roué 5de7a5274e Remove useless #if swift(>=3.1) 2018-05-22 20:32:24 +02:00
Gwendal Roué e0a1ee4c10 Merge pull request #354 from fpillet/linux-support
Main framework compiles on Linux
2018-05-21 09:35:54 +02:00
Gwendal Roué cdf5462005 Harmonize fetching methods with CustomizedDecodingOfDatabaseRows playground 2018-05-21 08:39:48 +02:00
Gwendal Roué 86f084cb3e Fix DatabaseRegion inline documentation 2018-05-21 08:27:47 +02:00
Gwendal Roué 5d7245af2a Fix DatabaseRegion documentation formatting 2018-05-21 08:26:06 +02:00
Gwendal Roué cacc3e8456 Fix DatabasePool.makeSnapshot() documentation 2018-05-21 08:21:36 +02:00
Gwendal Roué 0620b1b513 Associations: inline documentation 2018-05-21 07:53:06 +02:00
Gwendal Roué 4eac0797fa Less TODO 2018-05-21 07:39:30 +02:00
Gwendal Roué 07176e941b Associations: inline documentation 2018-05-21 07:35:25 +02:00
Gwendal Roué dadece1b04 Associations: inline documentation 2018-05-20 19:35:18 +02:00
Gwendal Roué b98992eb18 Associations: inline documentation 2018-05-20 19:05:45 +02:00
Gwendal Roué 0191d64f56 Associations: inline documentation 2018-05-20 18:55:14 +02:00
Gwendal Roué 02d5b9c014 Associations: inline documentation 2018-05-20 18:13:34 +02:00
Gwendal Roué aa81b992c4 Associations: inline documentation 2018-05-20 17:48:22 +02:00
Gwendal Roué 9be001533c Fix inner link 2018-05-20 16:16:02 +02:00
Gwendal Roué 7be345521b Associations: new "DerivableRequest Protocol" documentation chapter 2018-05-20 16:14:23 +02:00
Gwendal Roué 67e48f8ad7 CustomizedDecodingOfDatabaseRows 2018-05-20 15:45:59 +02:00
Florent Pillet c0bd8ce917 Rolled back to previous NSUUID extension as compiler freaks out on a more modern implementation 2018-05-20 14:37:59 +02:00
Florent Pillet da65deec69 Removed LinuxMain.swift 2018-05-20 14:21:41 +02:00
Florent Pillet 34db8efea0 Added missing LinuxMain.swift 2018-05-20 00:44:59 +02:00
Florent Pillet df8887be05 Fix NSUUID compilation issue (now using more Swift code) 2018-05-20 00:27:02 +02:00
Florent Pillet 55472c2d7f Main framework compiles on Linux 2018-05-19 18:52:35 +02:00
Gwendal Roué 2a1c87f24a Link to "Customized Decoding of Database Rows" from the "Custom Requests" chapter 2018-05-19 18:45:13 +02:00
Gwendal Roué 88c4f02f5d Fix typo 2018-05-19 18:04:55 +02:00
Gwendal Roué 3017668ba2 Fix typo 2018-05-19 13:58:57 +02:00
Gwendal Roué 4f5fdf45e8 More reasons not to fear leaving FetchableRecord 2018-05-19 13:27:24 +02:00
Gwendal Roué 6037c418cb New "Customized Decoding of Database Rows" documentation chapter 2018-05-19 12:52:51 +02:00
Gwendal Roué 785853dd2b Move the Custom Value Types chapter 2018-05-19 12:28:52 +02:00
Gwendal Roué 2ce2b4885d Rename playground 2018-05-19 12:26:38 +02:00
Gwendal Roué 5637514dd6 AlternateRowDecoder playground 2018-05-19 12:25:35 +02:00
Gwendal Roué 0a3a8d738a AlternateRowDecoder playground 2018-05-18 19:20:03 +02:00
Gwendal Roué 1d1c7fc467 Merge branch 'GRDB3' of github.com:groue/GRDB.swift into GRDB3 2018-05-18 18:47:42 +02:00
Gwendal Roué 1f274f5c04 More AlternateRowDecoder playground 2018-05-18 18:47:12 +02:00
Gwendal Roué eddc078c2d Prepare AlternateRowDecoder playground 2018-05-18 14:29:03 +02:00
Gwendal Roué 5136142d83 Playgrounds documentation 2018-05-18 08:49:47 +02:00
Gwendal Roué 857798b939 Extend the "thank you" notice 2018-05-15 13:35:36 +02:00
Gwendal Roué 82d8fd65d0 Merge pull request #350 from fpillet/patch-1
Use `String(format: ...)`
2018-05-13 15:15:05 +02:00
Florent Pillet 2de040a6f1 Use String(format: ...)
... instead of `NSString(format: ...) as String`
2018-05-12 15:39:59 +02:00
Gwendal Roué aead6eec4a Sometimes you don't understand what you read because information is not given at the right time 2018-05-07 19:39:13 +02:00
Gwendal Roué 756863152c Fix documentation typos 2018-05-07 19:33:07 +02:00
Gwendal Roué c1c3233ba2 Remove two useless .init (thank you Xcode autocomplete) 2018-05-07 19:23:33 +02:00
Gwendal Roué 91ad986d0b Cleanup and add internal documentation for the non-trivial TableAlias 2018-05-07 19:17:19 +02:00
Gwendal Roué a35f012286 Cleanup 2018-05-07 17:50:27 +02:00
Gwendal Roué 56a0dab443 Typo 2018-05-07 09:10:50 +02:00
Gwendal Roué 69cf95e828 Typo 2018-05-06 20:03:28 +02:00
Gwendal Roué 56ae745851 Prepare v3.0.0-beta.1 release 2018-05-06 14:55:39 +02:00
Gwendal Roué 62f985469c Update WhyAdoptGRDB.md for GRDB3 2018-05-06 14:53:49 +02:00
Gwendal Roué a12bc2e90e Tweaks in GRDB2MigrationGuide.md 2018-05-06 14:44:32 +02:00
Gwendal Roué 402f9d3ba9 Tweaks in AssociationBasics.md 2018-05-06 14:43:44 +02:00
Gwendal Roué a360976e23 ForeignKey initializer accepts ColumnExpression 2018-05-06 14:15:12 +02:00
Gwendal Roué de6667a236 WIP: GRDB2MigrationGuide.md 2018-05-06 12:44:06 +02:00
Gwendal Roué 6db0831bfd fix links 2018-05-06 12:12:11 +02:00
Gwendal Roué 26607ba193 WIP: GRDB2MigrationGuide.md 2018-05-06 11:56:02 +02:00
Gwendal Roué 15299eaac0 WIP: GRDB2MigrationGuide.md 2018-05-06 11:53:19 +02:00
Gwendal Roué 9c9217727c WIP: GRDB2MigrationGuide.md 2018-05-06 11:10:42 +02:00
Gwendal Roué 6434f0cdb1 WIP: GRDB2MigrationGuide.md 2018-05-06 11:09:44 +02:00
Gwendal Roué 7a520f3269 WIP: GRDB2MigrationGuide.md 2018-05-06 10:55:39 +02:00
Gwendal Roué cc7cf597f3 WIP: GRDB2MigrationGuide.md 2018-05-06 10:50:14 +02:00
Gwendal Roué 0a6b34bb85 Merge pull request #348 from groue/GRDB3-RxGRDB
GRDB3 Support for RxGRDB
2018-05-06 10:08:44 +02:00
Gwendal Roué 175c96cd38 Update documentation of FetchRequest protocol 2018-05-06 10:03:07 +02:00
Gwendal Roué cce0e332e0 Update documentation of FetchRequest protocol 2018-05-06 10:01:10 +02:00
Gwendal Roué 214748fe5a DatabaseRegion.fullDatabase is public 2018-05-06 09:11:00 +02:00
Gwendal Roué dc7bdfed50 More fixits for DatabaseRegion 2018-05-05 12:02:50 +02:00
Gwendal Roué 2d008b8c54 Yet another request protocols update, in order to empower RxGRDB 2018-05-05 11:57:17 +02:00
Gwendal Roué 310c2637cb Merge pull request #347 from groue/GRDB3-DerivableRequest
Common API for requests and associations derivation
2018-05-05 11:56:59 +02:00
Gwendal Roué 264bceee2a Cleanup 2018-05-04 14:28:29 +02:00
Gwendal Roué cdad6fa313 Introduce DerivableRequest 2018-05-04 14:19:27 +02:00
Gwendal Roué babaefca8f WIP: GRDB2MigrationGuide.md 2018-05-04 10:48:56 +02:00
Gwendal Roué 6a4382c323 TODO 2018-05-04 08:32:51 +02:00
Gwendal Roué 231906e5ea WIP: GRDB2MigrationGuide.md 2018-05-03 10:17:38 +02:00
Gwendal Roué 1c9db9ec10 WIP: GRDB2MigrationGuide.md 2018-05-03 08:55:52 +02:00
Gwendal Roué 31e927f9da WIP: GRDB2MigrationGuide.md 2018-05-03 08:54:50 +02:00
Gwendal Roué 26b9030eaa WIP: GRDB2MigrationGuide.md 2018-05-03 08:53:19 +02:00
Gwendal Roué da38df6bd6 WIP: GRDB2MigrationGuide.md 2018-05-03 08:51:31 +02:00
Gwendal Roué ebb1eba96f WIP: GRDB2MigrationGuide.md 2018-05-03 08:34:02 +02:00
Gwendal Roué c7a1daa8e5 WIP: GRDB2MigrationGuide.md 2018-05-02 21:55:53 +02:00
Gwendal Roué 0aa75f418f WIP: GRDB2MigrationGuide.md 2018-05-02 21:27:03 +02:00
Gwendal Roué a5d56d38d6 WIP: GRDB2MigrationGuide.md 2018-05-02 20:03:56 +02:00
Gwendal Roué fa04627ece WIP: GRDB2MigrationGuide.md 2018-05-02 19:57:36 +02:00
Gwendal Roué 33ec30438d WIP: GRDB2MigrationGuide.md 2018-05-02 19:52:26 +02:00
Gwendal Roué e3ab3a991e WIP: GRDB2MigrationGuide.md 2018-05-02 18:47:34 +02:00
Gwendal Roué 287422f2f8 WIP: GRDB2MigrationGuide.md 2018-05-02 13:59:15 +02:00
Gwendal Roué e184963b8f WIP: GRDB2MigrationGuide.md 2018-05-02 13:40:33 +02:00
Gwendal Roué 06f9a4601c TODO 2018-05-02 07:43:16 +02:00
Gwendal Roué 7a30eb2613 Merge pull request #319 from groue/GRDB3-Associations
Associations & Joins
2018-05-01 21:48:06 +02:00
Gwendal Roué 5160b69c34 Merge branch 'GRDB3' into GRDB3-Associations 2018-05-01 21:47:44 +02:00
Gwendal Roué fa00b8ad99 Associations and Joins documentation 2018-05-01 21:44:43 +02:00
Gwendal Roué 1bf7f67008 Update inline documentation with singular table names 2018-05-01 20:32:18 +02:00
Gwendal Roué 872d6d21ac Update README.md with singular table names 2018-05-01 19:01:45 +02:00
Gwendal Roué ab36df6e0f Use "finalized" to describe queries that are ready for SQL generation 2018-05-01 17:42:39 +02:00
Gwendal Roué ffaabdfd62 Toward improved DatabaseRegion for joined requests 2018-05-01 17:20:37 +02:00
Gwendal Roué 8e2cdeebc3 Cleanup 2018-05-01 15:03:36 +02:00
Gwendal Roué a3189f79b6 StatementArguments: no more need for internal setters 2018-05-01 14:52:03 +02:00
Gwendal Roué 66a425f718 Thread-safe table name disambiguation, via SQLGenerationContext. Merge SQLTableQualifier into TableAlias. 2018-05-01 14:44:51 +02:00
Gwendal Roué 344eba821f Spot more qualifier/alias problems 2018-04-30 19:31:56 +02:00
Gwendal Roué 8d5e57873e Documentation 2018-04-30 15:33:16 +02:00
Gwendal Roué 9f78a758bd RowAdapter.addingScopes returns self if the scopes dictionary is empty 2018-04-30 14:04:07 +02:00
Gwendal Roué e6f084d397 Law of Demeter 2018-04-30 13:59:20 +02:00
Gwendal Roué 09458c1d37 Documentation, move asRequest(of:) to QueryInterfaceRequest in order to avoid AnyFetchRequest contamination 2018-04-30 13:41:20 +02:00
Gwendal Roué 9a379fc1bc Use DatabasePromise where relevant 2018-04-30 12:57:12 +02:00
Gwendal Roué a45d019472 Simplification
Rename AssociationMapping to JoinCondition
Replace AssociationMappingRequest enum with ForeignKeyJoinConditionRequest struct
Rename AssociationChainOperator to AssociationJoinOperator, and "chain" to "join"
2018-04-30 12:50:38 +02:00
Gwendal Roué 50dd846a36 Remove useless constraint on Association.LeftAssociated and Association.RightAssociated 2018-04-30 12:25:07 +02:00
Gwendal Roué dddeff458a none() is no longer a requirement of FilteredRequest 2018-04-30 09:02:05 +02:00
Gwendal Roué ae162a88c6 Upgrade .swift-version and Swift badge to 4.1 2018-04-30 08:57:10 +02:00
Gwendal Roué ccc259c25c Documentation 2018-04-30 08:55:16 +02:00
Gwendal Roué 5e7235307a Cleanup 2018-04-30 08:36:29 +02:00
Gwendal Roué 5747d1cff0 No more #if swift(>=4.1) 2018-04-30 08:26:23 +02:00
Gwendal Roué e05a64f1cb Cleanup 2018-04-30 08:11:16 +02:00
Gwendal Roué 83104769ef Conditional Conformance requires Swift 4.1 and Xcode 9.3+ 2018-04-29 19:21:10 +02:00
Gwendal Roué 39c5313738 Associations Documentation 2018-04-29 18:45:51 +02:00
Gwendal Roué d6f088609e Prevent chaining required association behind an optional one 2018-04-29 18:34:49 +02:00
Gwendal Roué 4586eb9a82 Associations Documentation 2018-04-29 18:27:59 +02:00
Gwendal Roué a16bd6b54e Associations Documentation 2018-04-29 18:18:33 +02:00
Gwendal Roué 3e46942f30 Associations 2018-04-29 18:16:39 +02:00
Gwendal Roué df79bb8ed8 whitespace 2018-04-28 10:36:58 +02:00
Gwendal Roué d6183a4745 Typo 2018-04-28 10:29:56 +02:00
Gwendal Roué bf470b5870 Documentation 2018-04-27 18:01:11 +02:00
Gwendal Roué 175656aa26 Documentation 2018-04-27 09:01:13 +02:00
Gwendal Roué 497295a0c6 Merge pull request #342 from groue/GRDB3-reversedCleanup
Reversing unordered requests
2018-04-26 19:45:27 +02:00
Gwendal Roué 0f21f886b4 Document that request.reversed() has no effect when request is not already ordered 2018-04-26 12:54:28 +02:00
Gwendal Roué f4382e6bcb Test that request.reversed() has no effect when request is not already ordered 2018-04-26 12:52:01 +02:00
Gwendal Roué 26108badd4 request.reversed() has no effect when request is not already ordered 2018-04-26 12:51:29 +02:00
Gwendal Roué 2ae93a2a0b Honor #337 2018-04-26 09:01:33 +02:00
Gwendal Roué d8860d2527 Typo 2018-04-26 08:27:37 +02:00
Gwendal Roué 40cfbd8c9c Update Documentation for the implicit transactions opened by the write method 2018-04-26 08:26:39 +02:00
Gwendal Roué 6dea09ec24 Typo 2018-04-26 08:05:57 +02:00
Gwendal Roué 8d84050f77 Typo 2018-04-26 07:58:06 +02:00
Gwendal Roué af8801c28a TODO 2018-04-26 07:45:16 +02:00
Gwendal Roué 58edfcbc99 Typo 2018-04-26 07:18:02 +02:00
Gwendal Roué 25748566ea No more obsolete string.characters in documentation 2018-04-26 07:14:57 +02:00
Gwendal Roué 66bd7cff77 Typo 2018-04-26 06:40:26 +02:00
Gwendal Roué d09afc8929 explicitely -> explicitly 2018-04-25 19:35:03 +02:00
Gwendal Roué 92f037eb74 Merge remote-tracking branch 'origin/master' into GRDB3 2018-04-25 19:32:44 +02:00
Gwendal Roué 7032bb6416 Typo 2018-04-25 11:28:43 +02:00
Gwendal Roué 433f4e828f TODO 2018-04-25 11:06:19 +02:00
Gwendal Roué 319baad70c Typo 2018-04-25 11:00:26 +02:00
Gwendal Roué 56d06d0889 Honor #337 2018-04-25 10:59:07 +02:00
Gwendal Roué 727491ca1a New usage section: database observation 2018-04-25 10:57:42 +02:00
Gwendal Roué bc57d67a91 Rewrite usage section with details HTML tags 2018-04-25 10:49:35 +02:00
Gwendal Roué 4754a9dbe0 Minor 2018-04-25 09:12:43 +02:00
Gwendal Roué c4bb84a88f Fix outdated documentation 2018-04-25 09:10:03 +02:00
Gwendal Roué 543c361f87 Enhance documentation 2018-04-25 09:06:29 +02:00
Gwendal Roué e5c4409ad4 Enhance documentation 2018-04-25 08:57:44 +02:00
Gwendal Roué 5fe609ae5c TODO 2018-04-24 09:32:07 +02:00
Gwendal Roué f1baa0503f #339 follow-up: extend the thank you notice :-) 2018-04-23 14:46:12 +02:00
Gwendal Roué 9d8015925d Merge pull request #339 from kluufger/patch-1
fix small typo in readme
2018-04-23 14:44:04 +02:00
Gwendal Roué 32ec7504e5 Merge pull request #340 from groue/GRDB3-SQLColumnExpression
ColumnExpression Protocol
2018-04-23 14:10:56 +02:00
kluufger 16513dc387 as -> at 2018-04-23 11:51:16 +00:00
kluufger 4804f78042 datase -> database 2018-04-23 11:20:47 +00:00
kluufger eae2c38e23 sharedApplication() -> shared 2018-04-23 11:06:17 +00:00
kluufger 7ffc2faa9a uppercase -> uppercased since later it's called as uppercased 2018-04-23 11:00:23 +00:00
kluufger 6f03d51390 fix link 2018-04-23 07:18:32 +00:00
Gwendal Roué 4409b07ef5 ColumnExpression documentation 2018-04-23 08:39:19 +02:00
Gwendal Roué 5ee390f0da No more support for CodingKey & ColumnExpression 2018-04-23 08:19:15 +02:00
kluufger 3aa5719600 identity -> identify 2018-04-22 21:01:12 +00:00
kluufger 70e6454c38 fix typo 2018-04-22 19:49:06 +00:00
Gwendal Roué d6f93afffe Update documentation in order to foster column enums 2018-04-22 19:10:10 +02:00
Gwendal Roué f2ae44384f Rename SQLColumnExpression to ColumnExpression 2018-04-22 18:13:47 +02:00
kluufger 3c290ed6e2 case-unsensitive -> case-insensitive 2018-04-22 15:59:17 +00:00
kluufger 85849a889f parent -> parents
not sure about this one, where do `(c, d)` come from?
2018-04-22 15:42:04 +00:00
kluufger 4993198266 no need for the ellipses 2018-04-22 15:38:05 +00:00
kluufger ee7b8f74d7 update db.create(table: "example") 2018-04-22 15:35:50 +00:00
kluufger 8fd321f823 add .unique() to email column 2018-04-22 15:12:46 +00:00
kluufger 0526994603 one more 2018-04-22 14:55:51 +00:00
kluufger 0688305f86 fix small typo in readme 2018-04-22 14:44:32 +00:00
Gwendal Roué e54ccdfc54 Tests for SQLColumnExpression 2018-04-22 14:56:51 +02:00
Gwendal Roué 29b364d5cb Introduce SQLColumnExpression 2018-04-22 14:56:40 +02:00
Gwendal Roué 71d602850e Typo 2018-04-22 13:49:13 +02:00
Gwendal Roué b590ee5444 Typo 2018-04-22 13:39:28 +02:00
Gwendal Roué db31a94461 Typo 2018-04-22 13:35:36 +02:00
Gwendal Roué 405b537ef2 Typo 2018-04-22 13:32:26 +02:00
Gwendal Roué 6722ea8676 Typo 2018-04-22 13:29:52 +02:00
Gwendal Roué d3879567c4 New "Examples of Record Definitions" chapter (addresses #338) 2018-04-22 13:26:40 +02:00
Gwendal Roué 4c6147fc37 Documentation 2018-04-22 12:05:11 +02:00
Gwendal Roué b2d2d17dda #330 follow-up: extract QualifiedAllColumns from AllColumns 2018-04-22 07:26:08 +02:00
Gwendal Roué 2dae6d945f #330 follow-up: extract QualifiedColumn from Column 2018-04-22 07:17:26 +02:00
Gwendal Roué ddc551626c Merge pull request #337 from groue/GRDB3-autoIncrementedPrimaryKey
Foster auto-incremented primary keys
2018-04-22 06:39:42 +02:00
Gwendal Roué 7aacaef2cd Foster autoIncrementedPrimaryKey in documentation 2018-04-21 20:11:34 +02:00
Gwendal Roué e80dab2ea9 Documentation for TableDefinition.autoIncrementedPrimaryKey 2018-04-21 19:42:27 +02:00
Gwendal Roué 822ff97050 Tests for TableDefinition.autoIncrementedPrimaryKey 2018-04-21 19:41:45 +02:00
Gwendal Roué 73e89f76aa Introduce TableDefinition.autoIncrementedPrimaryKey 2018-04-21 19:41:21 +02:00
Gwendal Roué c21a330dce Cleanup 2018-04-21 19:40:30 +02:00
Gwendal Roué b8fc762e11 Cleanup 2018-04-21 19:28:58 +02:00
Gwendal Roué e44249be1c Merge pull request #336 from groue/GRDB3-LogicalOperatorRefactoring
Enhancements to logical operators
2018-04-21 19:06:36 +02:00
Gwendal Roué f4ab65e399 Fix typo 2018-04-21 17:21:16 +02:00
Gwendal Roué d63565f191 Documentation for joined(operator:) 2018-04-21 17:17:46 +02:00
Gwendal Roué 729f6bdc6c Tests for joined(operator:) 2018-04-21 17:05:03 +02:00
Gwendal Roué c691625b15 Dedicated implementations for AND and OR sql operators. Introduce joined(operator:) 2018-04-21 16:53:44 +02:00
Gwendal Roué 4e57bf5a0e Fix a youth error: DatabaseDateComponents initializer from DateComponents is no longer failable 2018-04-21 15:27:21 +02:00
Gwendal Roué 223d0a3fd3 Merge remote-tracking branch 'origin/development' into GRDB3 2018-04-21 15:20:36 +02:00
Gwendal Roué 00fa47b6b7 Family gets bigger :-) 2018-04-21 15:04:54 +02:00
Gwendal Roué f52536f4ae Append #334 to CHANGELOG 2018-04-21 15:04:37 +02:00
Gwendal Roué 76e1d4381d Merge pull request #334 from sobri909/development
Improve date parsing performance and memory footprint
2018-04-21 14:49:13 +02:00
Gwendal Roué 6c5d6ba631 SQLiteDateParser: tighten vsscanf format 2018-04-21 10:37:03 +02:00
Gwendal Roué 1311f6c87c SQLiteDateParser: fix nanosecond parsing 2018-04-21 10:17:07 +02:00
Gwendal Roué 219f96a11a More DatabaseDateComponents parsing tests 2018-04-21 10:16:49 +02:00
Gwendal Roué 8b175280fa TODO 2018-04-21 07:40:11 +02:00
Gwendal Roué 632bce5521 SQLiteDateParser: don't parse garbage into nanoseconds 2018-04-20 19:41:34 +02:00
Gwendal Roué 316d28746b SQLiteDateParser: optimize nanoseconds parsing 2018-04-20 19:26:42 +02:00
Gwendal Roué 9efe4a6efa Add a sanity check 2018-04-20 19:18:46 +02:00
Gwendal Roué 85fbf64068 Add missing imports (should fix travis issues) 2018-04-20 19:17:24 +02:00
Gwendal Roué 282255b841 No need for useScanfStrategy any longer 2018-04-20 19:14:58 +02:00
Gwendal Roué 9e380e5fea Cleanup 2018-04-20 19:14:32 +02:00
Gwendal Roué f12495b24a New DateParsingTests in GRDBOSXPerformanceTests 2018-04-20 19:06:02 +02:00
Gwendal Roué 266040747e Date adopts StatementColumnConvertible 2018-04-20 18:42:12 +02:00
Gwendal Roué 11a4a6acbd Documentation 2018-04-20 18:41:58 +02:00
Gwendal Roué c70689fe54 Check useScanfStrategy in DatabaseDateComponents.init(sqliteStatement:index:)
...so that we can eventually compare gains
2018-04-20 18:34:19 +02:00
Gwendal Roué 936b31f1f0 DatabaseDateComponents adopts StatementColumnConvertible
We'll need benchmarks to evaluate the gain, here
2018-04-20 14:04:12 +02:00
Gwendal Roué 8915672ce5 SQLiteDateParser: parse C strings
Since the goal of this PR is efficiency, we'll soon parse Date and
DatabaseDateComponents right from raw SQLite buffers.
2018-04-20 13:51:20 +02:00
Gwendal Roué 0640f90fc1 (whitespace) 2018-04-20 13:32:50 +02:00
Gwendal Roué d1a0e8d906 SQLiteDateParser.components(from:) is not public 2018-04-20 13:31:57 +02:00
Gwendal Roué e9a668ca56 SQLiteDateParser: no more static methods 2018-04-20 13:31:35 +02:00
Gwendal Roué 27194c802d SQLiteDateParser: use withUnsafeMutablePointer instead of allocations
OK, not really: the nanosecond components remains in the heap.
But we may find a way to put 11 chars on the stack.
2018-04-20 13:30:26 +02:00
Gwendal Roué 7aabfeaeac SQLiteDateParser: get rid of the mutex 2018-04-20 13:09:22 +02:00
Gwendal Roué 6d9bce3a25 Add SQLiteDateParser.swift to GRDBCustom and GRDBCipher
... so that all GRDB flavors can use the new technique.
GRDB has three distinct projects since #282.
2018-04-20 13:08:17 +02:00
Gwendal Roué efa0e3850f GRDB3 TODO 2018-04-20 06:16:10 +02:00
Gwendal Roué 1e7e011a61 Merge pull request #335 from groue/GRDB3-RowLookup
Row scopes collection, breadth-first scope search
2018-04-20 06:00:52 +02:00
Gwendal Roué e45642b6c1 Cleanup 2018-04-19 21:48:12 +02:00
Gwendal Roué b550e2bfd5 Cleanup 2018-04-19 21:45:40 +02:00
Gwendal Roué 4b3854d05d Finally, the meat: perform breadth-first search in let record = row[key], and in FetchableRecord & Decodable 2018-04-19 20:46:58 +02:00
Gwendal Roué 0362ae76ea Rename Row.Scopes to Row.ScopesView. Move breadth-first lookup to a new view, row.scopesTree, of type Row.ScopesTreeView 2018-04-19 20:29:11 +02:00
Gwendal Roué 098c11baf2 Row.Scopes.lookup(_:) performs a breadth-first lookup of a scope name 2018-04-19 19:50:43 +02:00
Gwendal Roué 4e659c550e Rename RowScopes to Row.Scopes. Harmonize row derivation. 2018-04-19 19:18:02 +02:00
Gwendal Roué 9cb1bac2fc Update documentation for scoped rows 2018-04-19 14:46:23 +02:00
Gwendal Roué 33d65e85d8 Update documentation for scoped rows 2018-04-19 14:44:05 +02:00
Gwendal Roué 7e260cf537 Update tests for new Row.scopes view 2018-04-19 14:41:49 +02:00
Gwendal Roué 57932235ba Introduce RowScopes collection, a view of a row's scopes 2018-04-19 09:07:16 +02:00
Gwendal Roué 2daba261a2 GRDB3 TODO 2018-04-19 08:09:46 +02:00
Gwendal Roué 9a6daedd6d Cleanup 2018-04-18 07:31:11 +02:00
Matt Greenfield 3b546dedd8 truncate nanosecond precision to 3 sig figs 2018-04-17 15:17:09 +07:00
Matt Greenfield 7320f88066 Revert "fix the tests to expect less nanosecond precision loss"
This reverts commit eba5df1fcc.
2018-04-17 15:14:18 +07:00
Matt Greenfield bde72e562e Revert "permit precision loss down to 3 sig figs"
This reverts commit 3bcc5b8064.
2018-04-17 15:14:09 +07:00
Matt Greenfield 33066133fc truncate date/time strings that include seconds precision beyond the nanosecond scale 2018-04-17 14:32:33 +07:00
Matt Greenfield 3bcc5b8064 permit precision loss down to 3 sig figs 2018-04-17 13:20:11 +07:00
Matt Greenfield eba5df1fcc fix the tests to expect less nanosecond precision loss 2018-04-17 12:57:59 +07:00
Matt Greenfield dad163771f not all nanosecond fractions have 3 sig figs, so can't hard code the acceptable string lengths 2018-04-17 12:38:23 +07:00
Matt Greenfield bb59f5e6f7 0.123 is not the same thing as 0.000123 2018-04-17 11:05:47 +07:00
Matt Greenfield 7a1aa88edb fractions of seconds are not the same thing as integer counts of nanoseconds 2018-04-16 19:18:49 +07:00
Gwendal Roué a2c06c1bdb Cleanup 2018-04-16 14:05:36 +02:00
Gwendal Roué 2a2c5a772f Cleanup 2018-04-16 14:05:04 +02:00
Gwendal Roué 969fac5c4b Cleanup 2018-04-16 14:01:54 +02:00
Matt Greenfield b444d376f4 differentiate between SS and SS.SSS formats 2018-04-16 17:39:41 +07:00
Matt Greenfield 59d7909f50 return correct Format for partial date/time combinations 2018-04-16 17:21:00 +07:00
Matt Greenfield f5f8ab5971 add SQLiteDateParser to project file 2018-04-16 16:32:32 +07:00
Matt Greenfield 362c4baeca initial scanf() based date string parser 2018-04-16 14:02:15 +07:00
Gwendal Roué d39f02113c Restore T.fetchXXX(db, request) APIs which were removed in PR #311 2018-04-16 08:50:55 +02:00
Gwendal Roué c9dc1223dd Harmonize dbQueue.writer with dbPool.writer 2018-04-15 20:14:25 +02:00
Gwendal Roué ba848d2d53 Less TODO 2018-04-15 19:57:36 +02:00
Gwendal Roué 1c9c3d4399 Merge pull request #332 from groue/GRDB3-DatabaseWriterRobustness
Implicit transaction in DatabasePool.write and DatabaseQueue.write
2018-04-15 19:51:52 +02:00
Gwendal Roué 090f872e80 Update documentation: don't mention dbQueue.inDatabase unless necessary 2018-04-15 18:09:34 +02:00
Gwendal Roué 3d9c1a2739 Cleanup 2018-04-15 17:26:37 +02:00
Gwendal Roué c97c260613 Update documentation about transactions 2018-04-15 17:15:13 +02:00
Gwendal Roué a46505e907 Cleanup 2018-04-15 14:30:12 +02:00
Gwendal Roué ea3f22c8a4 Fix tests that were failing now that DatabaseQueue.inDatabase runs inside a transaction 2018-04-13 18:07:24 +02:00
Gwendal Roué d78479e4af [WIP] DatabaseQueue.inDatabase runs inside a transaction 2018-04-13 08:56:03 +02:00
Gwendal Roué 267371ba90 Tests that DatabasePool.write opens a transaction 2018-04-13 08:20:17 +02:00
Gwendal Roué cc136922e5 Typo 2018-04-12 14:07:38 +02:00
Gwendal Roué 02927106ca It looks like documentation wants that DatabaseQueue automatically opens transactions as well... 2018-04-12 14:06:13 +02:00
Gwendal Roué 1275ebc2b1 Layout 2018-04-12 14:02:31 +02:00
Gwendal Roué 2ac2a148c6 Typo 2018-04-12 14:00:19 +02:00
Gwendal Roué 1a5f432ee1 Update documentation for DatabasePool.writeWithoutTransaction 2018-04-12 13:59:10 +02:00
Gwendal Roué 5df4e713b6 GRDB3 TODO 2018-04-12 12:39:29 +02:00
Gwendal Roué 20d2c74f87 Update documentation for DatabasePool.writeWithoutTransaction 2018-04-12 12:02:25 +02:00
Gwendal Roué bc244802c0 Update tests for DatabasePool/Writer.writeWithoutTransaction 2018-04-12 07:58:23 +02:00
Gwendal Roué bd2f17ee10 Fixes needed by DatabasePool/Writer.writeWithoutTransaction 2018-04-12 07:58:01 +02:00
Gwendal Roué 563a4d5c71 Introduce DatabaseWriter.writeWithoutTransaction 2018-04-11 20:03:18 +02:00
Gwendal Roué 78e6241d16 DatabaseWriter.write now guarantees that eventual concurrent readers don't see any changes until all changes are executed. DatabasePool.write thus wraps changes in a transaction. 2018-04-11 20:03:18 +02:00
Gwendal Roué d08f630a2c Merge pull request #331 from groue/GRDB3-RowDescription
Improve Row descriptions
2018-04-11 20:02:31 +02:00
Gwendal Roué 26912e746b Update documentation for new Row description format 2018-04-11 15:49:16 +02:00
Gwendal Roué fa68b62be1 Improve Row.description & Row.debugDescription 2018-04-11 13:39:44 +02:00
Gwendal Roué 07a1d4d1b8 Database.rollback: add missing dispatch queue check 2018-04-11 13:21:56 +02:00
Gwendal Roué 9c6b48980c Database.isInsideTransaction: add missing dispatch queue check 2018-04-11 13:18:34 +02:00
Gwendal Roué 79c7dd03a5 [Whitespace] 2018-04-11 13:10:15 +02:00
Gwendal Roué b252c689df Merge pull request #330 from groue/GRDB3-RemovePATs
Expressions are no longer PATs
2018-04-11 13:08:46 +02:00
Gwendal Roué c34380cf5c SQLExpression and SQLSelectable are no longer PATs 2018-04-11 08:19:15 +02:00
Gwendal Roué 75ab9d615c Merge pull request #329 from groue/GRDB3-RequestDerivation
Introduce request derivation protocols
2018-04-11 08:04:30 +02:00
Gwendal Roué b9333fab34 Update a few tests that have been broken by 64899e5a39.
(Some expressions which were not safely wrapped inside parenthesis now are wrapped inside parenthesis)
2018-04-10 13:45:31 +02:00
Gwendal Roué 64899e5a39 Introduce SelectionRequest, FilteredRequest, AggregatingRequest, and OrderedRequest.
Those request protocols allow types that are not QueryInterfaceRequest to expose the same derivation API. This is a necessary step towards associations.
2018-04-10 13:44:23 +02:00
Gwendal Roué 80889dc9d2 Merge pull request #328 from groue/GRDB3-DatabaseRequest
Allow observation of complex fetching strategies
2018-04-10 12:50:37 +02:00
Gwendal Roué b7239c4b6f Document request protocols 2018-04-08 13:18:02 +02:00
Gwendal Roué 67ae1d4cf0 Document request protocols 2018-04-08 13:09:24 +02:00
Gwendal Roué 03f5a83cbf Introduce and DatabaseRequest and SelectStatementRequest on top of FetchRequest 2018-04-08 12:08:51 +02:00
Gwendal Roué 77bb2ecc82 Merge branch 'SQLite-3.22.0' of github.com:groue/GRDB.swift into GRDB3 2018-04-08 11:51:56 +02:00
Gwendal Roué 3160b65172 Upgrade SQLiteCustom to 3.22.0 2018-04-04 13:23:46 +02:00
Gwendal Roué 65b3ba1d12 TODO 2018-04-04 09:49:38 +02:00
Gwendal Roué ce919f0411 GRDB3 TODO 2018-03-31 16:00:34 +02:00
Gwendal Roué 2dfbe8e5f2 Prevent snapshot creation from within a transaction 2018-03-31 15:56:42 +02:00
Gwendal Roué e9d45b5435 GRDB3 TODO 2018-03-31 15:07:19 +02:00
Gwendal Roué c3f9c75b3c Rename databaseEqual to databaseEquals 2018-03-31 14:53:22 +02:00
Gwendal Roué d24f79ee4d Merge branch 'master' into GRDB3 2018-03-31 14:36:43 +02:00
Gwendal Roué 2992bd544e GRDB3 TODO 2018-03-30 10:49:43 +02:00
Gwendal Roué 31ed3ce277 GRDB3 TODO 2018-03-30 09:12:35 +02:00
Gwendal Roué 91b574e153 v2.10.0 2018-03-30 08:32:18 +02:00
Gwendal Roué 7966b43daf Merge pull request #295 from groue/Swift4.1
Xcode 9.3 & Swift 4.1
2018-03-30 08:31:30 +02:00
Gwendal Roué 17dfb0db9d CHANGELOG 2018-03-30 08:19:46 +02:00
Gwendal Roué 2c3a62abbc Update performance tests for Swift 4.1 2018-03-30 08:12:24 +02:00
Gwendal Roué f9a806d9aa Xcode 9.3 artifact: IDEWorkspaceChecks.plist 2018-03-30 07:51:34 +02:00
Gwendal Roué afd2d25e5e Makefile: add support for Xcode 9.3 2018-03-30 07:21:49 +02:00
Gwendal Roué 4ee9580d31 Remove redundant conformance of DatabaseValue to SQLExpressible 2018-03-29 15:31:22 +02:00
Gwendal Roué b35cf4afdc Record.save(_:) documents that is can't be overridden 2018-03-15 20:46:03 +01:00
Gwendal Roué 930246592a Cleanup TODO 2018-03-15 20:32:04 +01:00
Gwendal Roué 727be0a8ab Merge pull request #321 from groue/GRDB3-Testability
Improve testability
2018-03-15 20:25:18 +01:00
Gwendal Roué ebe1d93c3a Polish 2018-03-15 20:22:39 +01:00
Gwendal Roué c7ad3ef4a9 DatabaseMigrator.appliedMigrations(in:) doc & changelog 2018-03-15 20:15:23 +01:00
Gwendal Roué fa8ed89eae DatabaseMigrator.appliedMigrations(_:) 2018-03-15 20:10:59 +01:00
Gwendal Roué 0d7f392bcd Database.isGRDBInternalTable(_:) 2018-03-15 20:04:50 +01:00
Gwendal Roué d61551cedb Database.isSQLiteInternalTable(_:) doc 2018-03-15 19:57:03 +01:00
Gwendal Roué 07b944039c Database.isSQLiteInternalTable(_:) 2018-03-15 19:52:44 +01:00
Gwendal Roué 95933e93dd Fix SQLRequest inline documentation 2018-03-12 23:03:46 +01:00
Gwendal Roué 1cbe60a13f Better checks for Swift < 4.1 (thanks @hartbit!) 2018-03-12 18:33:06 +01:00
Gwendal Roué 9505ba1606 Replace flatMap with compactMap in README.md 2018-03-12 18:20:10 +01:00
Gwendal Roué bca1fe0d9b SE-0184: backport UnsafeMutablePointer.deallocate() 2018-03-12 18:20:10 +01:00
Gwendal Roué 1d28ca1fca TODO Swift 4.1 2018-03-12 18:20:10 +01:00
Gwendal Roué a75e519294 SE-0185: let Swift 4.1 generate as much Equatable and Hashable conformance as possible 2018-03-12 18:20:10 +01:00
Gwendal Roué 75d5c2a39f SE-0187: deprecate Cursor.flatMap in favor of Cursor.compactMap 2018-03-12 18:20:10 +01:00
Gwendal Roué 85d3c584ef Swift 4.1 compatibility (SE-0184 , SE-0187) 2018-03-12 18:20:10 +01:00
Gwendal Roué ad0f6de809 Fix Xcode9.3 warnings 2018-03-12 18:20:10 +01:00
Gwendal Roué 5defb058d3 TODO 2018-03-05 14:22:58 +01:00
Gwendal Roué f202ad5e3f TODO 2018-03-05 10:18:44 +01:00
Gwendal Roué 1cd8467b8f TODO 2018-03-05 09:59:01 +01:00
Gwendal Roué f2462d4270 Improve Record overview 2018-03-02 18:56:43 +01:00
Gwendal Roué 4a4f4e37ba Improve Record overview 2018-03-02 15:13:12 +01:00
Gwendal Roué 3a625157ff README typos 2018-02-28 09:02:48 +01:00
Gwendal Roué 3bbc17fe4a Rename "record changes tracking" to "record comparison" in order to avoid confusion with database changes tracking performed by database observation 2018-02-28 08:58:27 +01:00
Gwendal Roué 8cff147029 TODO.md 2018-02-28 08:41:46 +01:00
Gwendal Roué ce984783ec Intra-doc links 2018-02-28 08:36:58 +01:00
Gwendal Roué dbde432948 Remove deprecated APIs 2018-02-28 08:35:07 +01:00
Gwendal Roué 85f945dcba Merge pull request #314 from groue/GRDB3-RenameRecordProtocols
Rename record protocols
2018-02-27 20:42:10 +01:00
Gwendal Roué 487f4e220f Record protocols fixit 2018-02-27 20:10:13 +01:00
Gwendal Roué 6a8dec11ea Record protocols changelog 2018-02-27 20:10:06 +01:00
Gwendal Roué 1a91020a84 After all, FetchableRecord and PersistableRecord 2018-02-27 19:25:49 +01:00
Gwendal Roué 08a08cd74f Rename MutablePersistable to EncodableRecord 2018-02-27 18:46:32 +01:00
Gwendal Roué 639de6ca11 Rename TableMapping to TableRecord 2018-02-27 13:28:29 +01:00
Gwendal Roué ba6a026cdc Rename RowConvertible to DecodableRecord 2018-02-27 13:17:51 +01:00
Gwendal Roué 07634229f9 GRDB3 TODO 2018-02-27 12:44:34 +01:00
Gwendal Roué 619aeb4355 Merge pull request #312 from groue/GRDB3-DropIteratorCursor
Drop IteratorCursor, use AnyCursor instead
2018-02-27 12:39:37 +01:00
Gwendal Roué e8d0af93fc Cursor changelog 2018-02-27 08:17:55 +01:00
Gwendal Roué 4faa9964bd Make AnyCursor final 2018-02-27 08:15:49 +01:00
Gwendal Roué 15a0ea79b0 Drop IteratorCursor, use AnyCursor instead 2018-02-27 08:11:48 +01:00
Gwendal Roué d0a281e14f Merge pull request #311 from groue/GRDB3-FetchRequest
Rename TypedRequest to FetchRequest, drop Request
2018-02-27 07:53:23 +01:00
Gwendal Roué 49e624e532 Update WhyAdoptGRDB.md for FetchRequest 2018-02-27 07:47:05 +01:00
Gwendal Roué 3bbcb8151d Update JoinSupportTests for FetchRequest 2018-02-26 22:34:46 +01:00
Gwendal Roué c7b9358bc7 Documentation polish 2018-02-26 22:29:58 +01:00
Gwendal Roué a552e7d25c Update README.md for FetchRequest 2018-02-26 22:18:35 +01:00
Gwendal Roué c108094aa5 FetchRequest changelog 2018-02-26 19:34:29 +01:00
Gwendal Roué 769c67e7d3 FetchRequest.adapted(_:) in not experimental 2018-02-26 19:34:16 +01:00
Gwendal Roué f605e049fd Rename TypedRequest to FetchRequest, drop Request 2018-02-26 13:12:33 +01:00
Gwendal Roué e44201e0e3 Apply advice from @sobri909 2018-02-25 09:43:00 +01:00
Gwendal Roué 028093199b Replace flatMap with compactMap in README.md 2018-02-25 09:26:18 +01:00
Gwendal Roué 6043b4288e SE-0184: backport UnsafeMutablePointer.deallocate() 2018-02-25 09:24:23 +01:00
Gwendal Roué 11ec16494d TODO Swift 4.1 2018-02-25 09:24:23 +01:00
Gwendal Roué b4922f60a2 SE-0185: let Swift 4.1 generate as much Equatable and Hashable conformance as possible 2018-02-25 09:24:23 +01:00
Gwendal Roué b0e126f29d SE-0187: deprecate Cursor.flatMap in favor of Cursor.compactMap 2018-02-25 09:24:23 +01:00
Gwendal Roué d8c411ad52 Swift 4.1 compatibility (SE-0184 , SE-0187) 2018-02-25 09:24:23 +01:00
Gwendal Roué 4f8f0e0bf3 Fix Xcode9.3 warnings 2018-02-25 09:23:05 +01:00
Gwendal Roué dee6bf79d1 TODO 2018-02-25 08:41:34 +01:00
Gwendal Roué baeba0dea3 v2.9.0 2018-02-25 07:40:14 +01:00
Gwendal Roué 3dc31ad638 Typo 2018-02-25 00:00:25 +01:00
Gwendal Roué 4201e2a611 README 2018-02-24 21:24:18 +01:00
Gwendal Roué d9f6fa7de6 CHANGELOG 2018-02-24 21:12:53 +01:00
Gwendal Roué d0146762bc Differences between Database Queues and Pools 2018-02-24 21:06:07 +01:00
Gwendal Roué 7e8f2e2fbc Differences between Database Queues and Pools 2018-02-24 21:05:23 +01:00
Gwendal Roué 497f4b65ef Differences between Database Queues and Pools 2018-02-24 21:03:08 +01:00
Gwendal Roué 03c44778ba Differences between Database Queues and Pools 2018-02-24 20:57:27 +01:00
Gwendal Roué 0cc744ae16 Differences between Database Queues and Pools 2018-02-24 20:54:12 +01:00
Gwendal Roué fae3862547 Typo 2018-02-24 20:08:07 +01:00
Gwendal Roué 70a222f3c9 Typo 2018-02-24 20:07:21 +01:00
Gwendal Roué 5676adca99 TODO: Decode NSDecimalNumber from text database values
(Idea from @robertmryan at https://github.com/ccgus/fmdb/pull/647#issuecomment-368083101)
2018-02-24 18:18:41 +01:00
Gwendal Roué 3a77ca68c4 TODO 2018-02-24 17:58:02 +01:00
Gwendal Roué 248437d1d6 DatabaseSnapshot documentation 2018-02-24 17:55:34 +01:00
Gwendal Roué afcde4609e CHANGELOG 2018-02-24 17:49:39 +01:00
Gwendal Roué 2e98974373 Cursor doc 2018-02-24 17:46:01 +01:00
Gwendal Roué 086a33fd62 Cursor doc 2018-02-24 17:44:33 +01:00
Gwendal Roué 33359dd435 Markdown typo 2018-02-24 17:42:52 +01:00
Gwendal Roué 574d71b50c Cursor level 2018-02-24 17:41:29 +01:00
Gwendal Roué c806b706d4 Focus on Cursor specificities 2018-02-24 17:40:16 +01:00
Gwendal Roué c3b8c0f7e9 Explain why cursors are not sequences (addresses #303) 2018-02-24 17:37:00 +01:00
Gwendal Roué a1cd622892 Focus on Cursor specificities 2018-02-24 17:30:31 +01:00
Gwendal Roué dea3ee0b84 Focus on Cursor specificities 2018-02-24 17:29:29 +01:00
Gwendal Roué 5c64348ea8 Focus on Cursor specificities 2018-02-24 17:25:13 +01:00
Gwendal Roué 262ac2c476 Intra-doc links 2018-02-24 17:17:34 +01:00
Gwendal Roué dbfbe30749 DatabaseSnapshot RAII 2018-02-24 17:15:53 +01:00
Gwendal Roué 70437bd4cb Documentation typos 2018-02-24 17:14:30 +01:00
Gwendal Roué 2d30b5ea1c Documentation typos 2018-02-24 17:13:27 +01:00
Gwendal Roué 5414111bed Update changes tracking documentation, and changelog 2018-02-24 17:06:35 +01:00
Gwendal Roué 9168bac16e Deprecate RecordBox. Introduce changes API on MutablePersistable. Rename Record changes tracking methods. 2018-02-24 16:19:21 +01:00
Gwendal Roué 8760d36f6c Snapshot documentation 2018-02-24 07:59:44 +01:00
Gwendal Roué 141b870bc0 Typo 2018-02-24 07:55:15 +01:00
Gwendal Roué 5e4406e78c Improves documentation (addresses #306) 2018-02-24 07:54:42 +01:00
Gwendal Roué c5426bfcf7 CHANGELOG 2018-02-24 07:44:35 +01:00
Gwendal Roué 76561a567f Introduce DatabaseSnapshot 2018-02-24 07:37:26 +01:00
Gwendal Roué 8288f0c751 Add a real-life test for allowsUnsafeTransactions 2018-02-23 19:11:38 +01:00
Gwendal Roué 7dc008db8b Expose Database.beginTransaction(), commit(), rollback(). New Configuration.allowsUnsafeTransactions flag. New fatal error when a database access block ends with a transaction left opened. 2018-02-23 14:14:05 +01:00
Gwendal Roué 86bb4a27a4 CHANGELOG 2018-02-23 13:23:44 +01:00
Gwendal Roué f2d9f50930 CHANGELOG 2018-02-23 13:10:40 +01:00
Gwendal Roué b9af7e6a25 Update ColumnInfo.primaryKeyIndex documentation 2018-02-23 12:55:27 +01:00
Gwendal Roué 00825748ff Fix ColumnInfo test (it is different with SQLite < 3.7.16) 2018-02-23 12:53:41 +01:00
Gwendal Roué fe0edde4a9 TODO 2018-02-23 12:41:19 +01:00
Gwendal Roué edfea91920 TODO 2018-02-23 09:03:58 +01:00
Gwendal Roué 319e6bcdc8 Typo 2018-02-23 08:55:40 +01:00
Gwendal Roué 274f73e040 Cleanup 2018-02-23 08:55:03 +01:00
Gwendal Roué fab37838b2 Cleanup 2018-02-23 08:49:50 +01:00
Gwendal Roué a5a3610bf6 Cleanup 2018-02-23 08:49:27 +01:00
Gwendal Roué 07e600163c Splitting rows: documentation WIP 2018-02-23 08:35:32 +01:00
Gwendal Roué 14a5dc5489 Cleanup 2018-02-23 08:34:34 +01:00
Gwendal Roué 46c2b94425 Cleanup 2018-02-23 08:32:50 +01:00
Gwendal Roué 9a1dc7f292 Cleanup 2018-02-23 08:32:17 +01:00
Gwendal Roué c68fc37959 Cleanup 2018-02-23 08:17:15 +01:00
Gwendal Roué aa1f555e05 Drop init(leftJoinedRow:), and expose Row subscripts that return records 2018-02-23 08:08:00 +01:00
Gwendal Roué 699e64c610 Splitting rows: documentation WIP 2018-02-22 23:31:58 +01:00
Gwendal Roué e8c1392314 TODO 2018-02-22 23:30:48 +01:00
Gwendal Roué c1ae47d188 Splitting rows: documentation WIP 2018-02-22 23:26:37 +01:00
Gwendal Roué 13a9f1113a Splitting rows: documentation WIP 2018-02-22 23:07:19 +01:00
Gwendal Roué c4ad86863f Splitting rows: documentation WIP 2018-02-22 23:03:39 +01:00
Gwendal Roué 8300a618f8 Splitting rows: documentation WIP 2018-02-22 22:58:56 +01:00
Gwendal Roué 52f0038262 Splitting rows: documentation WIP 2018-02-22 22:58:05 +01:00
Gwendal Roué 31710ce91c Splitting rows: documentation WIP 2018-02-22 22:55:24 +01:00
Gwendal Roué a9c75652e1 Splitting rows: documentation WIP 2018-02-22 22:54:21 +01:00
Gwendal Roué 3e13e5be57 Splitting rows: documentation WIP 2018-02-22 22:48:52 +01:00
Gwendal Roué c27979a210 Splitting rows: documentation WIP 2018-02-22 22:37:42 +01:00
Gwendal Roué 37d7c84bc3 Splitting rows: documentation WIP 2018-02-22 22:30:13 +01:00
Gwendal Roué 62f5c8fc2f Splitting rows: documentation WIP 2018-02-22 22:18:12 +01:00
Gwendal Roué 289c449dff Splitting rows: documentation WIP 2018-02-22 22:13:29 +01:00
Gwendal Roué e7b7b603d2 Splitting rows: documentation WIP 2018-02-22 22:08:23 +01:00
Gwendal Roué e7e342600b Splitting rows: documentation WIP 2018-02-22 21:03:17 +01:00
Gwendal Roué db6e3b8371 Splitting rows: documentation WIP 2018-02-22 20:33:46 +01:00
Gwendal Roué 79ed15c38c Deprecate Database.columnCount(in:) in favor of Database.columns(in:). Update doc and changelog 2018-02-22 14:00:19 +01:00
Gwendal Roué 6f175dcafb Add ColumnInfoTests to GRDBCustom/GRDBCipher tests 2018-02-22 13:52:52 +01:00
Gwendal Roué ca70a10bd4 TODO 2018-02-22 13:37:49 +01:00
Gwendal Roué ae3319e9f9 Make ColumnInfo public (asked by @freak4pc) 2018-02-22 13:20:41 +01:00
Gwendal Roué 5112cb24f5 Expose EmptyRowAdapter, and ScopeAdapter(base:scopes:) 2018-02-22 12:38:03 +01:00
Gwendal Roué c6bbccc02e Have AdaptedRow go straight to SQLite when possible (avoid DatabaseValue initializer) 2018-02-22 12:23:19 +01:00
Gwendal Roué 93ec4d2515 Remove Row.hasNull(named:String) and Row.hasNull(Column) 2018-02-22 12:00:06 +01:00
Gwendal Roué 955dc6094b TODO 2018-02-22 09:24:30 +01:00
Gwendal Roué bd694cbc53 Cleanup 2018-02-22 08:50:35 +01:00
Gwendal Roué c115a035ec Row.hasNull(atIndex:) goes straight to sqlite3_column_type() when possible 2018-02-22 08:39:14 +01:00
Gwendal Roué 288144f347 splittingRowAdapters(columnCounts:), ScopeAdapter(nestedScopes:), RowConvertible?(leftJoinedRow:), TableMapping.numberOfSelectedColumns(_:), support for nested codable records 2018-02-21 23:15:13 +01:00
Gwendal Roué 3bdfdaa40a TableMapping.selectionSQL(_:) 2018-02-21 13:51:37 +01:00
Gwendal Roué 22949813af Row.hasNull(atIndex:), Row.hasNull(named:), Row.hasNull(_:), Row.hasNonNullValue 2018-02-20 14:43:06 +01:00
Gwendal Roué 5c98b01484 Update Record.updateChanges(_:) documentation 2018-02-20 13:20:50 +01:00
Gwendal Roué ea5e1cd0db CHANGELOG 2018-02-20 13:18:38 +01:00
Gwendal Roué b5d9955442 Tests: setup Database.logError only once (and avoid SQLite misuse) 2018-02-20 13:16:11 +01:00
Gwendal Roué feb5cb35b4 Record.updateChanges now returns whether the record had changes 2018-02-20 13:06:58 +01:00
Gwendal Roué 654c7083eb TODO 2018-02-17 17:44:03 +01:00
Gwendal Roué a0457928b3 TODO 2018-02-17 17:40:25 +01:00
Gwendal Roué 4df535a3a9 TODO 2018-02-17 17:32:15 +01:00
Gwendal Roué 0b251ec4e0 TODO 2018-01-31 19:54:37 +01:00
Gwendal Roué 7704a9ac41 v2.8.0 2018-01-29 08:12:29 +01:00
Gwendal Roué 59031893ff Merge pull request #297 from groue/MoreCursor
More sequence-like cursor methods
2018-01-29 07:19:58 +01:00
Gwendal Roué fcfa044320 Parts of Cursor implementation are derived from Swift.org 2018-01-28 18:56:40 +01:00
Gwendal Roué f95658e7ce Remove convenience cursor types from reference documentation
Those types bloat the documentation for no real value: DropFirstCursor, DropWhileCursor, EnumeratedCursor, FilterCursor, FlattenCursor, MapCursor, PrefixCursor, PrefixWhileCursor
2018-01-28 17:13:53 +01:00
Gwendal Roué 2c16fcaa99 Cursor cleanup 2018-01-28 17:13:52 +01:00
Gwendal Roué 4e638016e1 Cursor changelog 2018-01-28 17:13:52 +01:00
Gwendal Roué 5d811c0e68 Documentation for Cursor convenience methods 2018-01-28 17:13:52 +01:00
Gwendal Roué 9f1f51637a Tests for Cursor.joined(separator:String) 2018-01-28 17:13:52 +01:00
Gwendal Roué 7c16ffcdf8 Cursor.joined(separator:String) 2018-01-28 17:13:51 +01:00
Gwendal Roué 7ca582719b Tests for Cursor.reduce(into:_:) 2018-01-28 17:13:51 +01:00
Gwendal Roué e4b83baa53 Cursor.reduce(into:_:) 2018-01-28 17:13:51 +01:00
Gwendal Roué ac6b2933a8 Tests for Cursor.max(by:), max(), min(by:), min() 2018-01-28 17:13:50 +01:00
Gwendal Roué 92758fa51d Cursor.max(by:), max(), min(by:), min() 2018-01-28 17:13:50 +01:00
Gwendal Roué acd06a4f5a Tests for Cursor.dropLast() 2018-01-28 17:13:50 +01:00
Gwendal Roué eec6b17398 Cursor.dropLast() 2018-01-28 17:13:50 +01:00
Gwendal Roué 15fbf02647 Tests for Cursor.dropFirst() 2018-01-28 17:13:49 +01:00
Gwendal Roué c296be5057 Cursor.dropFirst() 2018-01-28 17:13:49 +01:00
Gwendal Roué 129e178ee0 Tests for Cursor.dropFirst(_:) 2018-01-28 17:13:49 +01:00
Gwendal Roué 1e5caa62a8 Tests for Cursor.prefix(while:) 2018-01-28 17:13:49 +01:00
Gwendal Roué 420ed0764b Tests for Cursor.drop(while:) 2018-01-28 17:13:49 +01:00
Gwendal Roué ce6bbb2885 Tests for Cursor.prefix(_:) 2018-01-28 17:13:48 +01:00
Gwendal Roué 87d6c5dd29 Cursor.prefix(_:) 2018-01-28 17:13:48 +01:00
Gwendal Roué dccd456497 Tests for Cursor.dropLast(_:) 2018-01-28 17:13:48 +01:00
Gwendal Roué 520bdd64e6 Tests for Cursor.dropFirst(_:) 2018-01-28 17:13:47 +01:00
Gwendal Roué 72608fd016 Cursor.dropLast(_:) 2018-01-28 17:13:47 +01:00
Gwendal Roué 69b51ffbd5 Tests for Cursor.dropFirst(_:) 2018-01-28 17:13:47 +01:00
Gwendal Roué c9044ea07b Cursor.dropFirst(_:) 2018-01-28 17:13:47 +01:00
Gwendal Roué 362c40326f Tests for Cursor.suffix(_:) 2018-01-28 17:13:47 +01:00
Gwendal Roué 28d0793688 Cursor.suffix(_:) 2018-01-28 17:13:46 +01:00
Gwendal Roué abdc2000c4 Tests for Cursor.prefix(while:) 2018-01-28 17:13:46 +01:00
Gwendal Roué 3d845b1e9f Cursor.prefix(while:) 2018-01-28 17:13:46 +01:00
Gwendal Roué bae8c97df4 Tests for Cursor.drop(while:) 2018-01-28 17:13:46 +01:00
Gwendal Roué 452c1d4b92 Cursor.drop(while:) 2018-01-28 17:13:46 +01:00
Gwendal Roué 9990e6e2a6 Less TODO 2018-01-28 17:13:16 +01:00
Gwendal Roué 8d0dc3eb78 Merge pull request #293 from groue/SQLite3.22.0
Upgrade SQLite version to 3.22.0
2018-01-27 09:33:54 +01:00
Gwendal Roué 0a2a3c75c1 Fix typo 2018-01-26 08:47:27 +01:00
Gwendal Roué 830e6acb4f Documentation and changelog 2018-01-26 08:44:18 +01:00
Gwendal Roué 1da85dff58 FTS5Pattern(matchingPrefixPhrase:) 2018-01-26 08:38:11 +01:00
Gwendal Roué dd40e3be5b Upgrade custom SQLite version in documentation 2018-01-26 08:00:50 +01:00
Gwendal Roué 224d6488a9 Upgrade swiftlyfalling/SQLiteLib to v3.22.0 2018-01-26 07:54:08 +01:00
Gwendal Roué cac31d3294 TODO: apply @hartbit's suggestion 2018-01-24 18:56:53 +01:00
Gwendal Roué 951d5fa58d TODO SQLite 3.22.0 2018-01-23 08:10:26 +01:00
Gwendal Roué 7a4f0778df Remove references to discarded GRDB Extension Guide 2018-01-21 17:31:45 +01:00
Gwendal Roué 5aff4d29fc CHANGELOG 2018-01-21 17:29:27 +01:00
Gwendal Roué 402b7001ee v2.7.0 2018-01-21 17:07:39 +01:00
Gwendal Roué f7d0979fb1 Remove ExtendingGRDB guide 2018-01-21 17:05:38 +01:00
Gwendal Roué 2289ed9d95 Cleanup Jazzy documentation from most redundant definitions and experimental APIs 2018-01-21 16:57:43 +01:00
Gwendal Roué dfcb44016f Enhance CHANGELOG 2018-01-21 15:19:55 +01:00
Gwendal Roué 37a434a615 Merge pull request #289 from groue/RecordBox
Bring changes tracking to any record type
2018-01-21 13:16:35 +01:00
Gwendal Roué 0ddcf1e401 RecordBox documentation 2018-01-21 13:14:14 +01:00
Gwendal Roué 0aa673f24e RecordBox consequence: more TODO 2018-01-21 12:05:41 +01:00
Gwendal Roué b3a24daa2f Documentation tweaks 2018-01-21 07:49:13 +01:00
Gwendal Roué 8c6954cd75 RecordBox documentation 2018-01-21 07:35:52 +01:00
Gwendal Roué 283f08de07 RecordBox changelog 2018-01-20 20:26:37 +01:00
Gwendal Roué d96543ddeb RecordBox documentation 2018-01-20 20:26:37 +01:00
Gwendal Roué 4b320f3cb5 RecordBox documentation 2018-01-20 20:26:37 +01:00
Gwendal Roué 69a6d3e3f3 RecordBox documentation 2018-01-20 20:26:36 +01:00
Gwendal Roué 93d4587732 RecordBox 2018-01-20 20:26:36 +01:00
Gwendal Roué 7481b9788a Run truncate optimization tests with and without transaction observer
This topic is sooo touchy...
2018-01-20 20:26:10 +01:00
Gwendal Roué acf3e0b397 TODO 2018-01-20 19:54:19 +01:00
Gwendal Roué 88ae0fa059 TODO 2018-01-20 17:59:54 +01:00
Gwendal Roué a1e63d9028 Fix management of current transaction observation broker (and discover a new SQLite oddity) 2018-01-20 16:11:05 +01:00
Gwendal Roué 2a1ad8d31c TODO 2018-01-20 09:09:32 +01:00
Gwendal Roué ba7cd2160f TODO 2018-01-20 06:09:44 +01:00
Gwendal Roué 8e50383371 v2.6.1 2018-01-19 16:24:09 +01:00
Gwendal Roué ffc5352840 Fix transaction observer crash 2018-01-19 16:17:38 +01:00
Gwendal Roué 53e849cbec v2.6.0 2018-01-18 13:05:07 +01:00
Gwendal Roué b71d57d7ec Merge pull request #288 from groue/TransactionObserverInvalidation
Enhance Database Observation
2018-01-18 13:04:41 +01:00
Gwendal Roué 4fe2b2542f Cleanup 2018-01-18 12:54:02 +01:00
Gwendal Roué 8c7895d8ab Have Makefile accept both Xcode9.0 and Xcode9.0.1 2018-01-18 12:47:29 +01:00
Gwendal Roué ad15f4dc59 Fix .travis.yml for Xcode9 2018-01-17 13:51:19 +01:00
Gwendal Roué c4ef161a83 Rename Statement.region and Request.region to fetchedRegion 2018-01-17 06:54:10 +01:00
Gwendal Roué bb48025947 Derived requests ought to preserve database region: fix failing tests 2018-01-16 20:39:19 +01:00
Gwendal Roué 389a7f28c4 Derived requests ought to preserve database region: failing tests 2018-01-16 20:39:13 +01:00
Gwendal Roué 714cc1c734 DatabaseRegion() is public 2018-01-16 19:57:30 +01:00
Gwendal Roué 8d0da7f870 DatabaseRegion documentation 2018-01-16 18:47:59 +01:00
Gwendal Roué e42e74103d DatabaseRegion documentation 2018-01-16 18:46:55 +01:00
Gwendal Roué 4bcdb91895 AnyRequest and all derived requests preserve database region, and counting method 2018-01-16 14:11:05 +01:00
Gwendal Roué 938977bbca Cleanup DatabaseRegion: no more public intersection, no more public way to specify rowids 2018-01-16 13:58:55 +01:00
Gwendal Roué 581c1c46e2 More TODO 2018-01-16 11:28:48 +01:00
Gwendal Roué 768b2ab620 More TODO 2018-01-16 09:30:12 +01:00
Gwendal Roué 4eff5ab357 More TODO 2018-01-16 09:06:53 +01:00
Gwendal Roué 888892b92f Cleanup 2018-01-16 09:04:06 +01:00
Gwendal Roué ba4f146c9c Cleanup 2018-01-16 08:55:48 +01:00
Gwendal Roué 8359dd2ae2 Cleanup 2018-01-16 08:54:12 +01:00
Gwendal Roué 0be80db8f9 Cleanup 2018-01-16 08:51:42 +01:00
Gwendal Roué 72de142519 Cleanup 2018-01-16 08:50:49 +01:00
Gwendal Roué 0a7468f56d Cleanup 2018-01-16 08:34:54 +01:00
Gwendal Roué 33b5c6c616 Rename DatabaseSelectionInfo to DatabaseRegion 2018-01-16 08:23:08 +01:00
Gwendal Roué 4003d7600d DatabaseSelectionInfo documentation WIP 2018-01-15 23:41:49 +01:00
Gwendal Roué a7122ba8bb Unit tests for DatabaseSelectionInfo.isModified methods 2018-01-15 23:09:52 +01:00
Gwendal Roué dc8c85d3db Odd failing tests for DatabaseSelectionInfo and the rowid column. Consequences not cleared out yet. 2018-01-15 22:44:09 +01:00
Gwendal Roué fc1b4a6f35 Complete refactoring of SelectStatement.SelectionInfo into DatabaseSelectionInfo 2018-01-15 22:28:43 +01:00
Gwendal Roué af42623654 Fix SPM tests 2018-01-15 07:22:01 +01:00
Gwendal Roué ab1a672336 Disable test that fails on iOS 8.1 (SQLite 3.7.13) 2018-01-14 23:31:19 +01:00
Gwendal Roué 4501d7dcde TransactionObserver: provide default implementation for rarely used and stabilized databaseWillChange() and databaseWillCommit() methods 2018-01-14 22:58:12 +01:00
Gwendal Roué 5d463d6bff Goal achieved! FetchedRecordsController uses ignoreDatabaseChangesUntilNextTransaction, and checks changed rowIds in order to avoid useless fetch requests 2018-01-14 22:41:27 +01:00
Gwendal Roué 9c8a9fbe32 SelectionInfo.rowIds contains the rowIds fetched by a request 2018-01-14 22:05:18 +01:00
Gwendal Roué 1a89b2eae5 Test that sqlite authorizer uses "ROWID" as the name of the rowid column 2018-01-14 20:15:55 +01:00
Gwendal Roué fd65e72bbb CHANGELOG 2018-01-14 19:41:05 +01:00
Gwendal Roué 33e8d0875d Remove update hook when no observer is active. Allow truncate optimization when deletions are not observed. 2018-01-14 19:34:11 +01:00
Gwendal Roué 19e75576a8 Documentation for TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() 2018-01-14 17:36:51 +01:00
Gwendal Roué 980860b2e9 Documentation for TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() 2018-01-14 17:35:17 +01:00
Gwendal Roué eee3e36238 Test TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() 2018-01-14 17:08:53 +01:00
Gwendal Roué eaadd37e87 TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() is public 2018-01-14 17:08:42 +01:00
Gwendal Roué a1e508b1df TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() 2018-01-14 16:45:36 +01:00
Gwendal Roué 2c8f9dffdd TODO GRDB3 2018-01-12 10:06:26 +01:00
Gwendal Roué 92fd3bf8ae TODO: TransactionObserver.stopObservingUntilNextTransaction() 2018-01-12 09:48:57 +01:00
Gwendal Roué c940675bf3 Fix typo 2018-01-12 09:12:35 +01:00
Gwendal Roué 2a147d5029 Travis: test Xcode 9.2 and Xcode 9.0 2018-01-12 08:19:02 +01:00
Gwendal Roué 0d236ae32c Row adopts RandomAccessCollection 2018-01-12 08:18:50 +01:00
Gwendal Roué cf4654108e More doc for filter(key:) and filter(keys:) 2018-01-12 07:19:26 +01:00
Gwendal Roué 7e9eed9374 v2.5.0 2018-01-11 21:16:54 +01:00
Gwendal Roué 383581938a Cleanup 2018-01-11 20:14:01 +01:00
Gwendal Roué df50da9024 Cleanup 2018-01-11 20:12:02 +01:00
Gwendal Roué d3a65303a1 Cleanup 2018-01-11 20:06:59 +01:00
Gwendal Roué 9a2bf923d2 Update CHANGELOG and README for new key-filtering requests 2018-01-11 20:04:49 +01:00
Gwendal Roué 9b27c0c651 WIP TableMapping.filter(key: [:]) and TableMapping.filter(keys: [[:], ]) 2018-01-11 19:34:28 +01:00
Gwendal Roué 2af85e7347 WIP TableMapping.filter(key:1) and TableMapping.filter(keys: [1, 2, 3]) 2018-01-11 18:09:01 +01:00
Gwendal Roué 071f0f4443 Cleanup 2018-01-10 08:50:45 +01:00
Gwendal Roué 903e8c96aa '^foo' is no longer an invalid FTS5 pattern in upcoming SQLite 3.22.0 2018-01-10 07:40:02 +01:00
Gwendal Roué 79a5fb9c15 Cleanup 2018-01-08 08:44:42 +01:00
Gwendal Roué 46ef4b27bb Fix failing test 2018-01-07 15:29:24 +01:00
Gwendal Roué 1838797d38 CHANGELOG 2018-01-07 14:25:36 +01:00
Gwendal Roué c7d500b8ba Optimize database event notifications for simple statements without side effect 2018-01-07 14:25:29 +01:00
Gwendal Roué 95a09cb644 Only notify observed events to transaction observers 2018-01-07 13:33:35 +01:00
Gwendal Roué c6ab92e60a v2.4.2 2018-01-06 14:35:05 +01:00
Gwendal Roué c0d5f3019b generatePerformanceReport reads versions of tested libraries from info.plist files 2018-01-06 13:37:30 +01:00
Gwendal Roué b09d5c3833 Fix FMDB performance tests 2018-01-06 12:47:01 +01:00
Gwendal Roué 3eff1b48b1 Update copyright year 2018-01-06 12:33:32 +01:00
Gwendal Roué a12fffc4e7 Update documentation about readFromCurrentState 2018-01-06 10:04:41 +01:00
Gwendal Roué 94715130fc DatabaseWriter.readFromCurrentState(_:) now fails with a fatal error if a transaction is currently opened 2018-01-06 09:19:26 +01:00
Gwendal Roué 313188ca0e More TODO 2018-01-05 19:40:55 +01:00
Gwendal Roué 5a68b008c6 CHANGELOG 2018-01-02 13:34:23 +01:00
Gwendal Roué 6fe9098c76 Statement compilation cleanup 2018-01-02 13:10:11 +01:00
Gwendal Roué 631a914acd Fix failing test for schema cache shared between DatabasePool reader and writer (stop sharing cache) 2018-01-02 13:08:41 +01:00
Gwendal Roué d1f24c9722 More TODO 2017-12-28 17:48:15 +01:00
Gwendal Roué 7b76c9319a Failing test for schema cache shared between DatabasePool reader and writer 2017-12-28 14:16:36 +01:00
Gwendal Roué 63083c5d1e Less TODO 2017-12-28 13:56:54 +01:00
Gwendal Roué c51a3cd624 Statement compilation cleanup 2017-12-17 13:57:35 +01:00
Gwendal Roué 1fadb7485a Less TODO 2017-12-17 13:14:15 +01:00
Gwendal Roué 58e05d13d1 v2.4.1 2017-12-16 15:09:59 +01:00
Gwendal Roué d8c9692d4d Fix typo 2017-12-16 14:40:58 +01:00
Gwendal Roué f83ffd3a25 Remove unused file 2017-12-16 14:35:09 +01:00
Gwendal Roué d12ff2a92b Scripts that generate performance comparison report 2017-12-16 14:35:02 +01:00
Gwendal Roué 8709d6f9a9 FMDB 2.7.4 2017-12-16 14:25:24 +01:00
Gwendal Roué e2806c55ff Upgrade Makefile test_performance target for Xcode 9.2 and Swift 4.0.3 2017-12-16 13:44:19 +01:00
Gwendal Roué 08d6c843d6 Upgrade performance comparison tests for Xcode 9.2 and Swift 4.0.3 2017-12-16 13:42:53 +01:00
Gwendal Roué 0da3726a89 Realm 3.0.2 2017-12-16 13:36:13 +01:00
Gwendal Roué 36676bcad3 SQLite.swift 0.11.4 2017-12-16 13:33:36 +01:00
Gwendal Roué 1509e1e9a8 Clean up projects & workspace 2017-12-16 13:29:05 +01:00
Gwendal Roué 4c71dd9ebe Remove compiler warning 2017-12-16 13:14:07 +01:00
Gwendal Roué ef8d0d6334 TODO.md 2017-12-15 18:49:36 +01:00
Gwendal Roué 7477b7a173 CHANGELOG.md 2017-12-13 08:24:14 +01:00
Gwendal Roué 246f36821b Merge pull request #284 from groue/Issue283
Don't call sqlite3_config() unless explicitly required to do so
2017-12-13 08:10:57 +01:00
Gwendal Roué d567ee60bf Remove compiler warning 2017-12-08 10:51:31 +01:00
Gwendal Roué 3a157d2808 Test for global SQLite error log requires global variables 2017-12-08 10:51:20 +01:00
Gwendal Roué 7d0c2f9ef8 Fix tests for Database.logError 2017-12-08 10:03:27 +01:00
Gwendal Roué f356f8734a Update Database.logError documentation, and make it clear that it has to be called very very early. 2017-12-07 13:35:19 +01:00
Gwendal Roué 5b7f4a7ff5 Call sqlite3_config(SQLITE_CONFIG_LOG, ...) if and only if Database.logError is set. 2017-12-07 13:14:49 +01:00
Gwendal Roué e10efca17a Fix typo 2017-12-03 16:27:59 +01:00
388 changed files with 55453 additions and 12115 deletions

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
<!--
ℹ We use Github issues for bug reports, feature requests, general support, and questions about the library.
Please fill out this template when filing an issue.
-->
### What did you do?
<!-- Please replace this with what you did. -->
### What did you expect to happen?
<!-- Please replace this with what you expected to happen. -->
### What happened instead?
<!-- Please replace this with of what happened instead. -->
### Environment
**GRDB flavor(s):** (GRDB, GRDBCipher, GRDBCustom?)
**GRDB version:**
**Installation method:** (CocoaPods, SPM, manual?)
**Xcode version:**
**Swift version:**
**Platform(s) running GRDB:** (iOS, macOS, watchOS?)
**macOS version running Xcode:**
### Demo Project
<!-- Please link to or upload a project we can download that reproduces the issue. -->
+13
View File
@@ -0,0 +1,13 @@
<!-- Please describe your pull request here. -->
### Pull Request Checklist
<!--
Please verify that your pull request checks those boxes:
-->
- [ ] 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.
- [ ] 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
+1 -1
View File
@@ -1 +1 @@
4.0
4.1
+143 -60
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,143 +15,226 @@ jobs:
###########################################
## Test GRDB
# Test GRDBOSX (Xcode 9.1)
# Test GRDBOSX (Xcode 10)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode10
env:
- TID=GRDBOSX (Xcode 9.1, macOS)
script: make test_framework_GRDBOSX
- TID=GRDBOSX (Xcode 10, Swift 4.2, macOS)
script: make test_framework_GRDBOSX_maxSwift
# Test GRDBWatchOS (Xcode 9.1)
# Test GRDBOSX (Xcode 10)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode10
env:
- TID=GRDBWatchOS (Xcode 9.1, 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 9.1, iOS <MAXIMUM VERSION>)
# Test GRDBiOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode10
env:
- TID=GRDBiOS (Xcode 9.1, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget
- TID=GRDBiOS (Xcode 10, Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
# Test GRDBiOS (Xcode 9.1, iOS <MINIMUM VERSION>))
# Test GRDBiOS (Xcode 9.4, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.4
env:
- TID=GRDBiOS (Xcode 9.1, iOS <MIN>)
- TID=GRDBiOS (Xcode 9.4, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
# Test GRDBiOS (Xcode 9.3, iOS <MINIMUM VERSION>))
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.3
env:
- TID=GRDBiOS (Xcode 9.3, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
# Test GRDB [SPM] (Xcode 9.1, macOS)
# Test GRDB [SPM] (Xcode 10, macOS)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode10
env:
- TID=GRDB [SPM] (Xcode 9.1, macOS)
- TID=GRDB [SPM] (Xcode 10, macOS)
script: make test_SPM
###########################################
## Test GRDB (Custom SQLite)
# Test GRDBCustomSQLiteOSX (Xcode 9.1)
# Test GRDBCustomSQLiteOSX (Xcode 10)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode10
env:
- TID=GRDBCustomSQLiteOSX (Xcode 9.1, macOS)
- TID=GRDBCustomSQLiteOSX (Xcode 10, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
# Test GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MAXIMUM VERSION>)
# Test GRDBCustomSQLiteiOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode10
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MAX>)
- 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
osx_image: xcode9.4
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9.4, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
# Test GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MINIMUM VERSION>))
# Test GRDBCustomSQLiteiOS (Xcode 9.3, iOS <MINIMUM VERSION>))
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.3
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MIN>)
- TID=GRDBCustomSQLiteiOS (Xcode 9.3, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test GRDB (SQLCipher)
# Test GRDBCipherOSX (Xcode 9.1)
# Test GRDBCipherOSX (Xcode 10)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode10
env:
- TID=GRDBCipherOSX (Xcode 9.1, macOS)
- TID=GRDBCipherOSX (Xcode 10, macOS)
script: make test_framework_GRDBCipherOSX
# Test GRDBCipheriOS (Xcode 9.1, iOS <MAXIMUM VERSION>)
# Test GRDBCipheriOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode10
env:
- TID=GRDBCipheriOS (Xcode 9.1, iOS <MAX>)
- TID=GRDBCipheriOS (Xcode 10, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
# Test GRDBCipheriOS (Xcode 9.1, iOS <MINIMUM VERSION>))
# Test GRDBCipheriOS (Xcode 9.4, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.4
env:
- TID=GRDBCipheriOS (Xcode 9.1, iOS <MIN>)
- TID=GRDBCipheriOS (Xcode 9.4, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
# Test GRDBCipheriOS (Xcode 9.3, iOS <MINIMUM VERSION>))
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.3
env:
- TID=GRDBCipheriOS (Xcode 9.3, iOS <MIN>)
script: make test_framework_GRDBCipheriOS_minTarget
###########################################
## Test Installation Methods
# Manual Install
# Manual Install (Xcode 10)
- stage: Test Installation
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode10
env:
- TID=Manual Install
- TID=Manual Install (Xcode 10)
script: make test_install_manual
# Manual Install (GRDBCipher)
# Manual Install (GRDBCipher, Xcode 10)
- stage: Test Installation
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode10
env:
- TID=Manual Install (GRDBCipher)
- TID=Manual Install (GRDBCipher, Xcode 10)
script: make test_install_GRDBCipher
# Cocoapods Lint
# CocoaPods Lint (Xcode 10)
- stage: Test Installation
osx_image: xcode9.1
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
script: make test_CocoaPodsLint
- TID=CocoaPods Lint GRDB.swift (Xcode 10)
script: make test_CocoaPodsLint_GRDB
# SPM Install
# CocoaPods Lint (Xcode 10)
- stage: Test Installation
osx_image: xcode9.1
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
env:
- TID=SPM
- 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.1
# 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
+957 -7
View File
File diff suppressed because it is too large. Load diff
+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
@@ -21,11 +21,9 @@
56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */; };
56B036111E8D9EBE003B6DA4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */; };
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; };
56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Person.swift */; };
56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */; };
56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */; };
56B036241E8D9F4C003B6DA4 /* PersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */; };
56B036251E8D9F4C003B6DA4 /* SimplePersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */; };
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; };
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; };
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */; };
56B0365E1E8D9FB1003B6DA4 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; };
56B0365F1E8D9FB1003B6DA4 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
/* End PBXBuildFile section */
@@ -94,41 +92,6 @@
remoteGlobalIDString = 56553C181C3E906C00522B5C;
remoteInfo = GRDBOSXCrashTests;
};
56B036421E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 560FC54D1CB003810014AA8E;
remoteInfo = GRDBCipherOSX;
};
56B036441E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 560FC5B01CB00B880014AA8E;
remoteInfo = GRDBCipherOSXTests;
};
56B036461E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 5671566C1CB16729007DC145;
remoteInfo = GRDBCipherOSXEncryptedTests;
};
56B036481E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = F3BA805A1CFB2BB2003DC1BA;
remoteInfo = GRDBCustomSQLiteOSX;
};
56B0364A1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = F3BA809B1CFB2F6F003DC1BA;
remoteInfo = GRDBCustomSQLiteOSXTests;
};
56B0364C1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
@@ -143,41 +106,6 @@
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
remoteInfo = GRDBiOSTests;
};
56B036501E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56AFCA231CB1A8BB00F48B96;
remoteInfo = GRDBCipheriOS;
};
56B036521E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56AFCA7F1CB1AA9900F48B96;
remoteInfo = GRDBCipheriOSTests;
};
56B036541E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56AFCAD71CB1ABC800F48B96;
remoteInfo = GRDBCipheriOSEncryptedTests;
};
56B036561E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = F3BA7FFE1CFB25E4003DC1BA;
remoteInfo = GRDBCustomSQLiteiOS;
};
56B036581E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = F3BA80411CFB2AD7003DC1BA;
remoteInfo = GRDBCustomSQLiteiOSTests;
};
56B0365A1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
@@ -265,11 +193,9 @@
56B036101E8D9EBE003B6DA4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
56B036121E8D9EBE003B6DA4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
56B0361A1E8D9F38003B6DA4 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = "<group>"; };
56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DemoViewController.swift; sourceTree = "<group>"; };
56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = "<group>"; };
56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonsViewController.swift; sourceTree = "<group>"; };
56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimplePersonsViewController.swift; sourceTree = "<group>"; };
56B0361A1E8D9F38003B6DA4 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = "<group>"; };
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = "<group>"; };
56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../GRDB.xcodeproj; sourceTree = "<group>"; };
/* End PBXFileReference section */
@@ -340,8 +266,9 @@
children = (
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
56B0361A1E8D9F38003B6DA4 /* Person.swift */,
56B0361D1E8D9F3D003B6DA4 /* Controllers */,
56B0361A1E8D9F38003B6DA4 /* Player.swift */,
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */,
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */,
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */,
56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */,
@@ -350,17 +277,6 @@
path = GRDBDemoiOS;
sourceTree = "<group>";
};
56B0361D1E8D9F3D003B6DA4 /* Controllers */ = {
isa = PBXGroup;
children = (
56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */,
56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */,
56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */,
56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */,
);
name = Controllers;
sourceTree = "<group>";
};
56B036271E8D9F79003B6DA4 /* Products */ = {
isa = PBXGroup;
children = (
@@ -369,18 +285,8 @@
56B0363F1E8D9F79003B6DA4 /* GRDBOSXPerformanceTests.xctest */,
563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */,
56B036411E8D9F79003B6DA4 /* GRDBOSXCrashTests.xctest */,
56B036431E8D9F79003B6DA4 /* GRDBCipher.framework */,
56B036451E8D9F79003B6DA4 /* GRDBCipherOSXTests.xctest */,
56B036471E8D9F79003B6DA4 /* GRDBCipherOSXEncryptedTests.xctest */,
56B036491E8D9F79003B6DA4 /* GRDBCustomSQLite.framework */,
56B0364B1E8D9F79003B6DA4 /* GRDBCustomSQLiteOSXTests.xctest */,
56B0364D1E8D9F79003B6DA4 /* GRDB.framework */,
56B0364F1E8D9F79003B6DA4 /* GRDBiOSTests.xctest */,
56B036511E8D9F79003B6DA4 /* GRDBCipher.framework */,
56B036531E8D9F79003B6DA4 /* GRDBCipheriOSTests.xctest */,
56B036551E8D9F79003B6DA4 /* GRDBCipheriOSEncryptedTests.xctest */,
56B036571E8D9F79003B6DA4 /* GRDBCustomSQLite.framework */,
56B036591E8D9F79003B6DA4 /* GRDBCustomSQLiteiOSTests.xctest */,
56B0365B1E8D9F79003B6DA4 /* GRDB.framework */,
);
name = Products;
@@ -455,7 +361,7 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0830;
LastUpgradeCheck = 0900;
LastUpgradeCheck = 0930;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
568E5FBE1E926430002582E0 = {
@@ -537,41 +443,6 @@
remoteRef = 56B036401E8D9F79003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B036431E8D9F79003B6DA4 /* GRDBCipher.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDBCipher.framework;
remoteRef = 56B036421E8D9F79003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B036451E8D9F79003B6DA4 /* GRDBCipherOSXTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBCipherOSXTests.xctest;
remoteRef = 56B036441E8D9F79003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B036471E8D9F79003B6DA4 /* GRDBCipherOSXEncryptedTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBCipherOSXEncryptedTests.xctest;
remoteRef = 56B036461E8D9F79003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B036491E8D9F79003B6DA4 /* GRDBCustomSQLite.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDBCustomSQLite.framework;
remoteRef = 56B036481E8D9F79003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0364B1E8D9F79003B6DA4 /* GRDBCustomSQLiteOSXTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBCustomSQLiteOSXTests.xctest;
remoteRef = 56B0364A1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0364D1E8D9F79003B6DA4 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
@@ -586,41 +457,6 @@
remoteRef = 56B0364E1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B036511E8D9F79003B6DA4 /* GRDBCipher.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDBCipher.framework;
remoteRef = 56B036501E8D9F79003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B036531E8D9F79003B6DA4 /* GRDBCipheriOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBCipheriOSTests.xctest;
remoteRef = 56B036521E8D9F79003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B036551E8D9F79003B6DA4 /* GRDBCipheriOSEncryptedTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBCipheriOSEncryptedTests.xctest;
remoteRef = 56B036541E8D9F79003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B036571E8D9F79003B6DA4 /* GRDBCustomSQLite.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDBCustomSQLite.framework;
remoteRef = 56B036561E8D9F79003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B036591E8D9F79003B6DA4 /* GRDBCustomSQLiteiOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBCustomSQLiteiOSTests.xctest;
remoteRef = 56B036581E8D9F79003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0365B1E8D9F79003B6DA4 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
@@ -674,13 +510,11 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */,
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */,
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */,
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */,
56B036241E8D9F4C003B6DA4 /* PersonsViewController.swift in Sources */,
56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */,
56B036251E8D9F4C003B6DA4 /* SimplePersonsViewController.swift in Sources */,
56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */,
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */,
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -751,6 +585,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_COMPLICATION_NAME = Complication;
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
@@ -767,6 +602,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_COMPLICATION_NAME = Complication;
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
@@ -784,6 +620,7 @@
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
@@ -801,6 +638,7 @@
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
@@ -827,6 +665,7 @@
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
@@ -834,6 +673,7 @@
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
@@ -865,7 +705,7 @@
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 4.0;
SWIFT_VERSION = 4.2;
};
name = Debug;
};
@@ -883,6 +723,7 @@
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
@@ -890,6 +731,7 @@
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
@@ -913,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;
@@ -923,6 +765,7 @@
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
@@ -936,6 +779,7 @@
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
@@ -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>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -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,20 +19,18 @@ 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()
migrator.registerMigration("createPersons") { db in
migrator.registerMigration("createPlayer") { db in
// Create a table
// See https://github.com/groue/GRDB.swift#create-tables
try db.create(table: "persons") { t in
// An integer primary key auto-generates unique IDs
t.column("id", .integer).primaryKey()
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
// Sort person names in a localized case insensitive fashion by default
// See https://github.com/groue/GRDB.swift/#unicode
// Sort player names in a localized case insensitive fashion by default
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
t.column("score", .integer).notNull()
@@ -41,12 +38,13 @@ struct AppDatabase {
}
migrator.registerMigration("fixtures") { db in
// Populate the persons table with random data
// Populate the players table with random data
for _ in 0..<8 {
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
}
// // Migrations for future application versions will be inserted here:
// migrator.registerMigration(...) { db in
// ...
@@ -55,3 +53,4 @@ struct AppDatabase {
return migrator
}
}
@@ -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
}
@@ -18,9 +18,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path)
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
// See https://github.com/groue/GRDB.swift/blob/master/README.md#memory-management
dbQueue.setupMemoryManagement(in: application)
}
}
@@ -1,15 +1,5 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "29x29",
@@ -42,16 +32,6 @@
"filename" : "Icon-60@3x.png",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "29x29",
@@ -1,70 +1,18 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11129.15" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
<?xml version="1.0" encoding="UTF-8"?>
<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="11103.10"/>
<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>
<!--Hall Of Fame-->
<scene sceneID="8jG-C9-QsI">
<objects>
<tableViewController id="cyv-nk-Plb" customClass="SimplePersonsViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="oON-zg-8kO">
<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"/>
<prototypes>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Person" textLabel="XIE-DF-pSO" detailTextLabel="vyz-CH-eMb" style="IBUITableViewCellStyleValue1" id="V5t-oJ-KD9">
<frame key="frameInset" minY="92" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="V5t-oJ-KD9" id="Coo-th-ywF">
<frame key="frameInset" width="342" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="XIE-DF-pSO">
<frame key="frameInset" minX="15" minY="12" width="31.5" height="19.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="16"/>
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="vyz-CH-eMb">
<frame key="frameInset" minX="298.5" minY="12" width="41.5" height="19.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="16"/>
<color key="textColor" red="0.55686274509803924" green="0.55686274509803924" blue="0.57647058823529407" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<nil key="highlightedColor"/>
</label>
</subviews>
</tableViewCellContentView>
<connections>
<segue destination="iNr-Oe-muq" kind="show" identifier="EditPerson" id="czF-1h-sYn"/>
</connections>
</tableViewCell>
</prototypes>
<connections>
<outlet property="dataSource" destination="cyv-nk-Plb" id="uBb-Bn-Lhg"/>
<outlet property="delegate" destination="cyv-nk-Plb" id="nLb-Ak-ZXS"/>
</connections>
</tableView>
<toolbarItems/>
<navigationItem key="navigationItem" title="Hall Of Fame" id="YLU-iz-PGw"/>
<simulatedToolbarMetrics key="simulatedBottomBarMetrics"/>
<connections>
<segue destination="ein-Sr-i8w" kind="presentation" identifier="NewPerson" id="zii-bJ-cOA"/>
</connections>
</tableViewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="PrM-ex-2C8" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="630" y="640"/>
</scene>
<!--Person Edition View Controller-->
<!--Player Edition View Controller-->
<scene sceneID="Juk-Ad-tZ2">
<objects>
<tableViewController id="iNr-Oe-muq" customClass="PersonEditionViewController" 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">
<tableViewController id="iNr-Oe-muq" customClass="PlayerEditionViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<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"/>
@@ -72,13 +20,14 @@
<tableViewSection id="Nzq-eO-jT3">
<cells>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="2gb-gB-918">
<rect key="frame" x="0.0" y="64" width="375" height="44"/>
<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">
<frame key="frameInset" width="375" height="44"/>
<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="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>
@@ -87,20 +36,21 @@
</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>
</tableViewCellContentView>
</tableViewCell>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="vp3-Ft-Gth">
<rect key="frame" x="0.0" y="108" width="375" height="44"/>
<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">
<frame key="frameInset" width="375" height="44"/>
<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="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>
@@ -108,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>
@@ -124,12 +74,12 @@
<navigationItem key="navigationItem" id="U4g-xG-W8b">
<barButtonItem key="leftBarButtonItem" systemItem="cancel" id="VIN-Hi-Twt">
<connections>
<segue destination="lTz-K0-aRY" kind="unwind" unwindAction="cancelPersonEdition:" id="fOs-ol-qJL"/>
<segue destination="lTz-K0-aRY" kind="unwind" unwindAction="cancelPlayerEdition:" id="fOs-ol-qJL"/>
</connections>
</barButtonItem>
<barButtonItem key="rightBarButtonItem" systemItem="done" id="2um-u5-BhV">
<barButtonItem key="rightBarButtonItem" style="done" systemItem="done" id="2um-u5-BhV">
<connections>
<segue destination="lTz-K0-aRY" kind="unwind" identifier="" unwindAction="commitPersonEdition:" id="Y1E-dI-wcl"/>
<segue destination="lTz-K0-aRY" kind="unwind" identifier="Commit" unwindAction="commitPlayerEdition:" id="Y1E-dI-wcl"/>
</connections>
</barButtonItem>
</navigationItem>
@@ -146,79 +96,14 @@
<placeholder placeholderIdentifier="IBFirstResponder" id="fNC-Ls-uRw" userLabel="First Responder" sceneMemberID="firstResponder"/>
<exit id="lTz-K0-aRY" userLabel="Exit" sceneMemberID="exit"/>
</objects>
<point key="canvasLocation" x="1450" y="1435"/>
</scene>
<!--GRDB Demo-->
<scene sceneID="XjB-aQ-v94">
<objects>
<tableViewController id="9kw-c5-KTk" customClass="DemoViewController" 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="f4Y-o2-7VW">
<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"/>
<sections>
<tableViewSection id="dCg-qU-h2X">
<cells>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" textLabel="clL-nG-zPX" style="IBUITableViewCellStyleDefault" id="kJB-sX-YAb">
<rect key="frame" x="0.0" y="64" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="kJB-sX-YAb" id="f5l-ob-3DG">
<frame key="frameInset" width="342" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Simple TableView" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="clL-nG-zPX">
<frame key="frameInset" minX="15" width="325" height="43.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="16"/>
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<nil key="highlightedColor"/>
</label>
</subviews>
</tableViewCellContentView>
<connections>
<segue destination="cyv-nk-Plb" kind="show" id="Bgq-9t-jRc"/>
</connections>
</tableViewCell>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" textLabel="I78-c5-0kp" style="IBUITableViewCellStyleDefault" id="q4C-mT-5mi">
<rect key="frame" x="0.0" y="108" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="q4C-mT-5mi" id="2Cu-K1-hiz">
<frame key="frameInset" width="342" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="FetchedRecordsController" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="I78-c5-0kp">
<frame key="frameInset" minX="15" width="325" height="43.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="16"/>
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<nil key="highlightedColor"/>
</label>
</subviews>
</tableViewCellContentView>
<connections>
<segue destination="PJp-Eq-ZjA" kind="show" id="1fk-ZR-6XN"/>
</connections>
</tableViewCell>
</cells>
</tableViewSection>
</sections>
<connections>
<outlet property="dataSource" destination="9kw-c5-KTk" id="IK7-Os-Odc"/>
<outlet property="delegate" destination="9kw-c5-KTk" id="U7E-yB-s8d"/>
</connections>
</tableView>
<navigationItem key="navigationItem" title="GRDB Demo" id="z0z-02-Ucy"/>
</tableViewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="OhY-4B-BcJ" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-190" y="1435"/>
<point key="canvasLocation" x="1134" y="2891"/>
</scene>
<!--Navigation Controller-->
<scene sceneID="2KX-IU-Z5Q">
<objects>
<navigationController id="ein-Sr-i8w" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="zIT-dB-Mfo">
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
<rect key="frame" x="0.0" y="20" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
@@ -227,49 +112,49 @@
</navigationController>
<placeholder placeholderIdentifier="IBFirstResponder" id="kNr-vk-I5l" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="630" y="1435"/>
<point key="canvasLocation" x="1134" y="2071"/>
</scene>
<!--Navigation Controller-->
<scene sceneID="N1X-4j-Re4">
<objects>
<navigationController id="UAh-8N-CM8" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="U7d-1C-GnL">
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
<rect key="frame" x="0.0" y="20" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
<segue destination="9kw-c5-KTk" kind="relationship" relationship="rootViewController" id="qDW-qI-Hyg"/>
<segue destination="PJp-Eq-ZjA" kind="relationship" relationship="rootViewController" id="klT-ZP-gtX"/>
</connections>
</navigationController>
<placeholder placeholderIdentifier="IBFirstResponder" id="sVt-e9-ghQ" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-1006" y="1435"/>
<point key="canvasLocation" x="-459" y="2071"/>
</scene>
<!--Hall Of Fame-->
<scene sceneID="9su-ms-vdJ">
<objects>
<tableViewController id="PJp-Eq-ZjA" customClass="PersonsViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<tableViewController id="PJp-Eq-ZjA" customClass="PlayersViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="tX0-ON-WSI">
<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"/>
<prototypes>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Person" textLabel="G8y-VE-YRu" detailTextLabel="NNc-J4-xiE" style="IBUITableViewCellStyleValue1" id="bFj-Hd-fwd">
<frame key="frameInset" minY="92" width="375" height="44"/>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Player" textLabel="G8y-VE-YRu" detailTextLabel="NNc-J4-xiE" style="IBUITableViewCellStyleValue1" id="bFj-Hd-fwd">
<rect key="frame" x="0.0" y="28" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="bFj-Hd-fwd" id="kDf-TZ-xhb">
<frame key="frameInset" width="342" height="43.5"/>
<rect key="frame" x="0.0" y="0.0" width="341" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="G8y-VE-YRu">
<frame key="frameInset" minX="15" minY="12" width="31.5" height="19.5"/>
<rect key="frame" x="16" y="12" width="31.5" height="19.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="16"/>
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="NNc-J4-xiE">
<frame key="frameInset" minX="298.5" minY="12" width="41.5" height="19.5"/>
<rect key="frame" x="298.5" y="12" width="41.5" height="19.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="16"/>
<color key="textColor" red="0.5568627451" green="0.5568627451" blue="0.57647058819999997" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
@@ -278,7 +163,7 @@
</subviews>
</tableViewCellContentView>
<connections>
<segue destination="iNr-Oe-muq" kind="show" identifier="EditPerson" id="Lgu-Yd-HSy"/>
<segue destination="iNr-Oe-muq" kind="show" identifier="Edit" id="Lgu-Yd-HSy"/>
</connections>
</tableViewCell>
</prototypes>
@@ -291,20 +176,23 @@
<barButtonItem title="Item" id="hMF-Rv-dAe"/>
</toolbarItems>
<navigationItem key="navigationItem" title="Hall Of Fame" id="QIv-M6-kT1">
<barButtonItem key="rightBarButtonItem" systemItem="add" id="2bK-Fl-55Q"/>
<barButtonItem key="leftBarButtonItem" systemItem="add" id="2bK-Fl-55Q">
<connections>
<segue destination="ein-Sr-i8w" kind="presentation" identifier="New" id="ehP-ZN-Nt4"/>
</connections>
</barButtonItem>
</navigationItem>
<simulatedToolbarMetrics key="simulatedBottomBarMetrics"/>
<connections>
<segue destination="ein-Sr-i8w" kind="presentation" identifier="NewPerson" id="7PC-xN-zD4"/>
<outlet property="newPlayerButtonItem" destination="2bK-Fl-55Q" id="O9m-8s-oRL"/>
</connections>
</tableViewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="af5-Qo-AkD" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="630" y="2254"/>
<point key="canvasLocation" x="348" y="2071"/>
</scene>
</scenes>
<inferredMetricsTieBreakers>
<segue reference="7PC-xN-zD4"/>
<segue reference="czF-1h-sYn"/>
<segue reference="Lgu-Yd-HSy"/>
</inferredMetricsTieBreakers>
</document>
@@ -1,10 +0,0 @@
import UIKit
class DemoViewController: UITableViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
navigationController?.isToolbarHidden = true
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Demo", style: .plain, target: nil, action: nil)
}
}
Binary file not shown.
+4 -2
View File
@@ -4,8 +4,6 @@
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>GRDB Demo</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
@@ -18,6 +16,8 @@
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
@@ -33,6 +33,8 @@
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
@@ -1,49 +0,0 @@
import GRDB
class Person: Record {
var id: Int64?
var name: String
var score: Int
init(name: String, score: Int) {
self.name = name
self.score = score
super.init()
}
// MARK: Record overrides
override class var databaseTableName: String {
return "persons"
}
required init(row: Row) {
id = row["id"]
name = row["name"]
score = row["score"]
super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
container["id"] = id
container["name"] = name
container["score"] = score
}
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
// MARK: Random
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é"]
class func randomName() -> String {
return names[Int(arc4random_uniform(UInt32(names.count)))]
}
class func randomScore() -> Int {
return 10 * Int(arc4random_uniform(101))
}
}
@@ -1,234 +0,0 @@
import UIKit
import GRDB
class PersonsViewController: UITableViewController {
var personsController: FetchedRecordsController<Person>!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItems = [
UIBarButtonItem(barButtonSystemItem: .add, target: self, action: .addPerson),
editButtonItem
]
personsController = try! FetchedRecordsController(dbQueue, request: personsSortedByScore)
personsController.trackChanges(
willChange: { [unowned self] _ in
self.tableView.beginUpdates()
},
onChange: { [unowned self] (controller, record, change) in
switch change {
case .insertion(let indexPath):
self.tableView.insertRows(at: [indexPath], with: .fade)
case .deletion(let indexPath):
self.tableView.deleteRows(at: [indexPath], with: .fade)
case .update(let indexPath, _):
if let cell = self.tableView.cellForRow(at: indexPath) {
self.configure(cell, at: indexPath)
}
case .move(let indexPath, let newIndexPath, _):
// Actually move cells around for more demo effect :-)
let cell = self.tableView.cellForRow(at: indexPath)
self.tableView.moveRow(at: indexPath, to: newIndexPath)
if let cell = cell {
self.configure(cell, at: newIndexPath)
}
// A quieter animation:
// self.tableView.deleteRows(at: [indexPath], with: .fade)
// self.tableView.insertRows(at: [newIndexPath], with: .fade)
}
},
didChange: { [unowned self] _ in
self.tableView.endUpdates()
})
try! personsController.performFetch()
configureToolbar()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isToolbarHidden = false
}
}
// MARK: - Navigation
extension PersonsViewController : PersonEditionViewControllerDelegate {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "EditPerson" {
let person = personsController.record(at: tableView.indexPathForSelectedRow!)
let controller = segue.destination as! PersonEditionViewController
controller.title = person.name
controller.person = person
controller.delegate = self // we will save person when back button is tapped
controller.cancelButtonHidden = true
controller.commitButtonHidden = true
}
else if segue.identifier == "NewPerson" {
setEditing(false, animated: true)
let navigationController = segue.destination as! UINavigationController
let controller = navigationController.viewControllers.first as! PersonEditionViewController
controller.title = "New Person"
controller.person = Person(name: "", score: 0)
}
}
@IBAction func addPerson(_ sender: AnyObject?) {
performSegue(withIdentifier: "NewPerson", sender: sender)
}
@IBAction func cancelPersonEdition(_ segue: UIStoryboardSegue) {
// Person creation: cancel button was tapped
}
@IBAction func commitPersonEdition(_ segue: UIStoryboardSegue) {
// Person creation: commit button was tapped
let controller = segue.source as! PersonEditionViewController
controller.applyChanges()
let person = controller.person!
if !person.name.isEmpty {
try! dbQueue.inDatabase { db in
try person.save(db)
}
}
}
func personEditionControllerDidComplete(_ controller: PersonEditionViewController) {
// Person edition: back button was tapped
controller.applyChanges()
let person = controller.person!
if !person.name.isEmpty {
try! dbQueue.inDatabase { db in
try person.save(db)
}
}
}
}
// MARK: - UITableViewDataSource
extension PersonsViewController {
func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
let person = personsController.record(at: indexPath)
cell.textLabel?.text = person.name
cell.detailTextLabel?.text = abs(person.score) > 1 ? "\(person.score) points" : "0 point"
}
override func numberOfSections(in tableView: UITableView) -> Int {
return personsController.sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return personsController.sections[section].numberOfRecords
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath)
configure(cell, at: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
// Delete the person
let person = personsController.record(at: indexPath)
try! dbQueue.inDatabase { db in
_ = try person.delete(db)
}
}
}
// MARK: - FetchedRecordsController Demo
extension PersonsViewController {
fileprivate func configureToolbar() {
toolbarItems = [
UIBarButtonItem(title: "Name ⬆︎", style: .plain, target: self, action: .sortByName),
UIBarButtonItem(title: "Score ⬇︎", style: .plain, target: self, action: .sortByScore),
UIBarButtonItem(title: "Randomize", style: .plain, target: self, action: .randomizeScores),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "💣", style: .plain, target: self, action: .stressTest)
]
}
@IBAction func sortByName() {
setEditing(false, animated: true)
try! personsController.setRequest(personsSortedByName)
}
@IBAction func sortByScore() {
setEditing(false, animated: true)
try! personsController.setRequest(personsSortedByScore)
}
@IBAction func randomizeScores() {
setEditing(false, animated: true)
try! dbQueue.inTransaction { db in
for person in try Person.fetchAll(db) {
person.score = Person.randomScore()
try person.update(db)
}
return .commit
}
}
@IBAction func stressTest() {
setEditing(false, animated: true)
for _ in 0..<50 {
DispatchQueue.global().async {
try! dbQueue.inTransaction { db in
if try Person.fetchCount(db) == 0 {
// Insert persons
for _ in 0..<8 {
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
}
} else {
// Insert a person
if arc4random_uniform(2) == 0 {
let person = Person(name: Person.randomName(), score: Person.randomScore())
try person.insert(db)
}
// Delete a person
if arc4random_uniform(2) == 0 {
if let person = try Person.order(sql: "RANDOM()").fetchOne(db) {
try person.delete(db)
}
}
// Update some persons
for person in try Person.fetchAll(db) {
if arc4random_uniform(2) == 0 {
person.score = Person.randomScore()
try person.update(db)
}
}
}
return .commit
}
}
}
}
}
// https://medium.com/swift-programming/swift-selector-syntax-sugar-81c8a8b10df3
private extension Selector {
static let addPerson = #selector(PersonsViewController.addPerson(_:))
static let sortByName = #selector(PersonsViewController.sortByName)
static let sortByScore = #selector(PersonsViewController.sortByScore)
static let randomizeScores = #selector(PersonsViewController.randomizeScores)
static let stressTest = #selector(PersonsViewController.stressTest)
}
private let personsSortedByName = Person.order(Column("name"))
private let personsSortedByScore = Person.order(Column("score").desc, Column("name"))
@@ -0,0 +1,65 @@
import GRDB
// A plain Player struct
struct Player {
// Prefer Int64 for auto-incremented database ids
var id: Int64?
var name: String
var score: Int
}
// 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 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 {
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.randomElement()!
}
static func randomScore() -> Int {
return 10 * Int.random(in: 0...100)
}
}
@@ -1,14 +1,16 @@
import UIKit
protocol PersonEditionViewControllerDelegate: class {
func personEditionControllerDidComplete(_ controller: PersonEditionViewController)
}
class PersonEditionViewController: UITableViewController {
weak var delegate: PersonEditionViewControllerDelegate?
var person: Person! { didSet { configureView() } }
var cancelButtonHidden: Bool = false { didSet { configureView() } }
var commitButtonHidden: Bool = false { didSet { configureView() } }
class PlayerEditionViewController: UITableViewController {
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 presentation: Presentation! { didSet { configureView() } }
@IBOutlet fileprivate weak var cancelBarButtonItem: UIBarButtonItem!
@IBOutlet fileprivate weak var commitBarButtonItem: UIBarButtonItem!
@@ -17,38 +19,29 @@ class PersonEditionViewController: UITableViewController {
@IBOutlet fileprivate weak var scoreCell: UITableViewCell!
@IBOutlet fileprivate weak var scoreTextField: UITextField!
func applyChanges() {
if let name = nameTextField.text, !name.isEmpty {
person.name = name
}
person.score = scoreTextField.text.flatMap { Int($0) } ?? 0
}
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
private func configureView() {
fileprivate func configureView() {
guard isViewLoaded else { return }
nameTextField.text = person.name
if person.score == 0 && person.id == nil {
nameTextField.text = player.name
if player.score == 0 && player.id == nil {
scoreTextField.text = ""
} else {
scoreTextField.text = "\(person.score)"
scoreTextField.text = "\(player.score)"
}
if cancelButtonHidden {
navigationItem.leftBarButtonItem = nil
} else {
switch presentation! {
case .modal:
navigationItem.leftBarButtonItem = cancelBarButtonItem
}
if cancelButtonHidden {
navigationItem.rightBarButtonItem = nil
} else {
navigationItem.rightBarButtonItem = commitBarButtonItem
case .push:
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
}
}
}
@@ -56,7 +49,7 @@ class PersonEditionViewController: UITableViewController {
// MARK: - Navigation
extension PersonEditionViewController {
extension PlayerEditionViewController {
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
// Force keyboard to dismiss early
@@ -64,12 +57,23 @@ extension PersonEditionViewController {
return true
}
override func willMove(toParentViewController parent: UIViewController?) {
super.willMove(toParentViewController: parent)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Commit" {
saveChanges()
}
}
override func willMove(toParent parent: UIViewController?) {
super.willMove(toParent: parent)
if parent == nil {
// Self is popping from its navigation controller
delegate?.personEditionControllerDidComplete(self)
switch presentation! {
case .modal:
break
case .push:
if parent == nil {
// Self is popping from its navigation controller
saveChanges()
}
}
}
@@ -78,7 +82,7 @@ extension PersonEditionViewController {
// MARK: - Form
extension PersonEditionViewController: UITextFieldDelegate {
extension PlayerEditionViewController: UITextFieldDelegate {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
@@ -101,4 +105,17 @@ extension PersonEditionViewController: UITextFieldDelegate {
}
return false
}
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)
}
}
}
@@ -0,0 +1,259 @@
import UIKit
import GRDB
/// PlayersViewController displays the list of players.
class PlayersViewController: UITableViewController {
private enum PlayerOrdering {
case byName
case 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(playersRequest)
configureOrderingBarButtonItem()
}
}
private var playersRequest: QueryInterfaceRequest<Player> {
switch playerOrdering {
case .byName:
return Player.orderedByName()
case .byScore:
return Player.orderedByScore()
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureToolbar()
configureNavigationItem()
configureTableView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isToolbarHidden = false
}
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))
}
}
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"
}
}
}
private func configureTableView() {
// 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()
},
onChange: { [unowned self] (controller, record, change) in
switch change {
case .insertion(let indexPath):
self.tableView.insertRows(at: [indexPath], with: .fade)
case .deletion(let indexPath):
self.tableView.deleteRows(at: [indexPath], with: .fade)
case .update(let indexPath, _):
if let cell = self.tableView.cellForRow(at: indexPath) {
self.configure(cell, at: indexPath)
}
case .move(let indexPath, let newIndexPath, _):
// Actually move cells around for more demo effect :-)
let cell = self.tableView.cellForRow(at: indexPath)
self.tableView.moveRow(at: indexPath, to: newIndexPath)
if let cell = cell {
self.configure(cell, at: newIndexPath)
}
// A quieter animation:
// self.tableView.deleteRows(at: [indexPath], with: .fade)
// self.tableView.insertRows(at: [newIndexPath], with: .fade)
}
},
didChange: { [unowned self] _ in
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
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return playersController.sections[section].numberOfRecords
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
configure(cell, at: indexPath)
return cell
}
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
_ = try player.delete(db)
}
}
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
let player = playersController.record(at: indexPath)
if player.name.isEmpty {
cell.textLabel?.text = "-"
} else {
cell.textLabel?.text = player.name
}
cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point"
}
}
// MARK: - Actions
extension PlayersViewController {
@IBAction func sortByName() {
setEditing(false, animated: true)
playerOrdering = .byName
}
@IBAction func sortByScore() {
setEditing(false, animated: true)
playerOrdering = .byScore
}
@IBAction func deletePlayers() {
setEditing(false, animated: true)
try! dbQueue.write { db in
_ = try Player.deleteAll(db)
}
}
@IBAction func refresh() {
setEditing(false, animated: true)
refreshPlayers()
}
@IBAction func stressTest() {
setEditing(false, animated: true)
for _ in 0..<50 {
DispatchQueue.global().async {
self.refreshPlayers()
}
}
}
private func refreshPlayers() {
try! dbQueue.write { db in
if try Player.fetchCount(db) == 0 {
// Insert new random players
for _ in 0..<8 {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
} else {
// Insert a player
if Bool.random() {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
// Delete a random player
if Bool.random() {
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
}
// Update some players
for var player in try Player.fetchAll(db) where Bool.random() {
player.score = Player.randomScore()
try player.update(db)
}
}
}
}
}
@@ -1,114 +0,0 @@
import UIKit
import GRDB
class SimplePersonsViewController: UITableViewController {
var persons: [Person]!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItems = [
UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(SimplePersonsViewController.addPerson(_:))),
editButtonItem
]
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadPersons()
tableView.reloadData()
}
private func loadPersons() {
persons = try! dbQueue.inDatabase { db in
try Person.order(Column("score").desc, Column("name")).fetchAll(db)
}
}
}
// MARK: - Navigation
extension SimplePersonsViewController : PersonEditionViewControllerDelegate {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "EditPerson" {
let person = persons[tableView.indexPathForSelectedRow!.row]
let controller = segue.destination as! PersonEditionViewController
controller.title = person.name
controller.person = person
controller.delegate = self // we will save person when back button is tapped
controller.cancelButtonHidden = true
controller.commitButtonHidden = true
}
else if segue.identifier == "NewPerson" {
setEditing(false, animated: true)
let navigationController = segue.destination as! UINavigationController
let controller = navigationController.viewControllers.first as! PersonEditionViewController
controller.title = "New Person"
controller.person = Person(name: "", score: 0)
}
}
@IBAction func addPerson(_ sender: AnyObject?) {
performSegue(withIdentifier: "NewPerson", sender: sender)
}
@IBAction func cancelPersonEdition(_ segue: UIStoryboardSegue) {
// Person creation: cancel button was tapped
}
@IBAction func commitPersonEdition(_ segue: UIStoryboardSegue) {
// Person creation: commit button was tapped
let controller = segue.source as! PersonEditionViewController
controller.applyChanges()
let person = controller.person!
if !person.name.isEmpty {
try! dbQueue.inDatabase { db in
try person.save(db)
}
}
}
func personEditionControllerDidComplete(_ controller: PersonEditionViewController) {
// Person edition: back button was tapped
controller.applyChanges()
let person = controller.person!
if !person.name.isEmpty {
try! dbQueue.inDatabase { db in
try person.save(db)
}
}
}
}
// MARK: - UITableViewDataSource
extension SimplePersonsViewController {
func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
let person = persons[indexPath.row]
cell.textLabel?.text = person.name
cell.detailTextLabel?.text = abs(person.score) > 1 ? "\(person.score) points" : "0 point"
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return persons.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath)
configure(cell, at: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
// Delete the person
let person = persons[indexPath.row]
try! dbQueue.inDatabase { db in
_ = try person.delete(db)
}
persons.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
+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.
File diff suppressed because it is too large. Load diff
+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.21.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 v2.4.0
git checkout v3.6.2
git submodule update --init SQLiteCustom/src
````
-591
View File
@@ -1,591 +0,0 @@
GRDB Extension Guide
====================
**Some parts of GRDB are extensible, so that you can make it better fit your needs.**
This guide is a step-by-step tour of GRDB extensibility, around a few topics:
- **[Add a value type](#add-a-value-type)**
You'll learn how to turn UIColor into a value type that you can store, fetch, and use in your records:
```swift
let rows = try Row.fetchCursor(db, "SELECT name, color FROM clothes")
while let row = try rows.next() {
let name: String = row["name"]
let color: UIColor = row["color"] // <-- New! UIColor as value
}
```
- **[Add an SQLite function or operator](#add-an-sqlite-function-or-operator)**
You'll learn how to add support for the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) function, and the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator:
```swift
Books.select(strftime("%Y", Column("publishedDate"))) // <-- New! strftime function
Books.filter(Column("body").glob("*Moby-Dick*")) // <-- New! glob method
```
- **[Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression)**
You'll learn how to add support for [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr):
```swift
let jsonString = Column("jsonString")
let request = Books.select(cast(jsonString, as: .blob)) // <-- New! cast function
let rows = try Row.fetchCursor(db, request)
while let row = try rows.next() {
let data = row.dataNoCopy(atIndex: 0)
}
```
- **Extend the query interface requests**
You may need to extend the [query interface requests](../../../#requests) so that their SELECT queries could embed recursive clauses, table joins, etc.
Pull requests are welcome. Open issues if you have questions.
Meanwhile, you can build your own [custom requests](../../../#custom-requests).
- **[Add a custom FTS5 full-text tokenizer](FTS5Tokenizers.md)**
Custom tokenizers can leverage extra full-text features such as synonyms or stop words.
- **Support a new kind of SQL query**
For example, you may need to generate SQL triggers, or create specific kinds of virtual tables.
Pull requests are welcome. Open issues if you have questions.
## Add a Value Type
**All value types adopt the [DatabaseValueConvertible protocol](../../../#custom-value-types).**
```swift
protocol DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue { get }
/// Returns a value initialized from databaseValue, if possible.
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self?
}
```
The `databaseValue` property returns [DatabaseValue](../../../#databasevalue), a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and Data. Since DatabaseValue has no public initializer, use `DatabaseValue.null`, or another type that already adopts the protocol: `1.databaseValue`, `"foo".databaseValue`, etc. Conversion to DatabaseValue *must not* fail.
The `fromDatabaseValue()` factory method returns an instance of your custom type if the databaseValue contains a suitable value. If the databaseValue does not contain a suitable value, such as "foo" for Date, `fromDatabaseValue` *must* return nil (GRDB will interpret this nil result as a conversion error, and react accordingly).
**What does the DatabaseValueConvertible protocol bring to a type like UIColor?**
Well, you will be able to use UIColor like all other [value types](../../../#values) (Bool, Int, String, Date, Swift enums, etc.):
- Use UIColor as [statement arguments](../../../#executing-updates):
```swift
try db.execute(
"INSERT INTO clothes (name, color) VALUES (?, ?)",
arguments: ["Shirt", UIColor.red])
```
- UIColor can be [extracted from rows](../../../#column-values):
```swift
let rows = try Row.fetchCursor(db, "SELECT * FROM clothes")
while let row = try rows.next() {
let name: String = row["name"]
let color: UIColor = row["color"]
}
```
- UIColor can be [directly fetched](../../../#value-queries):
```swift
let colors = try UIColor.fetchAll(db, "SELECT DISTINCT color FROM clothes") // [UIColor]
```
- Use UIColor in [Records](../../../#records):
```swift
class ClothingItem : Record {
var name: String
var color: UIColor
required init(row: Row) {
name = row["name"]
color = row["color"]
super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
container["name"] = name
container["color"] = color
}
}
```
- Use UIColor in the [query interface](../../../#the-query-interface):
```swift
let redClothes = try ClothingItem.filter(colorColumn == UIColor.red).fetchAll(db)
```
**Let's have UIColor adopt DatabaseValueConvertible**
In order to preserve as most information as possible, we'll archive UIColor as a data blob using the NSCoding protocol. But YMMV.
```swift
extension UIColor : DatabaseValueConvertible {
/// Encode UIColor as a data blob
var databaseValue: DatabaseValue {
// Use NSKeyedArchiver to build Data
let data = NSKeyedArchiver.archivedData(withRootObject: self)
// Data is already DatabaseValueConvertible
return data.databaseValue
}
/// Returns a UIColor if databaseValue contains suitable data, and
/// nil otherwise.
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
// Only Data blobs can contain a UIColor
guard let data = Data.fromDatabaseValue(databaseValue) else {
return nil
}
// We're looking for an archived object
guard let color = NSKeyedUnarchiver.unarchiveObject(with: data) else {
return nil
}
// The cast function will return nil if the unarchived object doesn't
// have the correct type
return cast(color) // Converts Any to Self?
}
}
```
Use the `cast` utility function when you want *non-final classes* to implement DatabaseValueConvertible. It avoids compiler errors that are not easy to deal with. Note that final classes and value types won't need it.
```swift
// Workaround Swift inconvenience around factories methods of non-final classes
func cast<T, U>(_ value: T) -> U? {
return value as? U
}
```
## Add an SQLite Function or Operator
**When an SQLite [function](https://www.sqlite.org/lang_corefunc.html) or [operator](https://www.sqlite.org/lang_expr.html) is missing from GRDB**, this usually means that there hasn't been a [feature request](http://github.com/groue/GRDB.swift/issues) yet.
But you don't have to wait: you can extend GRDB and the query interface to add support for the missing syntax element (and eventually submit a pull request later).
Let's remind our goal: we'll add the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) function, and the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator.
Their SQL usage is the following:
```sql
-- Publication years of books
SELECT STRFTIME('%Y', publishedOn) FROM books;
-- Books that talk about Moby Dick
SELECT * FROM books WHERE body GLOB '*Moby-Dick*';
```
Translated in the query interface, this gives:
```swift
Books.select(strftime("%Y", Column("publishedDate")))
Books.filter(Column("body").glob("*Moby-Dick*"))
```
`strftime` is a top-level Swift function because this is how GRDB usually imports SQLite functions which do not have matching standard Swift counterpart, like AVG, LEGNTH, SUM. It helps the Swift code looking like SQL when it is relevant.
In the same fashion, we expose the GLOB SQL operator as the `glob` Swift method, just because `value.glob(pattern)` reads like `value GLOB pattern`.
Whenever you import a SQL feature to Swift, you'll have to decide: should you preserve the SQL look and feel, or adopt a well-established swiftism? It's really up to you.
### STRFTIME
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
The [STRFTIME](https://www.sqlite.org/lang_datefunc.html) SQL function accepts many arguments. We'll simplify it to `strftime(format, date)`, so that we can write:
```sql
// Publication years of books
// SELECT STRFTIME('%Y', publishedOn) FROM books
Books.select(strftime("%Y", Column("publishedDate")))
```
The signature of the Swift `strftime` function is:
```swift
func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression
```
SQLSpecificExpressible and SQLExpression are types of the [query interface](../../../#the-query-interface) that you do not usually see. We have moved down one floor, closer to the SQL guts of GRDB. We'll see more new types and protocols below.
The return value is SQLExpression. All GRDB functions and operators that build [query interface expressions](../../../#expressions) return values of this type. It represents actual [SQLite expressions](https://www.sqlite.org/lang_expr.html).
SQLExpression is a protocol, so that you can build your own [custom expressions](#add-a-new-kind-of-sqlite-expression). But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, and here we'll use SQLExpressionFunction that is dedicated to function calls:
```swift
struct SQLExpressionFunction : SQLExpression {
/// Creates an SQL function call
///
/// // ABS(-1)
/// SQLExpressionFunction(.abs, arguments: -1)
init(_ functionName: SQLFunctionName, arguments: SQLExpressible...)
}
```
So here is the code that defines our `strftime` function:
```swift
// Add a SQLFunctionName just like we add NSNotification.Name since
// the release of Swift 3.
extension SQLFunctionName {
/// The `STRFTIME` SQL function
static let strftime = SQLFunctionName("STRFTIME")
}
/// Returns an expression that evaluates the `STRFTIME` SQL function.
///
/// // STRFTIME('%Y', date)
/// strftime("%Y", Column("date"))
func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionFunction(.strftime, arguments: format, date)
}
```
The `strftime` function is now complete, ready to be used. We haven't yet described the SQLSpecificExpressible type of the `date` argument:
SQLSpecificExpressible is the protocol for all types that can be turned into a SQL expression, but types like Int, Date, or UIColor that exist outside of GRDB and the query interface. Having `strftime` accept a SQLSpecificExpressible date prevents it from polluting the global space. It is *specific* to GRDB:
```swift
strftime("%Y", Date()) // Compiler error
strftime("%Y", Column("date")) // SQLExpression: STRFTIME('%Y', date)
```
You may want to compare it to another protocol, SQLExpressible, which will be described [below](#add-a-new-kind-of-sqlite-expression), when we add support for CAST SQL expressions.
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `strftime` function, it is the SQLSpecificExpressible protocol.
### GLOB
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
For the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator, we want to define the glob Swift method:
```swift
// Books that talk about Moby Dick
// SELECT * FROM books WHERE body GLOB '*Moby-Dick*'
Books.filter(Column("body").glob("*Moby-Dick*"))
```
This time we can't use the SQLExpressionFunction type, because it can't generate the SQL for a binary operator. Instead, we'll use another [built-in expression](#built-in-expressions), SQLExpressionBinary:
```swift
struct SQLExpressionBinary : SQLExpression {
/// Creates an expression made of two expressions joined with a binary operator.
///
/// // length * width
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible)
}
```
Now we have to find the signature of our Swift method. The GLOB operator accepts any value on both sides. However, what kind of Swift code should we accept?
```swift
// 1) body GLOB '*Moby-Dick*' -- Yes, of course
Column("body").glob("*Moby-Dick*")
// 2) body GLOB pattern -- Sure, why not?
Column("body").glob(Column("pattern"))
// 3) 'Some Swift String' GLOB pattern - Not sure, but OK
"Some Swift String".glob(Column("pattern"))
// 4) 'Some Swift String' GLOB 'Another Swift String' -- NO
"Some Swift String".glob("Another Swift String")
```
We don't want the form 4, because this is an unacceptable pollution of the Swift global namespace. A good GRDB extension limits its scope to database-related code.
We thus have two overloaded definitions of the `glob` method:
```swift
extension SQLSpecificExpressible {
func glob(_ pattern: SQLExpressible) -> SQLExpression
}
extension SQLExpressible {
func glob(_ pattern: SQLSpecificExpressible) -> SQLExpression
}
```
SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all expressions, and all [value types](../../../#values) (including String).
SQLSpecificExpressible is a sub protocol of SQLExpressible protocol, restricted to all types that can be turned into a SQL expression, but types like Int, Date, or String that exist outside of GRDB and the query interface.
By extending both, we can define the GLOB operators for any pair that contains at least one type that is specific to GRDB - and leave the global Swift space clean.
The final implementation follows:
```swift
// Add a SQLBinaryOperator just like we add NSNotification.Name since
// the release of Swift 3.
extension SQLBinaryOperator {
/// The `GLOB` binary operator
static let glob = SQLBinaryOperator("GLOB")
}
extension SQLSpecificExpressible {
/// Returns an SQL `GLOB` expression.
///
/// // body GLOB '*Moby-Dick*'
/// Column("body").glob("*Moby-Dick*")
func glob(_ pattern: SQLExpressible) -> SQLExpression {
return SQLExpressionBinary(.glob, self, pattern)
}
}
extension SQLExpressible {
/// Returns an SQL `GLOB` expression.
///
/// // 'Some Swift String' GLOB pattern
/// "Some Swift String".glob(Column("pattern"))
func glob(_ pattern: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.glob, self, pattern)
}
}
```
### Built-in Expressions
When you extend GRDB with a new function, method, or operator that generates an [SQL expression](https://www.sqlite.org/lang_expr.html), you have to return a value the adopts the SQLExpression protocol.
We have already seen in our [previous](#strftime) [examples](#glob) two concrete types that generate SQL function calls and binary operators: SQLExpressionFunction and SQLExpressionBinary.
This section of the documentation lists all built-in expressions. Adding a custom SQLExpression type will be documented [below](#add-a-new-kind-of-sqlite-expression).
#### Column and DatabaseValue
The [Column](../../../#the-query-interface) type from the query interface, and [DatabaseValue](../../../#databasevalue), the type that wraps the five values supported by SQLite (NULL, Int64, Double, String and Data) are expressions. They are rather trivial, and it is unlikely that you use them in your GRDB extensions.
#### SQLExpressionLiteral
Use SQLExpressionLiteral when you need to go fast:
```swift
struct SQLExpressionLiteral : SQLExpression {
/// Creates an SQL literal expression.
///
/// SQLExpressionLiteral("1 + 2")
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
init(_ sql: String, arguments: StatementArguments? = nil)
}
```
For an example of use, see the [Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression) chapter.
#### SQLExpressionUnary
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
SQLExpressionUnary builds an expression by prefixing another expression with an unary operator:
```swift
struct SQLExpressionUnary : SQLExpression {
/// Creates an expression made of an unary operator and
/// an operand expression.
///
/// // NOT favorite
/// SQLExpressionUnary(.not, Column("favorite"))
init(_ op: SQLUnaryOperator, _ value: SQLExpressible)
}
```
You add missing SQLite unary operators by extending SQLUnaryOperator:
```swift
extension SQLUnaryOperator {
/// The `+` unary operator
static let plus = SQLUnaryOperator("+", needsRightSpace: false)
}
```
#### SQLExpressionBinary
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
SQLExpressionBinary builds an expression by joining two expressions with a binary operator:
```swift
struct SQLExpressionBinary : SQLExpression {
/// Creates an expression made of two expressions joined with a binary operator.
///
/// // length * width
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible)
}
```
You add missing SQLite binary operators by extending SQLBinaryOperator:
```swift
extension SQLBinaryOperator {
/// The `GLOB` binary operator
static let glob = SQLBinaryOperator("GLOB")
}
```
#### SQLExpressionFunction
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
SQLExpressionFunction builds an SQL function call:
```swift
struct SQLExpressionFunction : SQLExpression {
/// Creates an SQL function call
///
/// // ABS(-1)
/// SQLExpressionFunction(.abs, arguments: -1)
init(_ functionName: SQLFunctionName, arguments: SQLExpressible...)
}
```
You add missing SQLite function names by extending SQLFunctionName:
```swift
extension SQLFunctionName {
/// The `STRFTIME` SQL function
static let strftime = SQLFunctionName("STRFTIME")
}
```
#### The IN Operator
Build a `value IN (...)` expression from any sequence of [values](../../../#values):
```swift
// SQLExpression: id IN (1, 2, 3)
[1,2,3].contains(Column("id"))
// SQLExpression: id NOT IN (1, 2, 3)
![1,2,3].contains(Column("id"))
```
#### The BETWEEN Operator
Build a `value BETWEEN min AND max` expression from Swift ranges:
```swift
// SQLExpression: id BETWEEN 1 AND 10
1...10.contains(Column("id")
```
#### The COUNT Function
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.4/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.4/Functions.html) functions:
```swift
// SQLExpression: COUNT(email)
count(Column("email"))
// SQLExpression: COUNT(DISTINCT email)
count(distinct: Column("email"))
```
#### The COLLATE Operator
Build a `expression COLLATE collation` expression with the `collating` method:
```swift
// SQLExpression: name = 'Arthur' COLLATE NOCASE
Column("name").collating(.nocase) == "Arthur"
```
## Add a New Kind of SQLite Expression
GRDB does not have built-in support for the full range of the SQLite [expression grammar](https://www.sqlite.org/lang_expr.html).
For example, [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr) are not ready-made. They can be useful, though: a CAST expression can efficiently convert json strings to UTF-8 data blobs for you:
```sql
SELECT CAST(jsonString AS BLOB) FROM books
```
We'll add below a Swift `cast` function:
```swift
let request = Books.select(cast(Column("jsonString"), as: .blob))
let jsonDatas = try Data.fetchAll(db, request) // [Data]
```
`cast` is a top-level Swift function because this is how GRDB usually imports SQLite features which do not have matching standard Swift counterpart. It helps the Swift code looking like SQL when it is relevant. But YMMV.
The signature of the `cast` function is:
```swift
func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression
```
Database.ColumnType is a String-based enumeration of all database column types (.integer, .text, .blob, etc.) You have already used if you have [created tables](../../../#create-tables) using the query interface.
The return type SQLExpression is the type returned by all GRDB functions and operators that build [query interface expressions](../../../#expressions).
SQLExpression is a protocol. But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, so that you generally don't have to write your custom expression type. Here we need something new. So we'll use the most versatile of all, SQLExpressionLiteral:
```swift
struct SQLExpressionLiteral : SQLExpression {
/// Creates an SQL literal expression.
///
/// SQLExpressionLiteral("1 + 2")
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
init(_ sql: String, arguments: StatementArguments? = nil)
}
```
Here is the code that defines our `cast` function:
```swift
func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression {
// Turn the value into a literal expression
let literal: SQLExpressionLiteral = value.sqlExpression.literal
// Build our "CAST(value AS type)" sql snippet
let sql = "CAST(\(literal.sql) AS \(type.rawValue))"
// And return a new literal expression, preserving input arguments
return SQLExpressionLiteral(sql, arguments: literal.arguments)
}
```
We haven't yet described the SQLExpressible type of the `value` argument:
SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all [value types](../../../#values) (Bool, Int, String, Date, Swift enums, etc.):
```swift
cast("foo", as: .blob) // SQLExpression: CAST('foo' AS BLOB)
cast(Column("name"), as: .blob) // SQLExpression: CAST(name AS BLOB)
```
You may want to compare it to another protocol, SQLSpecificExpressible, which has been described [above](#strftime), when we were adding support for the STRFTIME SQL function.
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `cast` function, it is Database.ColumnType.
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/SQLExpression.html) protocol.
+533
View File
@@ -0,0 +1,533 @@
Migrating From GRDB 2 to GRDB 3
===============================
GRDB 3 comes with new features, but also a few breaking changes, and a set of updated good practices. This guide aims at helping you upgrading your applications.
**For all users**
- [Swift 4.1 Required]
- [iOS 8 Sunsetting]
- [Database Schema Recommendations]
- [Record Protocols Renaming]
- [Columns Definition]
**By topic**
- [If You Use Database Queues]
- [If You Use Database Pools]
- [If You Use Database Snapshots]
- [If You Use Record Types]
- [If You Use Custom Requests]
- [If You Use RxGRDB]
- [Notable Documentation Updates]
## Swift 4.1 Required
GRDB 3 uses [conditional conformances], introduced in Swift 4.1. It can only be built on Xcode 9.3+.
## iOS 8 Sunsetting
GRDB 3 is only tested on iOS 9+, due to a limitation in Xcode 9.3. Code that targets older versions of SQLite and iOS is still there, but is not supported.
## Database Schema Recommendations
GRDB 2 was totally schema-agnostic, and would gladly accept any database.
GRDB 3 still accepts any database, but brings two schema recommendations:
- :bulb: Integer primary keys should be auto-incremented, in order to avoid any row id to be reused.
When ids can be reused, your app and [database observation tools] may think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not.
GRDB 3 thus comes with a new good practice: use the `autoIncrementedPrimaryKey` method when you create a database table with an integer primary key:
```diff
try db.create(table: "author") { t in
- t.column("id", .integer).primaryKey() // GRDB 2
+ t.autoIncrementedPrimaryKey("id") // GRDB 3 recommendation
t.column("name", .text).notNull()
}
```
- :bulb: Database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, 'httpRequest'.
This will help you using the new [Associations] feature when you need it. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration.
This convention is applied by the default implementation of the `TableRecord.databaseTableName`: see [If You Use Record Types] below.
Since you are reading this guide, your application has already defined its database schema. You can migrate it in order to apply the new recommendations, if needed. Below is a sample code that uses [DatabaseMigrator], the recommended tool for managing your database schema:
```swift
var migrator = DatabaseMigrator()
// Existing GRDB 2 migration:
migrator.registerMigration("initial") { db in
try db.create(table: "authors") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text).notNull()
}
try db.create(table: "books") { t in
t.column("id", .integer).primaryKey()
t.column("authorId", .integer).notNull().references("authors")
t.column("title", .text).notNull()
}
}
// New GRDB 3 migration:
// - Rename tables so that they look like Swift identifiers (singular and camelCased)
// - Make integer primary keys auto-incremented
//
// Since several tables are recreated from scratch, referential integrity
// constraints may break during the process. The
// registerMigrationWithDeferredForeignKeyCheck method makes sure that foreign
// key checks are temporarily disabled, and checked at the end:
migrator.registerMigrationWithDeferredForeignKeyCheck("GRDB3") { db in
try db.create(table: "author") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorId", .integer).notNull().references("author")
t.column("title", .text).notNull()
}
try db.execute("""
INSERT INTO author SELECT * FROM authors;
INSERT INTO book SELECT * FROM books;
""")
try db.drop(table: "authors")
try db.drop(table: "books")
}
```
## Record Protocols Renaming
GRDB 3 has renamed the [record protocols]:
- `RowConvertible` -> `FetchableRecord`
- `TableMapping` -> `TableRecord`
- `Persistable` -> `PersistableRecord`
- `MutablePersistable` -> `MutablePersistableRecord`
After upgrading, build your project: the compiler will guide you through the renaming by the way of fixits.
## Columns Definition
GRDB 2 has you define columns of the query interface with the Column type:
```swift
// GRDB 2
let nameColumn = Column("name")
let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
```
A recommended practice was to define enum namespaces in record types:
```swift
// GRDB 2
struct Player: RowConvertible, TableMapping {
enum Columns {
static let id = Column("id")
static let name = Column("name")
static let score = Column("score")
}
init(row: Row) {
id = row[Columns.id]
name = row[Columns.name]
score = row[Columns.score]
}
}
```
In GRDB 3, `Column` is still there, but a new `ColumnExpression` protocol has been introduced in order to streamline column enums:
```swift
// GRDB 3
struct Player: FetchableRecord, TableRecord {
enum Columns: String, ColumnExpression {
case id, name, score
}
init(row: Row) {
id = row[Columns.id]
name = row[Columns.name]
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)
}
}
```
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 {
var name: String
var sqlType: String
}
let nameColumn = TypedColumn(name: "name", sqlType: "VARCHAR")
let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
```
## If You Use Database Queues
With GRDB 2, you used to access the database through the `inDatabase` or `inTransaction` [DatabaseQueue] methods:
```swift
// GRDB 2
let players = try dbQueue.inDatabase { db in
try Player.fetchAll(db)
}
try dbQueue.inDatabase { db in
try player.updateChanges(db)
}
var balance: Amount! = nil
try dbQueue.inTransaction { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
balance = try sourceAccount.fetchBalance(db)
return .commit
}
```
The code above still runs, unchanged, in GRDB 3.
Yet it is now recommended that you use the `read` and `write` methods instead:
```swift
// GRDB 3
let players = try dbQueue.read { db in
try Player.fetchAll(db)
}
try dbQueue.write { db in
try player.updateChanges(db)
}
let balance = try dbQueue.write { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
return try sourceAccount.fetchBalance(db)
}
```
The purpose of the new `read` and `write` methods is to soothe the "transaction mental load" of previous versions of GRDB, a legacy of the [FMDB] heritage. All developers can *forget* to open transactions, with the unfortunate consequence that the database may end up containing inconsistent values. Experienced developers may *wonder* whether they should open transactions or not, even when this doesn't matter a lot.
With GRDB 3, use `read` when you need to read values. It's impossible to write within a `read` block, which means that you can be sure that no unwanted side effect can happen.
When you need to write, use `write`: your database changes are automatically wrapped in a transaction, with the guarantee that all changes are written to disk, or, should any error happen, none at all.
Of course, precise transaction handling sometimes matter. Check the updated [Transactions and Savepoints] chapter.
## If You Use Database Pools
With GRDB 2, you used to access the database through the `read`, `write` or `writeInTransaction` [DatabasePool] methods:
```swift
// GRDB 2
let players = try dbPool.read { db in
try Player.fetchAll(db)
}
try dbPool.write { db in
try player.updateChanges(db)
}
var balance: Amount! = nil
try dbPool.writeInTransaction { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
balance = try sourceAccount.fetchBalance(db)
return .commit
}
```
In GRDB 3, the `write` method has changed: it now automatically wraps your database changes in a transaction, which means that the last block can be rewritten as below:
```swift
// GRDB 3
let balance = try dbPool.write { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
return try sourceAccount.fetchBalance(db)
}
```
Side effect: you can no longer open explicit transactions inside a `write` block:
```swift
// GRDB 2: OK
// GRDB 3: SQLite error 1 with statement `BEGIN DEFERRED TRANSACTION`:
// cannot start a transaction within a transaction
try dbPool.write { db in
try db.inTransaction { ... }
}
```
When precise transaction handling is needed, check the updated [Transactions and Savepoints] chapter.
The purpose of this change is to prevent an easy misuse of database pools in previous GRDB versions. Unless writes were wrapped inside an explicit transactions, concurrent reads could see an inconsistent state of the database:
```swift
// GRDB 2: unsafe
// GRDB 3: safe
try dbPool.write { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
}
```
Since `write` now wraps your changes in a transaction, you have the guarantee that concurrent reads can't see them until they are all written to disk.
## If You Use Database Snapshots
With GRDB 2, you used to create [database snapshots] with the `makeSnaphot` [DatabasePool] method. For example:
```swift
// GRDB 2
let snapshot: DatabaseSnapshot = try dbPool.write { db in
try Player.deleteAll()
return dbPool.makeSnapshot()
}
// Guaranteed to be zero
let count = try snapshot.read { db in
try Player.fetchCount(db)
}
```
GRDB 3 will crash the above code on the `makeSnapshot()` line, with a fatal error: "makeSnapshot() must not be called from inside a transaction."
To avoid this error, you will need [precise transaction handling]:
```swift
// GRDB 3
let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in
try Player.deleteAll()
return dbPool.makeSnapshot()
}
```
## If You Use Record Types
Record types that adopt the former TableMapping protocol, renamed TableRecord, used to declare their table name:
```swift
// GRDB 2
struct Place: TableMapping {
static let databaseTableName = "place"
}
print(Place.databaseTableName) // print "place"
```
With GRDB 3, the `databaseTableName` property gets a default implementation:
```swift
// GRDB 3
struct Place: TableRecord { }
print(Place.databaseTableName) // print "place"
```
That default name follows the [Database Schema Recommendations]: it is singular, camel-cased, and looks like a Swift identifier:
- Place: `place`
- Country: `country`
- PostalAddress: `postalAddress`
- HTTPRequest: `httpRequest`
- TOEFL: `toefl`
When you subclass the Record class, the Swift compiler won't let you profit from this default name: you have to keep on providing an explicit table name:
```swift
// GRDB 2 and GRDB 3
class Place: Record {
override var databaseTableName: String {
return "place"
}
}
```
## If You Use Custom Requests
[Custom requests] let you escape the limitations of the [query interface], when it can not generate the requests you need.
You may, for example, use `SQLRequest`:
```swift
// GRDB 2
extension Player {
static func filter(color: Color) -> AnyTypedRequest<Player> {
let sql = "SELECT * FROM players WHERE color = ?"
let request = SQLRequest(sql, arguments: [color])
return request.asRequest(of: Player.self)
}
}
let players = try Player.filter(color: .red).fetchAll(db)
```
The `AnyTypedRequest` type is no longer available, and `SQLRequest` is now a generic type:
```swift
// GRDB 3
extension Player {
static func filter(color: Color) -> SQLRequest<Player> {
let sql = "SELECT * FROM players WHERE color = ?"
return SQLRequest(sql, arguments: [color])
}
}
let players = try Player.filter(color: .red).fetchAll(db)
```
See the updated [Custom Requests](../README.md#custom-requests) chapter for more information.
## If You Use RxGRDB
Some RxGRDB APIs have slighly changed. Did you track multiple requests at the same time with "fetch tokens"?
```swift
// GRDB 2
dbQueue.rx
.fetchTokens(in: [request, ...])
.mapFetch { db in try fetchResult(db) }
.subscribe(...)
```
Now you'll write instead:
```swift
// GRDB 3
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.
GRDB 3.6 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition.
For example:
```swift
// GRDB 2: Track a team and its players
let teamId = 1
let teamRequest = Team.filter(key: teamId)
let playersRequest = Player.filter(teamId: teamId)
dbQueue.rx
.fetchTokens(in: [teamRequest, playersRequest])
.mapFetch { db -> TeamInfo? in
guard let team = try teamRequest.fetchOne(db) else {
return nil
}
let players = try playersRequest.fetchAll(db)
return TeamInfo(team: team, players: players)
}
.subscribe(onNext: { teamInfo: TeamInfo? in
...
})
// GRDB 3: Track a team and its players
struct TeamInfoRequest: DatabaseRegionConvertible { ... }
let request = TeamInfoRequest(teamId: 1)
ValueObservation.tracking(request, fetch: { try request.fetchOne($0) })
.rx
.fetch(in: dbQueue)
.subscribe(onNext: { teamInfo: TeamInfo? in
...
})
```
## Notable Documentation Updates
If you have time, you may dig deeper in GRDB 3 with those updated documentation chapter:
- [Database Queues](../README.md#database-queues): focus on the new `read` and `write` methods.
- [Transactions and Savepoints](../README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature.
- [ScopeAdapter](../README.md#scopeadapter): do you use row adapters? If so, have a look.
- [Examples of Record Definitions](../README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass).
- [SQL Operators](../README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`.
- [Custom Requests](../README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter.
- [Migrations](../README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests).
[How To Upgrade]: #how-to-upgrade
[Database Schema Recommendations]: #database-schema-recommendations
[Record Protocols Renaming]: #record-protocols-renaming
[Columns Definition]: #columns-definition
[Swift 4.1 Required]: #swift-41-required
[iOS 8 Sunsetting]: #ios-8-sunsetting
[If You Use Database Queues]: #if-you-use-database-queues
[If You Use Database Pools]: #if-you-use-database-pools
[If You Use Database Snapshots]: #if-you-use-database-snapshots
[If You Use Record Types]: #if-you-use-record-types
[If You Use Custom Requests]: #if-you-use-custom-requests
[If You Use RxGRDB]: #if-you-use-rxgrdb
[Notable Documentation Updates]: #notable-documentation-updates
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[Associations]: AssociationsBasics.md
[DatabaseMigrator]: ../README.md#migrations
[database observation tools]: ../README.md#database-changes-observation
[Transactions and Savepoints]: ../README.md#transactions-and-savepoints
[precise transaction handling]: ../README.md#transactions-and-savepoints
[DatabaseQueue]: ../README.md#database-queues
[DatabasePool]: ../README.md#database-pools
[database snapshots]: ../README.md#database-snapshots
[FMDB]: http://github.com/ccgus/fmdb
[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/GRDB.swift#the-databaseregionconvertible-protocol
[conditional conformances]: https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md
@@ -0,0 +1,350 @@
Good Practices for Designing Record Types
=========================================
This guide aims at helping you leverage the best of GRDB [records] and [associations].
Since GRDB sits right between low-level libraries like SQLite itself or [FMDB], and high-level ORM like [Core Data] or [Realm], you may face questions when designing the model layer of your application.
To support this guide, we'll design a simply library application that lets the user crawl through books and their authors.
- [Trust SQLite More Than Yourself]
- [Record Types are Responsible for Their Tables]
- [Compose Records]
- [Fetch In Time]
- [Observe the Database and Refetch when Needed]
## Trust SQLite More Than Yourself
SQLite is a robust database. Even if you don't know it well, and aren't familiar with the SQL language, you are able to take profit from its solid foundation. It is very difficult to corrupt an SQLite database file. And it can make sure that only valid information is persisted on disk.
This is important because we developers write bugs, and some of them will ship in the wild, affecting your application users. But thanks to SQLite, those bugs will be unable to corrupt your precious users' data. All it takes is a robust **database schema**.
For example, if we were to define a [migration] that sets up our library database, made of books and their authors, we could write:
```swift
var migrator = DatabaseMigrator()
migrator.registerMigration("createLibrary") { db in
try db.create(table: "author") { t in // (1)
t.autoIncrementedPrimaryKey("id") // (2)
t.column("name", .text).notNull() // (3)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text).notNull() // (4)
t.column("authorId", .integer) // (5)
.notNull() // (6)
.indexed() // (7)
.references("author", onDelete: .cascade) // (8)
}
}
try migrator.migrate(dbQueue)
```
1. Our database table names follow the GRDB 3 recommendation: generally speaking they should be singular, and camel-cased. Make them look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
2. Each author has a unique id.
3. An author must have a name.
4. A book must have a title.
5. The `book.authorId` column is used to link a book to the author it belongs to.
6. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
7. The `book.authorId` column is indexed in order to ease the selection of an author's books.
8. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
Thanks to this database schema, you can be confident so no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc.
> :bulb: **Tip**: Don't look at your local SQLite database as you look at the JSON you load from a remote server. You can't control the JSON, its format and content: your application must defend itself against wacky servers. But you can control the database. Put the database on your side, make it trustable. Learn about relational databases, and how they can help you guarantee the quality of your application data. Put as much energy as you can in the proper definition of your database schema.
>
> :bulb: **Tip**: Plan early for future versions of your application, and use [migrations].
>
> :bulb: **Tip**: In the definition of your migrations, define tables and their columns with **strings**:
>
> ```swift
> migrator.registerMigration("createLibrary") { db in
> // RECOMMENDED
> try db.create(table: "author") { t in
> t.autoIncrementedPrimaryKey("id")
> ...
> }
>
> // NOT RECOMMENDED
> try db.create(table: Author.databaseTableName) { t in
> t.autoIncrementedPrimaryKey(Author.Columns.id.name)
> ...
> }
> }
> ```
>
> By using strings, you make sure that you will not have to change the Swift code of your migrations in the future. Even if author columns eventually change. Even if the Author type eventually gets replaced with another type. Even when your startup eventually pivots and starts selling pet food. A good migration that never changes is easy to test once and for good. A good migration that never changes will run smoothly on all devices in the wild, even if a user upgrades straight from version 1.0 to version 5.0 of your application.
>
> So make sure that migrations don't use application types and values: migrations should talk to the database, only to the database, and use the database language: **strings**.
## Record Types are Responsible for Their Tables
Define one record type per database table.
In this sample code, we'll use codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
```swift
struct Author: Codable, FetchableRecord, MutablePersistableRecord {
var id: Int64?
var name: String
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
struct Book: Codable, FetchableRecord, MutablePersistableRecord {
var id: Int64?
var authorId: Int64
var title: String
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
```
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`. See [record protocols] for more information.
> :bulb: **Tip**: When a column of a database table can't be NULL, store it in a non-optional property of your record type. On the other side, when the database may contain NULL, define an optional property.
>
> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(with:for:)` method:
>
> ```swift
> var author = Author(id: nil, name: "Hermann Melville")
> try author.insert(db)
> print(author.id) // Some non-nil id
> ```
Since `Author` and `Book` can insert, update, and delete rows in the `author` and `book` database tables, they are *responsible for modifying those database tables*.
Applying the **[Single Responsibility Principle]** has a consequence: don't even try to have an author responsible for its books. Don't add a `books: [Book]` property in Author. Don't let Author write in the `book` table. When a new fellow coworker joins your team and asks you "who is saving books in the database?", you don't want to answer "it depends." You want to confidently answer: "the Book type".
> :bulb: **Tip**: Make sure each record type deals with one database table, and only one database table.
## Compose Records
Now that we have two types for authors and books, we'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
GRDB can help you do this with [associations]. In our case, each author **has many** books, and each book **belongs to** its author. Here is how you define those associations, along with their companion properties:
```swift
extension Author {
static let books = hasMany(Book.self)
var books: QueryInterfaceRequest<Book> {
return request(for: Author.books)
}
}
extension Book {
static let author = belongsTo(Author.self)
var author: QueryInterfaceRequest<Author> {
return request(for: Book.author)
}
}
```
Thanks to this setup, you can fetch associated records:
```swift
// Fetch an author and its books
struct AuthorInfo {
var author: Author
var books: [Book]
}
let authorInfo: AuthorInfo? = try dbQueue.read { db in
guard let author = try Author.fetchOne(db, key: 123) else { return nil }
let books = try author.books.fetchAll(db)
return AuthorInfo(author: author, books: books)
}
// Fetch all authorships
struct Authorship: Decodable, FetchableRecord {
var book: Book
var author: Author
}
let authorships: [Authorship] = try dbQueue.read { db in
let request = Book.including(required: Book.author)
return try Authorship.fetchAll(db, request)
}
```
The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they?
That is because other ORMs perform lazy loading:
```ruby
# Ruby's Active Record
author = Author.find(123) # fetch author
books = author.books # lazily fetches books on demand
```
GRDB does not perform lazy loading. Lazy loading either requires record to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation] against concurrent changes. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer. This is why GRDB has removed lazy loading from the list of desirable features. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information.
The consequence is that each part of your application will load the data it needs, at the moment it needs it, as below:
1. Prepare the application screen that lists all authors:
```swift
let authors: [Author] = dbQueue.read { db in
Author.order(Colum("name")).fetchAll(db)
}
```
2. Prepare the application screen that displays an author and her books:
```swift
struct AuthorInfo {
var author: Author
var books: [Book]
}
let authorId = 123
let authorInfo: AuthorInfo? = try dbQueue.read { db in
guard let author = try Author.fetchOne(db, key: authorId) else { return nil }
let books = try author.books.fetchAll(db)
return AuthorInfo(author: author, books: books)
}
```
3. Prepare the application screen that displays a book information:
```swift
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var author: Author
}
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
let request = Book
.filter(key: bookId)
.including(required: Book.author)
return try BookInfo.fetchOne(db, request)
}
```
> :bulb: **Tip**: Identify the various **graph of objects** needed by the various parts of your application. Design them independently, by composing the basic record types. Fetch the data your application needs, at the moment it needs it, no more, no less.
## Fetch In Time
> :bulb: **Tip**: Make sure you fetch all the data your application needs in a **single database read**.
```swift
// NOT RECOMMENDED
let bookId = 123
// Two fetches not grouped in a single `read` block:
if let book = databaseManager.getBook(id: bookId) {
let author = databaseManager.getAuthor(id: book.authorId)!
// use book and author
}
// RECOMMENDED (without associations)
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
// All fetches are grouped in a single `read` block:
if let book = try Book.fetchOne(db, key: bookId) {
let author = try Author.fetchOne(db, key: book.authorId)!
return BookInfo(book: book, author: author)
} else {}
return nil
}
}
if let bookInfo = bookInfo {
// use bookInfo
}
// RECOMMENDED (with associations)
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
// All fetches are grouped in a single `read` block:
let request = Book
.filter(key: bookId)
.including(required: Book.author)
return try BookInfo.fetchOne(db, request)
}
if let bookInfo = bookInfo {
// use bookInfo
}
```
This tip is paramount, and deserves an explanation because too many database libraries out there tend to completely disregard multi-threading gotchas.
When you do not fetch your data in a single database access block, other threads of your application may modify the database in the background, and have you fetch inconsistent data. This leads to hard-to-reproduce bugs, from funny values on screen to data loss.
Wrapping all fetches in a `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony:
```ruby
# Ruby's Active Record
if book = Book.find(123) # fetch book
author = book.author # fetch author
# use book and author
end
```
The problem is that it is very hard to guarantee that you will surely fetch an author after you have fetched a book, despite the constraints of the database schema. One has to perform subsequent fetches in the proper [isolation] level, so that eventual concurrent writes that modify the database are unable to mess with subsequent requests.
This isolation can be achieved with record management, as in [Core Data] or [Realm], that target long-running multi-threaded applications. On the other side, most web-oriented ORMs rely on short-lived database transactions, so that each HTTP request can be processed independently of others.
GRDB is not a managed ORM. It thus has to use the same isolation techniques as web-oriented ORMs. But unlike web-oriented ORMs, GRDB can't provide implicit isolation: the application must decide when it wants to safely read information in the database, and this decision is made explicit with database access methods such as `dbQueue.read`.
Do not overlook this advice, or your application will exhibit weird concurrency-related bugs. Read the [Concurrency Guide] for detailed information, and the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more rationale.
## Observe the Database and Refetch when Needed
We have seen above that the Author and Book record types are [responsible](#record-types-are-responsible-for-their-tables) for their own dedicated database tables. Later we [composed](#compose-records) them into more complex types such as `BookInfo` or `AuthorInfo`. We advised the application to fetch database information [right on time](#fetch-in-time), when it needs to process it.
Fetched information eventually becomes obsoleted, as the application modifies the database content.
It is up to the application to decide how long it should keep fetched information in memory. Very often though, the application will want to keep memory information synchronized with the database content.
This synchronization is not automatic with GRDB: records do not "auto-update". That is because applications do not always want this feature, and because it is difficult to write correct multi-threaded applications when values can change in unexpected ways.
Instead, have a look at [Database Observation]:
> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes.
>
> :bulb: **Tip**: [FetchedRecordsController] performs automated tracking of database changes, and can animate the cells of a table or collection view.
>
> :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.
[records]: ../README.md#records
[associations]: AssociationsBasics.md
[FMDB]: https://github.com/ccgus/fmdb
[Core Data]: https://developer.apple.com/documentation/coredata
[Realm]: https://realm.io
[Active Record]: http://guides.rubyonrails.org/active_record_basics.html
[Django]: https://docs.djangoproject.com/en/2.0/topics/db/
[record protocols]: ../README.md#record-protocols-overview
[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns
[Single Responsibility Principle]: https://en.wikipedia.org/wiki/Single_responsibility_principle
[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
[Why Adopt GRDB?]: WhyAdoptGRDB.md
[isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
[migrations]: ../README.md#migrations
[migration]: ../README.md#migrations
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
[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
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
[Record Types are Responsible for Their Tables]: #record-types-are-responsible-for-their-tables
[Compose Records]: #compose-records
[Fetch In Time]: #fetch-in-time
[Observe the Database and Refetch when Needed]: #observe-the-database-and-refetch-when-needed
@@ -0,0 +1,154 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="468px" height="145px" viewBox="0 0 468 145" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
<title>AmbiguousForeignKeys</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="200" height="127" rx="10"></rect>
<filter x="-7.2%" y="-9.1%" width="114.5%" height="122.8%" 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="200" height="103" rx="10"></rect>
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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>
<circle id="path-8" cx="3.5" cy="28.5" r="3.5"></circle>
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-9"></path>
<circle id="path-10" cx="3.5" cy="47.5" r="3.5"></circle>
</defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="AmbiguousForeignKeys" transform="translate(9.000000, 6.000000)">
<g id="Table">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="128" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">id</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">authorId</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 79.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">translatorId</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 103.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">title</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="book" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="82.9443359" y="21">book</tspan>
</text>
</g>
<g id="Table-Copy-2" transform="translate(250.000000, 0.000000)">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">id</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">name</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 79.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="person" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="76.2109375" y="21">person</tspan>
</text>
</g>
<g id="Group-3" transform="translate(197.000000, 39.000000)">
<g id="Oval">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-8"></use>
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="28.5" r="4"></circle>
</g>
<g id="Path-3">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-9"></use>
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
</g>
<path d="M2.5,28.5 C2.5,28.5 2.5,28.5 16.5,28.5 C30.5,28.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
</g>
<g id="Group-3" transform="translate(197.000000, 44.000000)">
<g id="Oval">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-10"></use>
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="47.5" r="4"></circle>
</g>
<path d="M2.5,47.5 C2.5,47.5 2.5,47.5 16.5,47.5 C30.5,47.5 27.5,0.5 40.5,0.5 C49.1666667,0.5 53.5,0.5 53.5,0.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 12 KiB

@@ -0,0 +1,133 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="468px" height="121px" viewBox="0 0 468 121" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
<title>BelongsToSchema</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="200" height="103" rx="10"></rect>
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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="200" height="103" rx="10"></rect>
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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>
<circle id="path-8" cx="200.5" cy="67.5" r="3.5"></circle>
<path d="M254.40688,43.6237841 L247.481919,39.8150553 C246.997998,39.5488989 246.38994,39.7254318 246.123784,40.2093525 C246.042579,40.3569975 246,40.5227683 246,40.6912712 L246,48.3087288 C246,48.8610135 246.447715,49.3087288 247,49.3087288 C247.168503,49.3087288 247.334274,49.2661494 247.481919,49.1849447 L254.40688,45.3762159 C254.890801,45.1100595 255.067334,44.5020019 254.801177,44.0180813 C254.709789,43.8519215 254.57304,43.7151719 254.40688,43.6237841 Z" id="path-9"></path>
</defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="BelongsToSchema" transform="translate(9.000000, 6.000000)">
<g id="Table">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">id</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">authorId</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 79.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">title</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="book" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="82.9443359" y="21">book</tspan>
</text>
</g>
<g id="Table-Copy-2" transform="translate(250.000000, 0.000000)">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">id</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">name</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 79.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="author" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="77.3867188" y="21">author</tspan>
</text>
</g>
<g id="Oval">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-8"></use>
<circle stroke="#FFFFFF" stroke-width="1" cx="200.5" cy="67.5" r="4"></circle>
</g>
<g id="Path-3">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-9"></use>
<path stroke="#FFFFFF" stroke-width="1" d="M254.64784,43.1856761 C254.897079,43.3227579 255.102204,43.5278823 255.239285,43.7771219 C255.63852,44.5030029 255.373721,45.4150893 254.64784,45.8143239 L247.722878,49.6230526 C247.501411,49.7448598 247.252754,49.8087288 247,49.8087288 C246.171573,49.8087288 245.5,49.1371559 245.5,48.3087288 L245.5,40.6912712 C245.5,40.4385168 245.563869,40.1898606 245.685676,39.9683931 C246.084911,39.2425121 246.996997,38.9777128 247.722878,39.3769474 L254.64784,43.1856761 Z"></path>
</g>
<path d="M199.5,67.5 C199.5,67.5 199.5,67.5 213.5,67.5 C227.5,67.5 224.5,44.5 237.5,44.5 C246.166667,44.5 250.5,44.5 250.5,44.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 10 KiB

@@ -0,0 +1,135 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="468px" height="121px" viewBox="0 0 468 121" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
<title>HasManySchema</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="200" height="103" rx="10"></rect>
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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="200" height="103" rx="10"></rect>
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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>
<circle id="path-8" cx="3.5" cy="28.5" r="3.5"></circle>
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-9"></path>
</defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="HasManySchema" transform="translate(9.000000, 6.000000)">
<g id="Table" transform="translate(250.000000, 0.000000)">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">id</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">authorId</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 79.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">title</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="book" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="82.9443359" y="21">book</tspan>
</text>
</g>
<g id="Table-Copy-2">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">id</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">name</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 79.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="author" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="77.3867188" y="21">author</tspan>
</text>
</g>
<g id="Group" transform="translate(224.000000, 55.000000) scale(-1, 1) translate(-224.000000, -55.000000) translate(195.000000, 39.000000)">
<g id="Oval">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-8"></use>
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="28.5" r="4"></circle>
</g>
<g id="Path-3">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-9"></use>
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
</g>
<path d="M2.5,28.5 C2.5,28.5 2.5,28.5 16.5,28.5 C30.5,28.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 10 KiB

@@ -0,0 +1,185 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="468px" height="200px" viewBox="0 0 468 200" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
<title>HasManyThroughSchema</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="200" height="103" rx="10"></rect>
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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="200" height="79" rx="10"></rect>
<filter x="-7.2%" y="-14.6%" width="114.5%" height="136.7%" 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="200" height="79" rx="10"></rect>
<filter x="-7.2%" y="-14.6%" width="114.5%" height="136.7%" 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>
<circle id="path-11" cx="3.5" cy="44.5" r="3.5"></circle>
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-12"></path>
<circle id="path-13" cx="3.5" cy="3.5" r="3.5"></circle>
<path d="M57.4068802,42.6237841 L50.4819187,38.8150553 C49.9979981,38.5488989 49.3899405,38.7254318 49.1237841,39.2093525 C49.0425794,39.3569975 49,39.5227683 49,39.6912712 L49,47.3087288 C49,47.8610135 49.4477153,48.3087288 50,48.3087288 C50.168503,48.3087288 50.3342738,48.2661494 50.4819187,48.1849447 L57.4068802,44.3762159 C57.8908008,44.1100595 58.0673337,43.5020019 57.8011773,43.0180813 C57.7097895,42.8519215 57.5730399,42.7151719 57.4068802,42.6237841 Z" id="path-14"></path>
</defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="HasManyThroughSchema" transform="translate(9.000000, 6.000000)">
<g id="Table" transform="translate(250.000000, 40.000000)">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">countryCode</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">citizenId</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 79.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">issueDate</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">date</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="passport" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="69.3613281" y="21">passport</tspan>
</text>
</g>
<g id="Table-Copy-2">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="80" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">code</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">name</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="country" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="73.3740234" y="21">country</tspan>
</text>
</g>
<g id="Table-Copy-2" transform="translate(0.000000, 103.000000)">
<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="#005CC5" fill-rule="evenodd" xlink:href="#path-8"></use>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-8"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="80" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-9)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">id</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-9)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">name</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="citizen" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="77.1782227" y="21">citizen</tspan>
</text>
</g>
<g id="Group" transform="translate(224.000000, 63.000000) scale(-1, 1) translate(-224.000000, -63.000000) translate(195.000000, 39.000000)">
<g id="Oval">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-11"></use>
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="44.5" r="4"></circle>
</g>
<g id="Path-3">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-12"></use>
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
</g>
<path d="M2.5,44.5 C2.5,44.5 2.5,44.5 16.5,44.5 C30.5,44.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
</g>
<g id="Group" transform="translate(224.000000, 128.500000) scale(-1, 1) translate(-224.000000, -128.500000) translate(195.000000, 104.000000)">
<g id="Oval">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-13"></use>
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="3.5" r="4"></circle>
</g>
<g id="Path-3">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-14"></use>
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,42.1856761 C57.8970791,42.3227579 58.1022035,42.5278823 58.2392853,42.7771219 C58.6385198,43.5030029 58.3737206,44.4150893 57.6478395,44.8143239 L50.7228781,48.6230526 C50.5014107,48.7448598 50.2527545,48.8087288 50,48.8087288 C49.1715729,48.8087288 48.5,48.1371559 48.5,47.3087288 L48.5,39.6912712 C48.5,39.4385168 48.563869,39.1898606 48.6856761,38.9683931 C49.0849107,38.2425121 49.9969971,37.9777128 50.7228781,38.3769474 L57.6478395,42.1856761 Z"></path>
</g>
<path d="M2.5,3.5 C2.5,3.5 2.5,3.5 16.5,3.5 C30.5,3.5 27.5,43.5 40.5,43.5 C49.1666667,43.5 53.5,43.5 53.5,43.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 15 KiB

@@ -0,0 +1,153 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="468px" height="145px" viewBox="0 0 468 145" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
<title>HasOneSchema</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="200" height="127" rx="10"></rect>
<filter x="-7.2%" y="-9.1%" width="114.5%" height="122.8%" 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="200" height="127" rx="10"></rect>
<filter x="-7.2%" y="-9.1%" width="114.5%" height="122.8%" 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>
<circle id="path-8" cx="3.5" cy="28.5" r="3.5"></circle>
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-9"></path>
</defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="HasOneSchema" transform="translate(9.000000, 6.000000)">
<g id="Table" transform="translate(250.000000, 0.000000)">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="128" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">id</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">countryCode</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 79.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">population</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 103.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">density</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">double</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="demographics" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="50.894043" y="21">demographics</tspan>
</text>
</g>
<g id="Table-Copy-2">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="128" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">code</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">name</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 79.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 103.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="country" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="73.3740234" y="21">country</tspan>
</text>
</g>
<g id="Group" transform="translate(224.000000, 55.000000) scale(-1, 1) translate(-224.000000, -55.000000) translate(195.000000, 39.000000)">
<g id="Oval">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-8"></use>
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="28.5" r="4"></circle>
</g>
<g id="Path-3">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-9"></use>
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
</g>
<path d="M2.5,28.5 C2.5,28.5 2.5,28.5 16.5,28.5 C30.5,28.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 12 KiB

@@ -0,0 +1,198 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="468px" height="247px" viewBox="0 0 468 247" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
<title>HasOneThroughSchema</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="200" height="79" rx="10"></rect>
<filter x="-7.2%" y="-14.6%" width="114.5%" height="136.7%" 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="200" height="103" rx="10"></rect>
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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="200" height="102" rx="10"></rect>
<filter x="-7.2%" y="-11.3%" width="114.5%" height="128.4%" 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>
<circle id="path-11" cx="3.5" cy="56.5" r="3.5"></circle>
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-12"></path>
<circle id="path-13" cx="3.5" cy="3.5" r="3.5"></circle>
<path d="M57.4068802,54.6237841 L50.4819187,50.8150553 C49.9979981,50.5488989 49.3899405,50.7254318 49.1237841,51.2093525 C49.0425794,51.3569975 49,51.5227683 49,51.6912712 L49,59.3087288 C49,59.8610135 49.4477153,60.3087288 50,60.3087288 C50.168503,60.3087288 50.3342738,60.2661494 50.4819187,60.1849447 L57.4068802,56.3762159 C57.8908008,56.1100595 58.0673337,55.5020019 57.8011773,55.0180813 C57.7097895,54.8519215 57.5730399,54.7151719 57.4068802,54.6237841 Z" id="path-14"></path>
</defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="HasOneThroughSchema" transform="translate(9.000000, 6.000000)">
<g id="Table" transform="translate(250.000000, 75.000000)">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="80" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">id</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">name</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="library" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="77.800293" y="21">library</tspan>
</text>
</g>
<g id="Group-2">
<g id="Table-Copy-2">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">id</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">libraryId</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-6)">
<g transform="translate(0.000000, 79.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">title</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="book" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="82.9443359" y="21">book</tspan>
</text>
</g>
<g id="Table-Copy-2" transform="translate(0.000000, 127.000000)">
<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="#005CC5" fill-rule="evenodd" xlink:href="#path-8"></use>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-8"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="103" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-9)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">libraryId</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-9)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">street</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-9)">
<g transform="translate(0.000000, 78.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">city</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="address" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="72.4545898" y="21">address</tspan>
</text>
</g>
</g>
<g id="Group" transform="translate(226.000000, 93.500000) scale(1, -1) translate(-226.000000, -93.500000) translate(197.000000, 63.000000)">
<g id="Oval">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-11"></use>
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="56.5" r="4"></circle>
</g>
<g id="Path-3">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-12"></use>
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
</g>
<path d="M2.5,56.5 C2.5,56.5 2.5,56.5 16.5,56.5 C30.5,56.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
</g>
<g id="Group" transform="translate(226.000000, 143.500000) scale(1, -1) translate(-226.000000, -143.500000) translate(197.000000, 113.000000)">
<g id="Oval">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-13"></use>
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="3.5" r="4"></circle>
</g>
<g id="Path-3">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-14"></use>
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,54.1856761 C57.8970791,54.3227579 58.1022035,54.5278823 58.2392853,54.7771219 C58.6385198,55.5030029 58.3737206,56.4150893 57.6478395,56.8143239 L50.7228781,60.6230526 C50.5014107,60.7448598 50.2527545,60.8087288 50,60.8087288 C49.1715729,60.8087288 48.5,60.1371559 48.5,59.3087288 L48.5,51.6912712 C48.5,51.4385168 48.563869,51.1898606 48.6856761,50.9683931 C49.0849107,50.2425121 49.9969971,49.9777128 50.7228781,50.3769474 L57.6478395,54.1856761 Z"></path>
</g>
<path d="M2.5,3.5 C2.5,3.5 2.5,3.5 16.5,3.5 C30.5,3.5 27.5,55.5 40.5,55.5 C49.1666667,55.5 53.5,55.5 53.5,55.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 16 KiB

@@ -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
@@ -0,0 +1,91 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="233px" height="121px" viewBox="0 0 233 121" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
<title>RecursiveSchema</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="200" height="103" rx="10"></rect>
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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>
<circle id="path-5" cx="22.5" cy="28.5" r="3.5"></circle>
<path d="M27.4068802,4.62378409 L20.4819187,0.815055312 C19.9979981,0.548898936 19.3899405,0.725431787 19.1237841,1.20935247 C19.0425794,1.35699745 19,1.52276825 19,1.69127122 L19,9.30872878 C19,9.86101353 19.4477153,10.3087288 20,10.3087288 C20.168503,10.3087288 20.3342738,10.2661494 20.4819187,10.1849447 L27.4068802,6.37621591 C27.8908008,6.11005953 28.0673337,5.50200193 27.8011773,5.01808125 C27.7097895,4.85192153 27.5730399,4.71517193 27.4068802,4.62378409 Z" id="path-6"></path>
</defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="RecursiveSchema" transform="translate(9.000000, 6.000000)">
<g id="Table-Copy-2">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 31.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">id</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 55.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">managerId</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">integer</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 79.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
<tspan x="10" y="17" fill="#000000">name</tspan>
</text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
<tspan x="110" y="17" fill="#000000">text</tspan>
</text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<g id="Field" mask="url(#mask-3)">
<g transform="translate(0.000000, 79.000000)">
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
</g>
</g>
<text id="employee" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="66.8730469" y="21">employee</tspan>
</text>
</g>
<g id="Group" transform="translate(209.000000, 55.000000) scale(-1, 1) translate(-209.000000, -55.000000) translate(195.000000, 39.000000)">
<g id="Oval">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-5"></use>
<circle stroke="#FFFFFF" stroke-width="1" cx="22.5" cy="28.5" r="4"></circle>
</g>
<g id="Path-3">
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-6"></use>
<path stroke="#FFFFFF" stroke-width="1" d="M27.6478395,4.18567614 C27.8970791,4.3227579 28.1022035,4.5278823 28.2392853,4.77712188 C28.6385198,5.5030029 28.3737206,6.4150893 27.6478395,6.81432386 L20.7228781,10.6230526 C20.5014107,10.7448598 20.2527545,10.8087288 20,10.8087288 C19.1715729,10.8087288 18.5,10.1371559 18.5,9.30872878 L18.5,1.69127122 C18.5,1.43851677 18.563869,1.18986057 18.6856761,0.968393096 C19.0849107,0.242512071 19.9969971,-0.0222872062 20.7228781,0.376947358 L27.6478395,4.18567614 Z"></path>
</g>
<path d="M23.5,28.5 C23.5,28.5 19.1666667,28.5 10.5,28.5 C-2.5,28.5 -2.5,5.5 10.5,5.5 C19.1666667,5.5 23.5,5.5 23.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 7.1 KiB

@@ -0,0 +1,110 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="292px" height="166px" viewBox="0 0 292 166" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
<title>TreeOfAssociationKeys</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="119" height="28" rx="10"></rect>
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" 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="119" height="28" rx="10"></rect>
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.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="119" height="28" rx="10"></rect>
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" 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="119" height="28" rx="10"></rect>
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" 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>
</defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="TreeOfAssociationKeys" transform="translate(9.000000, 6.000000)">
<path d="M60,78 L60,114" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
<path id="Line-decoration-1" d="M57,103.2 L60,114 L63,103.2" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M139,14 L77,57" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
<path id="Line-decoration-1" d="M84.1648227,48.3799469 L77,57 L87.5842165,53.3102356" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M140,14 L206,57" id="Line-Copy" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
<path id="Line-Copy-decoration-1" d="M195.313438,53.61808 L206,57 L198.58872,48.5909017" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
<g id="Table-Copy-2" transform="translate(80.000000, 0.000000)">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
</g>
<text id="root" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="45.390625" y="19">root</tspan>
</text>
</g>
<g id="Table-Copy-3" transform="translate(0.000000, 62.000000)">
<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="#417505" fill-rule="evenodd" xlink:href="#path-5"></use>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
</g>
<text id="&quot;author&quot;" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="30.2421875" y="19">"author"</tspan>
</text>
</g>
<g id="Table-Copy-5" transform="translate(155.000000, 62.000000)">
<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="#9013FE" fill-rule="evenodd" xlink:href="#path-8"></use>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-8"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
</g>
<text id="&quot;coverImage&quot;" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="12.8037109" y="19">"coverImage"</tspan>
</text>
</g>
<g id="Table-Copy-4" transform="translate(0.000000, 120.000000)">
<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="#D0021B" fill-rule="evenodd" xlink:href="#path-11"></use>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-11"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
</g>
<text id="&quot;country&quot;" mask="url(#mask-12)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="26.2294922" y="19">"country"</tspan>
</text>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 8.5 KiB

@@ -0,0 +1,130 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="421px" height="227px" viewBox="0 0 421 227" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
<title>TreeOfAssociationKeysMapping</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="119" height="28" rx="10"></rect>
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" 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="119" height="28" rx="10"></rect>
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.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="119" height="28" rx="10"></rect>
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" 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="119" height="28" rx="10"></rect>
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" 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>
</defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="TreeOfAssociationKeysMapping" transform="translate(0.000000, 6.000000)">
<g id="Group-4">
<path d="M83,36 L83,186" id="Line-Copy-2" stroke="#727272" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4,8"></path>
<path d="M159,96 L159,186" id="Line-Copy-3" stroke="#727272" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4,8"></path>
<path d="M246,156 L246,186" id="Line-Copy-4" stroke="#727272" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4,8"></path>
<path d="M352,96 L352,186" id="Line-Copy-5" stroke="#727272" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4,8"></path>
<path d="M85,14 L136,57" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
<path id="Line-decoration-1" d="M125.809367,52.3319166 L136,57 L129.676951,47.7447827" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M85,14 L292,57" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
<path id="Line-decoration-1" d="M280.815576,57.7407092 L292,57 L282.035901,51.8661193" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M156,72 L207,115" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
<path id="Line-decoration-1" d="M196.809367,110.331917 L207,115 L200.676951,105.744783" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
<g id="Table-Copy-6" transform="translate(23.000000, 0.000000)">
<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>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
</g>
<text id="root" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="45.390625" y="19">root</tspan>
</text>
</g>
<g id="Table-Copy-7" transform="translate(100.000000, 62.000000)">
<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="#417505" fill-rule="evenodd" xlink:href="#path-5"></use>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
</g>
<text id="&quot;author&quot;" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="30.2421875" y="19">"author"</tspan>
</text>
</g>
<g id="Table-Copy-8" transform="translate(293.000000, 62.000000)">
<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="#9013FE" fill-rule="evenodd" xlink:href="#path-8"></use>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-8"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
</g>
<text id="&quot;coverImage&quot;" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="12.8037109" y="19">"coverImage"</tspan>
</text>
</g>
<g id="Table-Copy-9" transform="translate(187.000000, 120.000000)">
<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="#D0021B" fill-rule="evenodd" xlink:href="#path-11"></use>
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-11"></use>
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
</g>
<text id="&quot;country&quot;" mask="url(#mask-12)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
<tspan x="26.2294922" y="19">"country"</tspan>
</text>
</g>
<g id="Group-5" transform="translate(0.000000, 191.000000)" font-family="Menlo-Regular, Menlo" font-size="14" font-weight="normal">
<text id="SELECT-book.*,-autho">
<tspan x="0" y="13" fill="#404040">SELECT </tspan>
<tspan x="59.0009766" y="13" fill="#4A90E2">book.*</tspan>
<tspan x="109.573242" y="13" fill="#404040">, </tspan>
<tspan x="126.430664" y="13" fill="#417505">author.*</tspan>
<tspan x="193.860352" y="13" fill="#404040">, </tspan>
<tspan x="210.717773" y="13" fill="#D0021B">country.*</tspan>
<tspan x="286.576172" y="13" fill="#404040">, </tspan>
<tspan x="303.433594" y="13" fill="#9013FE">coverImage.*</tspan>
<tspan x="404.578125" y="13" fill="#404040"></tspan>
<tspan x="0" y="29" fill="#404040">FROM …</tspan>
</text>
</g>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 10 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

@@ -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
+1 -1
View File
@@ -1 +1 @@
The main documentation is available in [README.md](../../../#documentation).
The main documentation is available in [README.md](../README.md#documentation).
+5 -3
View File
@@ -16,17 +16,19 @@ To release a new GRDB version:
- Makefile
- CHANGELOG.md
- Documentation/CustomSQLiteBuilds.md
- Documentation/ExtendingGRDB.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
- Push to the Swift4 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):
`make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb`
+78 -62
View File
@@ -10,7 +10,7 @@ We'll start with a few [core principles](#core-principles), so that you see wher
### It is generally easier to access a database through "record types".
This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow[nameColumn]`, doesn't it?
This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow["name"]`, doesn't it?
The reputation of "active records" and ORMs has been tarnished by the recent focus on immutability, memory safety, and functional idioms that comes with languages like Swift and Rust. Features of 1st-generation records such as auto-updating, uniquing, lazy loading of relations, etc. are now considered ill-advised, if not plain harmful because of the multi-threading headaches they cause.
@@ -37,9 +37,9 @@ GRDB puts all bets on SQLite, and focuses on front-end GUI applications.
This means that dealing with servers, MySQL, or PostgreSQL is out of scope. GRDB is not an alternative to IBM's [Swift-Kuery], Vapor's [Fluent], or Perfect's [StORM].
Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, changes tracking, database observation, multi-threading safety, table view animations, support for reactive streams...
Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, record comparison, database observation, multi-threading safety, table view animations, support for reactive streams...
Some will call GRDB "opinionated", or "bloated". Well, the bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face.
The bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face.
Since you don't have to take my words for granted, we'll now see how GRDB actually solves common problems that developers face with other database libraries.
@@ -51,7 +51,7 @@ What is the purpose of the above principles, if not providing solutions to diffi
### Allow any Swift struct or class to become a database record
Most libraries that provide record types want you to subclass a root class: NSManagedObject, Realm.Object, FCModel.
Most libraries that provide record types want you to subclass a root class: [NSManagedObject](https://developer.apple.com/documentation/coredata/nsmanagedobject), [Realm.Object](https://www.realm.io/docs/swift/latest), [FCModel](https://github.com/marcoarment/FCModel).
The main problem with those root classes is that they are classes. You can't define records from plain Swift structs, and leverage all advantages of Swift value types: immutability, multi-threading safety, etc.
@@ -65,28 +65,30 @@ struct Place {
}
```
By adopting the [RowConvertible] protocol, places can be loaded from SQL requests:
By adopting the [FetchableRecord] protocol, places can be loaded from SQL requests:
```swift
extension Place: RowConvertible { ... }
let places = try Place.fetchAll(db, "SELECT * FROM places") // [Place]
extension Place: FetchableRecord { ... }
let places = try Place.fetchAll(db, "SELECT * FROM place") // [Place]
```
Add the [TableMapping] protocol, and SQL requests are generated for you:
Add the [TableRecord] protocol, and SQL requests are generated for you:
```swift
extension Place: TableMapping { ... }
extension Place: TableRecord { ... }
let place = try Place.fetchOne(db, key: 1) // Place?
```
Add the [Persistable] protocol, and places know how to insert, update and delete themselves:
Add the [PersistableRecord] protocol, and places know how to insert, update and delete themselves:
```swift
extension Place: Persistable { ... }
extension Place: PersistableRecord { ... }
try place.delete(db)
```
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.
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.
### Allow database records to cross threads
@@ -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
@@ -129,25 +131,25 @@ First, notifications only come from database changes safely saved on disk. This
Next, you choose the dispatch queue on which notifications happen. It can be on the special "writer queue", which allows you to process changes before any other thread has any opportunity to perform further database modifications. But notifications can also happen on the queue of your choice (generally the main queue, by default, as in the example above). Of course, GRDB makes sure notifications happen in the same order as database transactions.
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, and even SQL triggers.
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, and even SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
### Non-blocking database reads
GRDB ships with two ways to access databases, [database queues](https://github.com/groue/GRDB.swift/blob/master/README.md#database-queues) and [pools](https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools).
GRDB ships with two ways to access databases, [database queues](../README.md#database-queues) and [pools](../README.md#database-pools).
Database queues look a lot like FMDB's [FMDatabaseQueue](https://github.com/ccgus/fmdb#using-fmdatabasequeue-and-thread-safety): they serialize database accesses in a serial dispatch queue. There is never more than one thread that is accessing the database. This means that a long running database transaction that happens in a background thread, such as the synchronization of your local database from a remote server, can block your UI. As long as the queue is busy, the main thread can't fetch the values it wants to display on screen.
[Database pools](https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
[Database pools](../README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
### Strong and clear multi-threading guarantees
I'd like to compare GRDB's handling of concurrency with other libraries. To be as clear as possible, we'll identity a few threats, or potential sources of bugs, and wonder if those are handled by the library, or left to the host application.
I'd like to compare GRDB's handling of concurrency with other libraries. To be as clear as possible, we'll identify a few threats, or potential sources of bugs, and wonder if those are handled by the library, or left to the host application.
The more threats are handled by the application, the more skilled and careful a developer has to be in order to avoid them.
- **Concurrent writes**: Two threads want to write in the database as the same time. SQLite does not allow that.
- **Concurrent writes**: Two threads want to write in the database at the same time. SQLite does not allow that.
- **Isolation troubles**: As two database queries run one after the other, a concurrent thread sneaks in and modifies the database in between. The two queries can thus perform inconsistent fetches or updates, unless they are properly isolated. Lack of isolation may display funny values on the screen, trigger a relational constraint error, or silently corrupt the database content.
- **Conflicts**: The same piece of data is both edited by the application user, and refreshed from a network operation. What will eventually be stored in the database? Can any conflict be noticed?
- **Blocked UI**: Can it happen that the UI is blocked because the main thread has to wait for a background thread to release a lock on the database?
@@ -162,9 +164,9 @@ The more threats are handled by the application, the more skilled and careful a
| GRDB's DatabaseQueue | :white_check_mark: | :white_check_mark: | Handled by the application | UI is blocked |
| GRDB's DatabasePool | :white_check_mark: | :white_check_mark: | Handled by the application | :white_check_mark: (as long as the maximum number of readers has not been reached) |
I had to omit Realm and FCModel from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue.
I had to omit [Realm] and [FCModel] from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue.
We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to use or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way. A weaker way to say this is that conflict handling at the library level can wait :sweat_smile:.
We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to plan, use, or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way.
Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and you'd better be a very skilled developer in order to use them properly.
@@ -175,79 +177,89 @@ For further information about GRDB concurrency, check its detailed [Concurrency
SQL is a weird language. Born in the 70s, easy to [misuse](https://xkcd.com/327/), feared by some developers, despised by others, and yet wonderfully concise and powerful.
GRDB provides high-level record methods that generate SQL for you:
GRDB [query interface] and [associations] can generate SQL for you:
```swift
// SELECT * FROM players ORDER BY score DESC LIMIT 10
// SELECT * FROM player ORDER BY score DESC LIMIT 10
let bestPlayers: [Player] = try Player
.order(scoreColumn.desc)
.limit(10)
.fetchAll(db)
// SELECT MAX(score) FROM players
// SELECT MAX(score) FROM player
let maximumScore: Int? = try Player
.select(max(scoreColumn))
.asRequestOf(Int.self)
.fetchOne(db)
// SELECT COUNT(*) FROM players WHERE score = ?
let exAequoCount: Int = try Player
.filter(scoreColumn == maximumScore)
.fetchCount(db)
// SELECT book.*, author.*
// FROM book
// LEFT JOIN author ON author.id = book.authorId
let request = Book.including(optional: Book.author)
let bookInfos: [BookInfo] = BookInfo.fetchAll(db, request)
```
But you can *always* switch to SQL when you want to:
But you can always switch to SQL when you want to:
```swift
let bestPlayers: [Player] = try Player.fetchAll(db, """
SELECT * FROM players ORDER BY score DESC LIMIT 10
SELECT * FROM player ORDER BY score DESC LIMIT 10
""")
let maximumScore: Int? = try Int.fetchOne(db, """
SELECT MAX(score) FROM players
SELECT MAX(score) FROM player
""")
let exAequoCount: Int? = try Int.fetchOne(db, """
SELECT COUNT(*) FROM players WHERE score = ?
""", arguments: [maximumScore])
```
SQL is also welcome in high-level database observation tools like [FetchedRecordsController] and [RxGRDB]:
Power users can also consume complex joined SQL queries into handy record values, by *adapting* raw database rows to the decoded records (see [Joined Queries Support](#../README.md#joined-queries-support)):
```swift
SQLRequest("SELECT * FROM players ORDER BY score DESC LIMIT 10")
.asRequest(of: Player.self)
.rx
.fetchAll(in: dbQueue)
.subscribe(onNext: { players: [Player] in
print("Best 10 players have changed")
})
let bookInfos: [BookInfo] = SQLRequest<BookInfo>("""
SELECT book.*, author.*
FROM book
LEFT JOIN author ON author.id = book.authorId
""")
.adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
db.columns(in: "book").count,
db.columns(in: "author").count])
return ScopeAdapter([
"book": adapters[0],
"author": adapters[1]])
}
```
You can of course deal with raw database rows, and fetch [lazy cursors](https://github.com/groue/GRDB.swift/blob/master/README.md#cursors) instead of arrays:
In performance-critical sections, you may want to deal with raw database rows, and fetch [lazy cursors](../README.md#cursors) instead of arrays:
```swift
let rows = try Row.fetchCursor(db, "SELECT * FROM players")
let rows = try Row.fetchCursor(db, "SELECT id, name, score FROM player")
while let row = try rows.next() {
let id: Int64 = row["id"]
let name: String = row["name"]
let score: Int = row["score"]
let id: Int64 = row[0]
let name: String = row[1]
let score: Int = row[2]
}
```
When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](https://github.com/groue/GRDB.swift/blob/master/README.md#custom-requests):
When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](../README.md#custom-requests):
```swift
extension Player {
static func customRequest(...) -> AnyTypedRequest<Player> {
return SQLRequest("""
SELECT ...
""", arguments: ...)
.asRequestOf(Player.self)
static func customRequest(...) -> SQLRequest<Player> {
return SQLRequest<Player>("SELECT ...", arguments: ...)
}
}
let players = Player.customRequest(...).fetchAll(db)
let players = try Player.customRequest(...).fetchAll(db)
```
Those custom requests are welcome in database observation tools like [ValueObservation] and [RxGRDB]:
```swift
Player.customRequest(...).rx
.fetchAll(in: dbQueue)
.subscribe(onNext: { players: [Player] in
print("Players have changed")
})
```
---
@@ -258,23 +270,27 @@ And if you happen to maintain an Objective-C application that uses FMDB, checkou
Happy GRDB! :gift:
[Concurrency Guide]: https://github.com/groue/GRDB.swift/blob/master/README.md#concurrency
[Concurrency Guide]: ../README.md#concurrency
[Core Data]: https://developer.apple.com/documentation/coredata
[DatabasePool]: https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools
[DatabasePool]: ../README.md#database-pools
[Diesel]: http://diesel.rs
[FCModel]: https://github.com/marcoarment/FCModel
[FetchedRecordsController]: https://github.com/groue/GRDB.swift/blob/master/README.md#fetchedrecordscontroller
[ValueObservation]: ../README.md#valueobservation
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
[Fluent]: https://github.com/vapor/fluent
[FMDB]: http://github.com/ccgus/fmdb
[GRDB]: http://github.com/groue/GRDB.swift
[GRDBObjc]: http://github.com/groue/GRDBObjc
[Persistable]: https://github.com/groue/GRDB.swift/blob/master/README.md#records
[PersistableRecord]: ../README.md#records
[Realm]: http://realm.io
[RowConvertible]: https://github.com/groue/GRDB.swift/blob/master/README.md#records
[FetchableRecord]: ../README.md#records
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[RxSwift]: https://github.com/ReactiveX/RxSwift
[SQLite.swift]: http://github.com/stephencelis/SQLite.swift
[StORM]: https://www.perfect.org/docs/StORM.html
[Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery
[TableMapping]: https://github.com/groue/GRDB.swift/blob/master/README.md#records
[TransactionObserver]: https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol
[TableRecord]: ../README.md#records
[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 = '2.4.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
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
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -40,8 +40,8 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
codeCoverageEnabled = "YES"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -10,7 +10,6 @@
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
@@ -31,7 +30,6 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -26,8 +26,8 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
codeCoverageEnabled = "YES"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
+21
View File
@@ -19,10 +19,31 @@
<FileRef
location = "group:Issue156.playground">
</FileRef>
<FileRef
location = "group:CustomizedDecodingOfDatabaseRows.playground">
</FileRef>
<FileRef
location = "group:Associations.playground">
</FileRef>
<FileRef
location = "group:MyPlayground.playground">
</FileRef>
</Group>
<FileRef
location = "group:CHANGELOG.md">
</FileRef>
<FileRef
location = "group:README.md">
</FileRef>
<FileRef
location = "group:TODO.md">
</FileRef>
<FileRef
location = "group:Documentation/ReleaseProcess.md">
</FileRef>
<FileRef
location = "group:Makefile">
</FileRef>
<FileRef
location = "group:GRDB.xcodeproj">
</FileRef>
@@ -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>
+107 -1
View File
@@ -1,4 +1,5 @@
import Foundation
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
@@ -20,6 +21,53 @@ public struct Configuration {
/// Default: false
public var readonly: Bool = false
/// The database label.
///
/// You can query this label at runtime:
///
/// var configuration = Configuration()
/// configuration.label = "MyDatabase"
/// let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
///
/// try dbQueue.read { db in
/// print(db.configuration.label) // Prints "MyDatabase"
/// }
///
/// The database label is also used to name the various dispatch queues
/// created by GRDB, visible in debugging sessions and crash logs. However
/// those dispatch queue labels are intended for debugging only. Their
/// format may change between GRDB releases. Applications should not depend
/// on the GRDB dispatch queue labels.
///
/// If the database label is nil, the current GRDB implementation uses the
/// following dispatch queue labels:
///
/// - `GRDB.DatabaseQueue`: the (unique) dispatch queue of a DatabaseQueue
/// - `GRDB.DatabasePool.writer`: the (unique) writer dispatch queue of
/// a DatabasePool
/// - `GRDB.DatabasePool.reader.N`, where N is 1, 2, ...: one of the reader
/// dispatch queue(s) of a DatabasePool. N grows with the number of SQLite
/// connections: it may get bigger than the maximum number of concurrent
/// readers, as SQLite connections get closed and new ones are opened.
/// - `GRDB.DatabasePool.snapshot.N`: the dispatch queue of a
/// DatabaseSnapshot. N grows with the number of snapshots.
///
/// If the database label is not nil, for example "MyDatabase", the current
/// GRDB implementation uses the following dispatch queue labels:
///
/// - `MyDatabase`: the (unique) dispatch queue of a DatabaseQueue
/// - `MyDatabase.writer`: the (unique) writer dispatch queue of
/// a DatabasePool
/// - `MyDatabase.reader.N`, where N is 1, 2, ...: one of the reader
/// dispatch queue(s) of a DatabasePool. N grows with the number of SQLite
/// connections: it may get bigger than the maximum number of concurrent
/// readers, as SQLite connections get closed and new ones are opened.
/// - `MyDatabase.snapshot.N`: the dispatch queue of a
/// DatabaseSnapshot. N grows with the number of snapshots.
///
/// The default label is nil.
public var label: String? = nil
/// A function that is called on every statement executed by the database.
///
/// Default: nil
@@ -43,6 +91,38 @@ public struct Configuration {
/// Default: deferred
public var defaultTransactionKind: Database.TransactionKind = .deferred
/// If false, it is a programmer error to leave a transaction opened at the
/// end of a database access block.
///
/// For example:
///
/// let dbQueue = DatabaseQueue()
///
/// // fatal error: A transaction has been left opened at the end of a database access
/// try dbQueue.inDatabase { db in
/// try db.beginTransaction()
/// }
///
/// If true, one can leave opened transaction at the end of database access
/// blocks:
///
/// var config = Configuration()
/// config.allowsUnsafeTransactions = true
/// let dbQueue = DatabaseQueue(configuration: config)
///
/// try dbQueue.inDatabase { db in
/// try db.beginTransaction()
/// }
///
/// try dbQueue.inDatabase { db in
/// try db.commit()
/// }
///
/// This configuration flag has no effect on DatabasePool readers: those
/// never allow leaving a transaction opened at the end of a read access.
///
/// Default: false
public var allowsUnsafeTransactions: Bool = false
// MARK: - Concurrency
@@ -57,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
@@ -74,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.
+501 -83
View File
@@ -1,3 +1,16 @@
//===----------------------------------------------------------------------===//
//
// Parts of this file are derived from the Swift.org open source project:
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// MARK: - Array, Sequence, Set extensions
extension Array {
/// Creates an array containing the elements of a cursor.
///
@@ -11,6 +24,15 @@ extension Array {
}
}
extension Sequence {
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>> {
return AnyCursor(self).flatMap(transform)
}
}
extension Set {
/// Creates a set containing the elements of a cursor.
///
@@ -24,6 +46,8 @@ extension Set {
}
}
// MARK: - Cursor
/// A type that supplies the values of some external resource, one at a time.
///
/// ## Overview
@@ -46,19 +70,11 @@ extension Set {
/// - A cursor can not be repeated.
///
/// The protocol comes with default implementations for many operations similar
/// to those defined by Swift's LazySequenceProtocol:
///
/// - `func contains(Self.Element)`
/// - `func contains(where: (Self.Element) throws -> Bool)`
/// - `func enumerated()`
/// - `func filter((Self.Element) throws -> Bool)`
/// - `func first(where: (Self.Element) throws -> Bool)`
/// - `func flatMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?)`
/// - `func flatMap<SegmentOfResult>((Self.Element) throws -> SegmentOfResult)`
/// - `func forEach((Self.Element) throws -> Void)`
/// - `func joined()`
/// - `func map<T>((Self.Element) throws -> T)`
/// - `func reduce<Result>(Result, (Result, Self.Element) throws -> Result)`
/// to those defined by Swift's Sequence protocol: `contains`, `dropFirst`,
/// `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`,
/// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`,
/// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`,
/// `suffix`.
public protocol Cursor : class {
/// The type of element traversed by the cursor.
associatedtype Element
@@ -68,33 +84,13 @@ public protocol Cursor : class {
func next() throws -> Element?
}
/// A type-erased cursor of Element.
///
/// This cursor forwards its next() method to an arbitrary underlying cursor
/// having the same Element type, hiding the specifics of the underlying
/// cursor.
public class AnyCursor<Element> : Cursor {
/// Creates a cursor that wraps a base cursor but whose type depends only on
/// the base cursor’s element type
public init<C: Cursor>(_ base: C) where C.Element == Element {
element = base.next
}
/// Creates a cursor that wraps the given closure in its next() method
public init(_ body: @escaping () throws -> Element?) {
element = body
}
/// Advances to the next element and returns it, or nil if no next
/// element exists.
public func next() throws -> Element? {
return try element()
}
private let element: () throws -> Element?
}
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.
///
@@ -144,14 +140,115 @@ extension Cursor {
/// Returns a cursor over the concatenated non-nil results of mapping
/// transform over this cursor.
public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> {
public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> {
return map(transform).filter { $0 != nil }.map { $0! }
}
@available(*, deprecated, renamed: "compactMap")
public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> {
return compactMap(transform)
}
/// Returns a cursor that skips any initial elements that satisfy
/// `predicate`.
///
/// - Parameter predicate: A closure that takes an element of the cursir as
/// its argument and returns `true` if the element should be skipped or
/// `false` otherwise. Once `predicate` returns `false` it will not be
/// called again.
public func drop(while predicate: @escaping (Element) throws -> Bool) -> DropWhileCursor<Self> {
return DropWhileCursor(self, predicate: predicate)
}
/// Returns a cursor containing all but the given number of initial
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the cursor, the result is an empty cursor.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// try print(numbers.dropFirst(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop from the beginning of
/// the cursor. `n` must be greater than or equal to zero.
/// - Returns: A cursor starting after the specified number of
/// elements.
public func dropFirst(_ n: Int) -> DropFirstCursor<Self> {
return DropFirstCursor(self, limit: n)
}
/// Returns a cursor containing all but the first element of the cursor.
///
/// The following example drops the first element from a cursor of integers.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst())
/// // Prints "[2, 3, 4, 5]"
///
/// If the cursor has no elements, the result is an empty cursor.
///
/// - Returns: A cursor starting after the first element of the cursor.
public func dropFirst() -> DropFirstCursor<Self> {
return dropFirst(1)
}
/// Returns an array containing all but the given number of final
/// elements.
///
/// The cursor must be finite. If the number of elements to drop exceeds
/// the number of elements in the cursor, the result is an empty array.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// try print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// cursor. `n` must be greater than or equal to zero.
/// - Returns: An array leaving off the specified number of elements.
public func dropLast(_ n: Int) throws -> [Element] {
GRDBPrecondition(n >= 0, "Can't drop a negative number of elements from a cursor")
if n == 0 { return try Array(self) }
var result: [Element] = []
var ringBuffer: [Element] = []
var i = ringBuffer.startIndex
while let element = try next() {
if ringBuffer.count < n {
ringBuffer.append(element)
} else {
result.append(ringBuffer[i])
ringBuffer[i] = element
i = ringBuffer.index(after: i) % n
}
}
return result
}
/// Returns an array containing all but the last element of the cursor.
///
/// The following example drops the last element from a cursor of integers.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast())
/// // Prints "[1, 2, 3, 4]"
///
/// If the cursor has no elements, the result is an empty cursor.
///
/// - Returns: An array leaving off the last element of the cursor.
public func dropLast() throws -> [Element] {
return try dropLast(1)
}
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, IteratorCursor<SegmentOfResult.Iterator>>> {
return flatMap { try IteratorCursor(transform($0)) }
public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>> {
return flatMap { try AnyCursor(transform($0)) }
}
/// Returns a cursor over the concatenated results of mapping transform
@@ -173,17 +270,152 @@ extension Cursor {
return MapCursor(self, transform)
}
/// Returns the result of calling the given combining closure with each
/// element of this sequence and an accumulating value.
public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) throws -> Result {
var result = initialResult
while let element = try next() {
result = try nextPartialResult(result, element)
/// Returns the maximum element in the cursor, using the given predicate as
/// the comparison between elements.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's maximum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns `nil`.
public func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element? {
guard var result = try next() else {
return nil
}
while let e = try next() {
if try areInIncreasingOrder(result, e) {
result = e
}
}
return result
}
/// Returns the minimum element in the cursor, using the given predicate as
/// the comparison between elements.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's minimum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns `nil`.
public func min(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element? {
guard var result = try next() else {
return nil
}
while let e = try next() {
if try areInIncreasingOrder(e, result) {
result = e
}
}
return result
}
/// Returns a cursor, up to the specified maximum length, containing the
/// initial elements of the cursor.
///
/// If the maximum length exceeds the number of elements in the cursor,
/// the result contains all the elements in the cursor.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// try print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Returns: A cursor starting at the beginning of this cursor
/// with at most `maxLength` elements.
public func prefix(_ maxLength: Int) -> PrefixCursor<Self> {
return PrefixCursor(self, maxLength: maxLength)
}
/// Returns a cursor of the initial consecutive elements that satisfy
/// `predicate`.
///
/// - Parameter predicate: A closure that takes an element of the cursor as
/// its argument and returns `true` if the element should be included or
/// `false` otherwise. Once `predicate` returns `false` it will not be
/// called again.
public func prefix(while predicate: @escaping (Element) throws -> Bool) -> PrefixWhileCursor<Self> {
return PrefixWhileCursor(self, predicate: predicate)
}
/// Returns the result of calling the given combining closure with each
/// element of this cursor and an accumulating value.
public func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult: (Result, Element) throws -> Result)
throws -> Result
{
var accumulator = initialResult
while let element = try next() {
accumulator = try nextPartialResult(accumulator, element)
}
return accumulator
}
/// Returns the result of calling the given combining closure with each
/// element of this cursor and an accumulating value.
public func reduce<Result>(
into initialResult: Result,
_ updateAccumulatingResult: (inout Result, Element) throws -> Void)
throws -> Result
{
var accumulator = initialResult
while let element = try next() {
try updateAccumulatingResult(&accumulator, element)
}
return accumulator
}
/// Returns an array, up to the given maximum length, containing the
/// final elements of the cursor.
///
/// The cursor must be finite. If the maximum length exceeds the number of
/// elements in the cursor, the result contains all the elements in the
/// cursor.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// try print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
public func suffix(_ maxLength: Int) throws -> [Element] {
GRDBPrecondition(maxLength >= 0, "Can't take a suffix of negative length from a cursor")
if maxLength == 0 {
return []
}
var ringBuffer: [Element] = []
ringBuffer.reserveCapacity(maxLength)
var i = ringBuffer.startIndex
while let element = try next() {
if ringBuffer.count < maxLength {
ringBuffer.append(element)
} else {
ringBuffer[i] = element
i += 1
i %= maxLength
}
}
if i != ringBuffer.startIndex {
let s0 = ringBuffer[i..<ringBuffer.endIndex]
let s1 = ringBuffer[0..<i]
return Array([s0, s1].joined())
}
return ringBuffer
}
}
// MARK: Equatable elements
extension Cursor where Element: Equatable {
/// Returns a Boolean value indicating whether the cursor contains the
/// given element.
@@ -197,6 +429,36 @@ extension Cursor where Element: Equatable {
}
}
// MARK: Comparable elements
extension Cursor where Element: Comparable {
/// Returns the maximum element in the cursor.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's maximum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns
/// `nil`.
public func max() throws -> Element? {
return try max(by: <)
}
/// Returns the minimum element in the cursor.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's minimum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns
/// `nil`.
public func min() throws -> Element? {
return try min(by: <)
}
}
// MARK: Cursor elements
extension Cursor where Element: Cursor {
/// Returns the elements of this cursor of cursors, concatenated.
public func joined() -> FlattenCursor<Self> {
@@ -204,13 +466,135 @@ extension Cursor where Element: Cursor {
}
}
// MARK: Sequence elements
extension Cursor where Element: Sequence {
/// Returns the elements of this cursor of sequences, concatenated.
public func joined() -> FlattenCursor<MapCursor<Self, IteratorCursor<Self.Element.Iterator>>> {
public func joined() -> FlattenCursor<MapCursor<Self, AnyCursor<Element.Element>>> {
return flatMap { $0 }
}
}
// MARK: String elements
extension Cursor where Element: StringProtocol {
/// Returns the elements of this cursor of sequences, concatenated.
public func joined(separator: String = "") throws -> String {
if separator.isEmpty {
var result = ""
while let x = try next() {
result.append(String(x))
}
return result
} else {
var result = ""
if let first = try next() {
result.append(String(first))
while let next = try next() {
result.append(separator)
result.append(String(next))
}
}
return result
}
}
}
// MARK: Specialized Cursors
/// A type-erased cursor of Element.
///
/// This cursor forwards its next() method to an arbitrary underlying cursor
/// having the same Element type, hiding the specifics of the underlying
/// cursor.
public final class AnyCursor<Element> : Cursor {
private let element: () throws -> Element?
/// Creates a cursor that wraps a base cursor but whose type depends only on
/// the base cursor’s element type
public init<C: Cursor>(_ base: C) where C.Element == Element {
element = base.next
}
/// Creates a cursor that wraps a base iterator but whose type depends only
/// on the base iterator’s element type
public convenience init<I: IteratorProtocol>(iterator: I) where I.Element == Element {
var iterator = iterator
self.init { iterator.next() }
}
/// Creates a cursor that wraps a base sequence but whose type depends only
/// on the base sequence’s element type
public convenience init<S: Sequence>(_ s: S) where S.Element == Element {
self.init(iterator: s.makeIterator())
}
/// Creates a cursor that wraps the given closure in its next() method
public init(_ body: @escaping () throws -> Element?) {
element = body
}
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> Element? {
return try element()
}
}
/// :nodoc:
public final class DropFirstCursor<Base: Cursor> : Cursor {
private let base: Base
private let limit: Int
private var dropped: Int = 0
init(_ base: Base, limit: Int) {
GRDBPrecondition(limit >= 0, "Can't drop a negative number of elements from a cursor")
self.base = base
self.limit = limit
}
public func next() throws -> Base.Element? {
while dropped < limit {
if try base.next() == nil {
dropped = limit
return nil
}
dropped += 1
}
return try base.next()
}
}
/// A cursor whose elements consist of the elements that follow the initial
/// consecutive elements of some base cursor that satisfy a given predicate.
///
/// :nodoc:
public final class DropWhileCursor<Base: Cursor> : Cursor {
private let base: Base
private let predicate: (Base.Element) throws -> Bool
private var predicateHasFailed = false
init(_ base: Base, predicate: @escaping (Base.Element) throws -> Bool) {
self.base = base
self.predicate = predicate
}
public func next() throws -> Base.Element? {
if predicateHasFailed {
return try base.next()
}
while let nextElement = try base.next() {
if try !predicate(nextElement) {
predicateHasFailed = true
return nextElement
}
}
return nil
}
}
/// An enumeration of the elements of a cursor.
///
/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method
@@ -223,27 +607,35 @@ extension Cursor where Element: Sequence {
/// }
/// // Prints: "0: foo"
/// // Prints: "1: bar"
///
/// :nodoc:
public final class EnumeratedCursor<Base: Cursor> : Cursor {
private let base: Base
private var index: Int
init(_ base: Base) {
self.index = 0
self.base = base
self.index = 0
}
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> (Int, Base.Element)? {
guard let element = try base.next() else { return nil }
defer { index += 1 }
return (index, element)
}
private var index: Int
private var base: Base
}
/// A cursor whose elements consist of the elements of some base cursor that
/// also satisfy a given predicate.
///
/// :nodoc:
public final class FilterCursor<Base: Cursor> : Cursor {
private let base: Base
private let isIncluded: (Base.Element) throws -> Bool
init(_ base: Base, _ isIncluded: @escaping (Base.Element) throws -> Bool) {
self.base = base
self.isIncluded = isIncluded
@@ -251,6 +643,7 @@ public final class FilterCursor<Base: Cursor> : Cursor {
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> Base.Element? {
while let element = try base.next() {
if try isIncluded(element) {
@@ -259,22 +652,25 @@ public final class FilterCursor<Base: Cursor> : Cursor {
}
return nil
}
private let base: Base
private let isIncluded: (Base.Element) throws -> Bool
}
/// A cursor consisting of all the elements contained in each segment contained
/// in some Base cursor.
///
/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:)
///
/// :nodoc:
public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Cursor {
private let base: Base
private var inner: Base.Element?
init(_ base: Base) {
self.base = base
}
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> Base.Element.Element? {
while true {
if let element = try inner?.next() {
@@ -286,16 +682,18 @@ public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Curs
self.inner = inner
}
}
private var inner: Base.Element?
private let base: Base
}
/// A Cursor whose elements consist of those in a Base Cursor passed through a
/// transform function returning Element.
///
/// See Cursor.map(_:)
///
/// :nodoc:
public final class MapCursor<Base: Cursor, Element> : Cursor {
private let base: Base
private let transform: (Base.Element) throws -> Element
init(_ base: Base, _ transform: @escaping (Base.Element) throws -> Element) {
self.base = base
self.transform = transform
@@ -303,42 +701,62 @@ public final class MapCursor<Base: Cursor, Element> : Cursor {
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> Element? {
guard let element = try base.next() else { return nil }
return try transform(element)
}
}
/// A cursor that only consumes up to `n` elements from an underlying
/// `Base` cursor.
///
/// :nodoc:
public final class PrefixCursor<Base: Cursor> : Cursor {
private let base: Base
private let transform: (Base.Element) throws -> Element
}
/// A Cursor whose elements are those of a sequence iterator.
public final class IteratorCursor<Base: IteratorProtocol> : Cursor {
private let maxLength: Int
private var taken = 0
/// Creates a cursor from a sequence iterator.
public init(_ base: Base) {
init(_ base: Base, maxLength: Int) {
self.base = base
self.maxLength = maxLength
}
/// Creates a cursor from a sequence.
public init<S: Sequence>(_ s: S) where S.Iterator == Base {
self.base = s.makeIterator()
public func next() throws -> Base.Element? {
if taken >= maxLength { return nil }
taken += 1
if let next = try base.next() {
return next
}
taken = maxLength
return nil
}
/// Advances to the next element and returns it, or nil if no next
/// element exists.
public func next() -> Base.Element? {
return base.next()
}
private var base: Base
}
extension Sequence {
/// A cursor whose elements consist of the initial consecutive elements of
/// some base cursor that satisfy a given predicate.
///
/// :nodoc:
public final class PrefixWhileCursor<Base: Cursor> : Cursor {
private let base: Base
private let predicate: (Base.Element) throws -> Bool
private var predicateHasFailed = false
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<IteratorCursor<Self.Iterator>, SegmentOfResult>> {
return IteratorCursor(self).flatMap(transform)
init(_ base: Base, predicate: @escaping (Base.Element) throws -> Bool) {
self.base = base
self.predicate = predicate
}
public func next() throws -> Base.Element? {
if !predicateHasFailed, let nextElement = try base.next() {
if try predicate(nextElement) {
return nextElement
} else {
predicateHasFailed = true
}
}
return nil
}
}
+228 -59
View File
@@ -25,21 +25,49 @@ 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.
///
/// Those are tables whose name begins with "sqlite_".
///
/// For more information, see https://www.sqlite.org/fileformat2.html
public func isSQLiteInternalTable(_ tableName: String) -> Bool {
// https://www.sqlite.org/fileformat2.html#internal_schema_objects
// > The names of internal schema objects always begin with "sqlite_"
// > and any table, index, view, or trigger whose name begins with
// > "sqlite_" is an internal schema object. SQLite prohibits
// > applications from creating objects whose names begin with
// > "sqlite_".
return tableName.starts(with: "sqlite_")
}
/// Returns whether a table is an internal GRDB table.
///
/// Those are tables whose name begins with "grdb_".
public func isGRDBInternalTable(_ tableName: String) -> Bool {
return tableName.starts(with: "grdb_")
}
/// 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`.
@@ -129,13 +157,6 @@ extension Database {
return primaryKey
}
/// The number of columns in the table named `tableName`.
///
/// - throws: A DatabaseError if table does not exist.
public func columnCount(in tableName: String) throws -> Int {
return try columns(in: tableName).count
}
/// The indexes on table named `tableName`; returns the empty array if the
/// table does not exist.
///
@@ -149,14 +170,29 @@ 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 {
// PRAGMA index_list doesn't throw any error when table does
// not exist. So let's check if table exists:
if try tableExists(tableName) == false {
throw DatabaseError(message: "no such table: \(tableName)")
}
}
schemaCache.set(indexes: indexes, forTable: tableName)
@@ -178,7 +214,7 @@ extension Database {
var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = []
var previousId: Int? = nil
for row in try Row.fetchAll(self, "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
// row = <Row id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"...">
// row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."]
let id: Int = row[0]
let seq: Int = row[1]
let table: String = row[2]
@@ -193,6 +229,14 @@ extension Database {
}
}
if rawForeignKeys.isEmpty {
// PRAGMA foreign_key_list doesn't throw any error when table does
// not exist. So let's check if table exists:
if try tableExists(tableName) == false {
throw DatabaseError(message: "no such table: \(tableName)")
}
}
let foreignKeys = try rawForeignKeys.map { (destinationTable, columnMapping) -> ForeignKeyInfo in
let orderedMapping = columnMapping
.sorted { $0.seq < $1.seq }
@@ -215,14 +259,31 @@ extension Database {
schemaCache.set(foreignKeys: foreignKeys, forTable: tableName)
return foreignKeys
}
/// Returns the actual name of the database table
func canonicalTableName(_ tableName: String) throws -> String {
guard let name = try schema().canonicalName(tableName, ofType: .table) else {
throw DatabaseError(message: "no such table: \(tableName)")
}
return name
}
func schema() throws -> SchemaInfo {
if let schemaInfo = schemaCache.schemaInfo {
return schemaInfo
}
let schemaInfo = try SchemaInfo(self)
schemaCache.schemaInfo = schemaInfo
return schemaInfo
}
}
extension Database {
/// The columns in the table named `tableName`.
/// The columns in the table named `tableName`
///
/// - throws: A DatabaseError if table does not exist.
func columns(in tableName: String) throws -> [ColumnInfo] {
public func columns(in tableName: String) throws -> [ColumnInfo] {
if let columns = schemaCache.columns(in: tableName) {
return columns
}
@@ -258,7 +319,9 @@ extension Database {
throw DatabaseError(message: "no such table: \(tableName)")
}
}
let columns = try ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
let columns = try ColumnInfo
.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
.sorted(by: { $0.cid < $1.cid })
guard columns.count > 0 else {
throw DatabaseError(message: "no such table: \(tableName)")
}
@@ -284,30 +347,80 @@ extension Database {
}
}
/// A column of a table
struct ColumnInfo : RowConvertible {
// CREATE TABLE players (
// id INTEGER PRIMARY KEY,
// firstName TEXT,
// lastName TEXT)
//
// PRAGMA table_info("players")
//
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
let name: String
let type: String
let notNull: Bool
let defaultDatabaseValue: DatabaseValue
let primaryKeyIndex: Int
/// A column of a database table.
///
/// This type closely matches the information returned by the
/// `table_info` pragma.
///
/// > CREATE TABLE player (
/// id INTEGER PRIMARY KEY,
/// firstName TEXT,
/// lastName TEXT)
/// > PRAGMA table_info("player")
/// cid name type notnull dflt_value pk
/// ---- ----- ------- -------- ---------- ---
/// 0 id INTEGER 0 NULL 1
/// 1 name TEXT 0 NULL 0
/// 2 score INTEGER 0 NULL 0
///
/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info
public struct ColumnInfo : FetchableRecord {
let cid: Int
init(row: Row) {
/// The column name
public let name: String
/// The column data type
public let type: String
/// True if and only if the column is constrained to be not null.
public let isNotNull: Bool
/// The SQL snippet that defines the default value, if any.
///
/// When nil, the column has no default value.
///
/// When not nil, it contains an SQL string that defines an expression. That
/// expression may be a literal, as `1`, or `'foo'`. It may also contain a
/// non-constant expression such as `CURRENT_TIMESTAMP`.
///
/// For example:
///
/// try db.execute("""
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY,
/// name TEXT DEFAULT 'Anonymous',
/// score INT DEFAULT 0,
/// creationDate DATE DEFAULT CURRENT_TIMESTAMP
/// )
/// """)
/// let columnInfos = try db.columns(in: "player")
/// columnInfos[0].defaultValueSQL // nil
/// columnInfos[1].defaultValueSQL // "'Anoynymous'"
/// columnInfos[2].defaultValueSQL // "0"
/// columnInfos[3].defaultValueSQL // "CURRENT_TIMESTAMP"
public let defaultValueSQL: String?
/// Zero for columns that are not part of the primary key.
///
/// Before SQLite 3.7.16, it is 1 for columns that are part of the
/// primary key.
///
/// Starting from SQLite 3.7.16, it is the one-based index of the column in
/// the primary key for columns that are part of the primary key.
///
/// References:
/// - https://sqlite.org/releaselog/3_7_16.html
/// - http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html
public let primaryKeyIndex: Int
/// :nodoc:
public init(row: Row) {
cid = row["cid"]
name = row["name"]
type = row["type"]
notNull = row["notnull"]
defaultDatabaseValue = row["dflt_value"]
isNotNull = row["notnull"]
defaultValueSQL = row["dflt_value"]
primaryKeyIndex = row["pk"]
}
}
@@ -336,38 +449,38 @@ public struct IndexInfo {
///
/// When the table's primary key is the rowid:
///
/// // CREATE TABLE items (name TEXT)
/// let pk = try db.primaryKey("items")
/// // CREATE TABLE item (name TEXT)
/// let pk = try db.primaryKey("item")
/// pk.columns // ["rowid"]
/// pk.rowIDColumn // nil
/// pk.isRowID // true
///
/// // CREATE TABLE citizens (
/// // CREATE TABLE citizen (
/// // id INTEGER PRIMARY KEY,
/// // name TEXT
/// // )
/// let pk = try db.primaryKey("citizens")!
/// let pk = try db.primaryKey("citizen")!
/// pk.columns // ["id"]
/// pk.rowIDColumn // "id"
/// pk.isRowID // true
///
/// When the table's primary key is not the rowid:
///
/// // CREATE TABLE countries (
/// // CREATE TABLE country (
/// // isoCode TEXT NOT NULL PRIMARY KEY
/// // name TEXT
/// // )
/// let pk = db.primaryKey("countries")!
/// let pk = db.primaryKey("country")!
/// pk.columns // ["isoCode"]
/// pk.rowIDColumn // nil
/// pk.isRowID // false
///
/// // CREATE TABLE citizenships (
/// // citizenID INTEGER NOT NULL REFERENCES citizens(id)
/// // countryIsoCode TEXT NOT NULL REFERENCES countries(isoCode)
/// // CREATE TABLE citizenship (
/// // citizenID INTEGER NOT NULL REFERENCES citizen(id)
/// // countryIsoCode TEXT NOT NULL REFERENCES country(isoCode)
/// // PRIMARY KEY (citizenID, countryIsoCode)
/// // )
/// let pk = db.primaryKey("citizenships")!
/// let pk = db.primaryKey("citizenship")!
/// pk.columns // ["citizenID", "countryIsoCode"]
/// pk.rowIDColumn // nil
/// pk.isRowID // false
@@ -454,3 +567,59 @@ public struct ForeignKeyInfo {
return mapping.map { $0.destination }
}
}
enum SchemaObjectType: String {
case index
case table
case trigger
case view
}
struct SchemaInfo: Equatable {
private var objects: Set<SchemaObject>
init(_ db: Database) throws {
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
"""))
}
/// 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?
var sql: String?
var isTemporary: Bool
#if !swift(>=4.2)
var hashValue: Int {
var hash = type.hashValue
hash ^= name.hashValue
hash ^= (tbl_name?.hashValue ?? 0)
hash ^= (sql?.hashValue ?? 0)
hash ^= isTemporary.hashValue
return hash
}
#endif
}
}
+94 -51
View File
@@ -1,12 +1,12 @@
import Foundation
extension Database {
// MARK: - Statements
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
@@ -14,12 +14,12 @@ extension Database {
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeSelectStatement(_ sql: String) throws -> SelectStatement {
return try makeStatement(sql, prepFlags: 0)
return try makeSelectStatement(sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?", prepFlags: 0)
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
@@ -29,12 +29,12 @@ extension Database {
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeSelectStatement(_ sql: String, prepFlags: Int32) throws -> SelectStatement {
return try makeStatement(sql, prepFlags: prepFlags)
return try SelectStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
/// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
@@ -55,7 +55,7 @@ extension Database {
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)")
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
@@ -63,12 +63,12 @@ extension Database {
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement {
return try makeStatement(sql, prepFlags: 0)
return try makeUpdateStatement(sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)", prepFlags: 0)
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)", prepFlags: 0)
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
@@ -78,12 +78,12 @@ extension Database {
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeUpdateStatement(_ sql: String, prepFlags: Int32) throws -> UpdateStatement {
return try makeStatement(sql, prepFlags: prepFlags)
return try UpdateStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedUpdateStatement("INSERT INTO players (name) VALUES (?)")
/// let statement = try db.cachedUpdateStatement("INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
@@ -105,13 +105,13 @@ extension Database {
/// Executes one or several SQL statements, separated by semi-colons.
///
/// try db.execute(
/// "INSERT INTO players (name) VALUES (:name)",
/// "INSERT INTO player (name) VALUES (:name)",
/// arguments: ["name": "Arthur"])
///
/// try db.execute("""
/// INSERT INTO players (name) VALUES (?);
/// INSERT INTO players (name) VALUES (?);
/// INSERT INTO players (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// """, arguments; ['Arthur', 'Barbara', 'Craig'])
///
/// This method may throw a DatabaseError.
@@ -185,41 +185,6 @@ extension Database {
// arguments that do not match the statement.
try! validateRemainingArguments() // throws if there are remaining arguments.
}
private func makeStatement<Statement: AuthorizedStatement>(_ sql: String, prepFlags: Int32) throws -> Statement {
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
authorizer = statementCompilationAuthorizer
defer { authorizer = nil }
var statement: Statement? = nil
let sqlCodeUnits = sql.utf8CString
var remainingSQL = ""
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let statementStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
var statementEnd: UnsafePointer<Int8>? = nil
do {
statement = try Statement(
database: self,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: prepFlags,
authorizer: statementCompilationAuthorizer)
} catch is EmptyStatementError {
throw DatabaseError(resultCode: .SQLITE_ERROR, message: "empty statement", sql: sql, arguments: nil)
}
let remainingData = Data(
bytesNoCopy: UnsafeMutableRawPointer(mutating: statementEnd!),
count: statementStart + sqlCodeUnits.count - statementEnd! - 1,
deallocator: .none)
remainingSQL = String(data: remainingData, encoding: .utf8)!.trimmingCharacters(in: statementSeparatorCharacterSet)
}
guard remainingSQL.isEmpty else {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
}
return statement!
}
}
extension Database {
@@ -258,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)
}
}
}
+242 -117
View File
@@ -21,8 +21,8 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// let dbQueue = DatabaseQueue(...)
///
/// // The Database is the `db` in the closure:
/// try dbQueue.inDatabase { db in
/// try db.execute(...)
/// try dbQueue.write { db in
/// try Player(...).insert(db)
/// }
public final class Database {
// The Database class is not thread-safe. An instance should always be
@@ -46,7 +46,20 @@ public final class Database {
/// > advantage of the error logging facility of SQLite in their products,
/// > as it is very low CPU and memory cost but can be a huge aid
/// > for debugging.
public static var logError: LogErrorFunction? = nil
public static var logError: LogErrorFunction? = nil {
didSet {
if logError != nil {
registerErrorLogCallback { (_, code, message) in
guard let logError = Database.logError else { return }
guard let message = message.map({ String(cString: $0) }) else { return }
let resultCode = ResultCode(rawValue: code)
logError(resultCode, message)
}
} else {
registerErrorLogCallback(nil)
}
}
}
/// The database configuration
public let configuration: Configuration
@@ -94,6 +107,12 @@ public final class Database {
// > Autocommit mode is on by default. Autocommit mode is disabled by a
// > BEGIN statement. Autocommit mode is re-enabled by a COMMIT
// > or ROLLBACK.
//
// > If another thread changes the autocommit status of the database
// > connection while this routine is running, then the return value
// > is undefined.
SchedulingWatchdog.preconditionValidQueue(self)
if isClosed { return false } // Support for SerializedDatabasae.deinit
return sqlite3_get_autocommit(sqliteConnection) == 0
}
@@ -131,7 +150,9 @@ public final class Database {
lazy var observationBroker = DatabaseObservationBroker(self)
/// The list of compile options used when building SQLite
static let sqliteCompileOptions: Set<String> = DatabaseQueue().inDatabase { try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS")) }
static let sqliteCompileOptions: Set<String> = DatabaseQueue().inDatabase {
try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS"))
}
// MARK: - Private properties
@@ -145,9 +166,6 @@ public final class Database {
// MARK: - Initializer
init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCache) throws {
// Setup the global SQLite error log before connecting to the database.
Database.setupGlobalErrorLog()
let sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
do {
try Database.activateExtendedCodes(sqliteConnection)
@@ -179,31 +197,21 @@ extension Database {
// MARK: - Database Opening
/// Registers the public Database.logError function as the global SQLite
/// error log, with sqlite3_config(SQLITE_CONFIG_LOG).
///
/// See https://sqlite.org/c3ref/c_config_covering_index_scan.html#sqliteconfiglog
private static func setupGlobalErrorLog() {
// We use a Swift static variable as a way to ensure that the error log
// is registered once and only once.
struct Impl {
static let setupErrorLog: () = {
registerErrorLogCallback { (_, code, message) in
guard let log = Database.logError else { return }
guard let message = message.map({ String(cString: $0) }) else { return }
let resultCode = ResultCode(rawValue: code)
log(resultCode, message)
}
}()
}
Impl.setupErrorLog
}
private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection {
// See https://www.sqlite.org/c3ref/open.html
var sqliteConnection: SQLiteConnection? = nil
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 {
@@ -280,53 +288,62 @@ extension Database {
setupBusyMode()
setupDefaultFunctions()
setupDefaultCollations()
observationBroker.setup()
observationBroker.installCommitAndRollbackHooks()
}
private func setupTrace() {
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
}, 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)
return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
}, dbPointer)
#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()
}
#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 {
@@ -396,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
@@ -445,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 {
@@ -531,6 +536,25 @@ extension Database {
}
}
extension Database {
// MARK: - Read-Only Access
/// Grants read-only access, starting SQLite 3.8.0
func readOnly<T>(_ block: () throws -> T) rethrows -> T {
if configuration.readonly {
return try block()
}
// 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! internalCachedUpdateStatement("PRAGMA query_only = 1").execute()
defer { try! internalCachedUpdateStatement("PRAGMA query_only = 0").execute() }
return try block()
}
}
extension Database {
// MARK: - Transactions & Savepoint
@@ -552,14 +576,14 @@ extension Database {
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is configuration.defaultTransactionKind, which itself
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
/// for more information.
/// - block: A block that executes SQL statements and return either
/// .commit or .rollback.
/// - throws: The error thrown by the block.
public func inTransaction(_ kind: TransactionKind? = nil, _ block: () throws -> TransactionCompletion) throws {
// Begin transaction
try beginTransaction(kind ?? configuration.defaultTransactionKind)
try beginTransaction(kind)
// Now that transaction has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
@@ -647,6 +671,7 @@ extension Database {
switch completion {
case .commit:
try execute("RELEASE SAVEPOINT grdb")
assert(!topLevelSavepoint || !isInsideTransaction)
needsRollback = false
case .rollback:
needsRollback = true
@@ -679,11 +704,70 @@ extension Database {
}
}
func beginTransaction(_ kind: TransactionKind) throws {
/// Begins a database transaction.
///
/// - parameter kind: The transaction type (default nil). If nil, the
/// transaction type is configuration.defaultTransactionKind, which itself
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
/// for more information.
/// - throws: The error thrown by the block.
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
let kind = kind ?? configuration.defaultTransactionKind
try execute("BEGIN \(kind.rawValue) TRANSACTION")
assert(isInsideTransaction)
}
private func rollback() throws {
/// 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.
public func rollback() throws {
// The SQLite documentation contains two related but distinct techniques
// to handle rollbacks and errors:
//
@@ -723,13 +807,17 @@ extension Database {
// The second technique is more robust, because we don't have to guess
// which rollback errors should be ignored, and which rollback errors
// should be exposed to the library user.
SchedulingWatchdog.preconditionValidQueue(self) // guard sqlite3_get_autocommit
if sqlite3_get_autocommit(sqliteConnection) == 0 {
try execute("ROLLBACK TRANSACTION")
}
assert(!isInsideTransaction)
}
func commit() throws {
/// Commits a database transaction.
public func commit() throws {
try execute("COMMIT TRANSACTION")
assert(!isInsideTransaction)
}
}
@@ -745,6 +833,49 @@ extension Database {
}
}
extension Database {
// MARK: - Backup
static func backup(from dbFrom: Database, to dbDest: Database, afterBackupInit: (() -> ())? = nil, afterBackupStep: (() -> ())? = nil) throws {
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else {
throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
}
guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else {
throw DatabaseError(resultCode: .SQLITE_ERROR)
}
afterBackupInit?()
do {
backupLoop: while true {
switch sqlite3_backup_step(backup, -1) {
case SQLITE_DONE:
afterBackupStep?()
break backupLoop
case SQLITE_OK:
afterBackupStep?()
case let code:
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
}
}
} catch {
sqlite3_backup_finish(backup)
throw error
}
switch sqlite3_backup_finish(backup) {
case SQLITE_OK:
break
case let code:
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
}
// The schema of the destination database has changed:
dbDest.clearSchemaCache()
}
}
#if SQLITE_HAS_CODEC
extension Database {
@@ -827,8 +958,10 @@ extension Database {
///
/// See https://www.sqlite.org/datatype3.html#collation
public struct CollationName : RawRepresentable, Hashable {
/// :nodoc:
public let rawValue: String
/// :nodoc:
public init(rawValue: String) {
self.rawValue = rawValue
}
@@ -837,11 +970,6 @@ extension Database {
self.rawValue = rawValue
}
/// The hash value
public var hashValue: Int {
return rawValue.hashValue
}
/// The `BINARY` built-in SQL collation
public static let binary = CollationName("BINARY")
@@ -854,15 +982,17 @@ extension Database {
/// An SQL column type.
///
/// try db.create(table: "players") { t in
/// t.column("id", .integer).primaryKey()
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("title", .text)
/// }
///
/// See https://www.sqlite.org/datatype3.html
public struct ColumnType : RawRepresentable, Hashable {
/// :nodoc:
public let rawValue: String
/// :nodoc:
public init(rawValue: String) {
self.rawValue = rawValue
}
@@ -871,11 +1001,6 @@ extension Database {
self.rawValue = rawValue
}
/// The hash value
public var hashValue: Int {
return rawValue.hashValue
}
/// The `TEXT` SQL column type
public static let text = ColumnType("TEXT")
+17 -8
View File
@@ -16,7 +16,7 @@ public final class DatabaseCollation {
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// db.add(collation: collation)
/// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard")
/// try db.execute("CREATE TABLE file (name TEXT COLLATE localized_standard")
///
/// - parameters:
/// - name: The function name.
@@ -32,18 +32,27 @@ 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:
public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
// See https://www.sqlite.org/c3ref/create_collation.html
return sqlite3_stricmp(lhs.name, lhs.name) == 0
+26 -16
View File
@@ -5,7 +5,7 @@ import Foundation
import SQLite3
#endif
public struct ResultCode : RawRepresentable {
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
public let rawValue: Int32
public init(rawValue: Int32) {
@@ -139,30 +139,34 @@ public struct ResultCode : RawRepresentable {
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
}
extension ResultCode : Equatable {
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension ResultCode : CustomStringConvertible {
public var description: String {
// CustomStringConvertible
extension ResultCode {
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.
public struct DatabaseError : Error {
public struct DatabaseError : Error, CustomStringConvertible, CustomNSError {
/// The SQLite error code (see
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
@@ -203,7 +207,7 @@ public struct DatabaseError : Error {
/// 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
}
@@ -223,7 +227,9 @@ public struct DatabaseError : Error {
let arguments: StatementArguments?
}
extension DatabaseError: CustomStringConvertible {
// CustomStringConvertible
extension DatabaseError {
/// :nodoc:
public var description: String {
var description = "SQLite error \(resultCode.rawValue)"
if let sql = sql {
@@ -239,19 +245,23 @@ extension DatabaseError: CustomStringConvertible {
}
}
extension DatabaseError : CustomNSError {
// CustomNSError
extension DatabaseError {
/// NSError bridging: the domain of the error.
/// :nodoc:
public static var errorDomain: String {
return "GRDB.DatabaseError"
}
/// NSError bridging: the error code within the given domain.
/// :nodoc:
public var errorCode: Int {
return Int(extendedResultCode.rawValue)
}
/// NSError bridging: the user-info dictionary.
/// :nodoc:
public var errorUserInfo: [String : Any] {
return [NSLocalizedDescriptionKey: description]
}
+33 -22
View File
@@ -5,12 +5,17 @@
#endif
/// An SQL function or aggregate.
public final class DatabaseFunction {
public let name: String
let argumentCount: Int32?
public final class DatabaseFunction: Hashable {
// SQLite identifies functions by (name + argument count)
private struct Identity: Hashable {
let name: String
let nArg: Int32 // -1 for variadic functions
}
public var name: String { return identity.name }
private let identity: Identity
let pure: Bool
private let kind: Kind
private var nArg: Int32 { return argumentCount ?? -1 }
private var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
/// Returns an SQL function.
@@ -38,8 +43,7 @@ public final class DatabaseFunction {
/// exactly *argumentCount* elements, provided *argumentCount* is
/// not nil.
public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) {
self.name = name
self.argumentCount = argumentCount
self.identity = Identity(name: name, nArg: argumentCount ?? -1)
self.pure = pure
self.kind = .function{ (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
@@ -68,7 +72,7 @@ public final class DatabaseFunction {
/// let dbQueue = DatabaseQueue()
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
/// dbQueue.add(function: fn)
/// try dbQueue.inDatabase { db in
/// try dbQueue.write { db in
/// try db.execute("CREATE TABLE test(i)")
/// try db.execute("INSERT INTO test(i) VALUES (1)")
/// try db.execute("INSERT INTO test(i) VALUES (2)")
@@ -89,8 +93,7 @@ public final class DatabaseFunction {
/// have exactly *argumentCount* elements, provided *argumentCount* is
/// not nil.
public init<Aggregate: DatabaseAggregate>(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type) {
self.name = name
self.argumentCount = argumentCount
self.identity = Identity(name: name, nArg: argumentCount ?? -1)
self.pure = pure
self.kind = .aggregate { return Aggregate() }
}
@@ -104,8 +107,8 @@ public final class DatabaseFunction {
let code = sqlite3_create_function_v2(
db.sqliteConnection,
name,
nArg,
identity.name,
identity.nArg,
eTextRep,
definitionP,
kind.xFunc,
@@ -127,8 +130,8 @@ public final class DatabaseFunction {
func uninstall(in db: Database) {
let code = sqlite3_create_function_v2(
db.sqliteConnection,
name,
nArg,
identity.name,
identity.nArg,
eTextRep,
nil, nil, nil, nil, nil)
@@ -274,7 +277,7 @@ public final class DatabaseFunction {
let aggregateContextU = Unmanaged.passRetained(aggregateContext)
var aggregateContextP = aggregateContextU.toOpaque()
withUnsafeBytes(of: &aggregateContextP) {
aggregateContextBufferP.copyBytes(from: $0)
aggregateContextBufferP.copyMemory(from: $0)
}
return aggregateContextU
}
@@ -309,15 +312,23 @@ public final class DatabaseFunction {
}
}
extension DatabaseFunction : Hashable {
/// The hash value
public var hashValue: Int {
return name.hashValue ^ nArg.hashValue
extension DatabaseFunction {
#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:
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
return lhs.name == rhs.name && lhs.nArg == rhs.nArg
return lhs.identity == rhs.identity
}
}
@@ -342,7 +353,7 @@ extension DatabaseFunction : Hashable {
/// let dbQueue = DatabaseQueue()
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
/// dbQueue.add(function: fn)
/// try dbQueue.inDatabase { db in
/// try dbQueue.write { db in
/// try db.execute("CREATE TABLE test(i)")
/// try db.execute("INSERT INTO test(i) VALUES (1)")
/// try db.execute("INSERT INTO test(i) VALUES (2)")
@@ -358,10 +369,10 @@ public protocol DatabaseAggregate {
/// aggregate function.
///
/// -- One value
/// SELECT maxLength(name) FROM players
/// SELECT maxLength(name) FROM player
///
/// -- Two values
/// SELECT maxFullNameLength(firstName, lastName) FROM players
/// SELECT maxFullNameLength(firstName, lastName) FROM player
///
/// This method is never called after the finalize() method has been called.
mutating func step(_ dbValues: [DatabaseValue]) throws
+376 -214
View File
@@ -1,4 +1,5 @@
import Foundation
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
@@ -9,13 +10,16 @@ import Foundation
#endif
/// A DatabasePool grants concurrent accesses to an SQLite database.
public final class DatabasePool {
public final class DatabasePool: DatabaseWriter {
private let writer: SerializedDatabase
private var readerConfig: Configuration
private var readerPool: Pool<SerializedDatabase>!
private var functions = Set<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
private var tokenizerRegistrations: [(Database) -> Void] = []
var snapshotCount = ReadWriteBox(0)
#if os(iOS)
private weak var application: UIApplication?
@@ -39,19 +43,17 @@ public final class DatabasePool {
/// - parameters:
/// - path: The path to the database file.
/// - configuration: A configuration.
/// - maximumReaderCount: The maximum number of readers. Default is 5.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public init(path: String, configuration: Configuration = Configuration()) throws {
GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1")
// Writer and readers share the same database schema cache
let sharedSchemaCache = SharedDatabaseSchemaCache()
// Writer
writer = try SerializedDatabase(
path: path,
configuration: configuration,
schemaCache: sharedSchemaCache)
schemaCache: SimpleDatabaseSchemaCache(),
defaultLabel: "GRDB.DatabasePool",
purpose: "writer")
// Activate WAL Mode unless readonly
if !configuration.readonly {
@@ -80,21 +82,17 @@ public final class DatabasePool {
readerConfig = configuration
readerConfig.readonly = true
readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections.
readerConfig.allowsUnsafeTransactions = false // Because there's no guarantee that one can get the same reader in order to close its opened transaction.
var readerCount = 0
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
readerCount += 1 // protected by pool's ReadWriteBox (undocumented behavior and protection)
let reader = try SerializedDatabase(
path: path,
configuration: self.readerConfig,
schemaCache: sharedSchemaCache)
reader.sync { db in
for function in self.functions {
db.add(function: function)
}
for collation in self.collations {
db.add(collation: collation)
}
}
schemaCache: SimpleDatabaseSchemaCache(),
defaultLabel: "GRDB.DatabasePool",
purpose: "reader.\(readerCount)")
reader.sync { self.setupDatabase($0) }
return reader
})
}
@@ -108,6 +106,25 @@ public final class DatabasePool {
NotificationCenter.default.removeObserver(self)
}
#endif
private func setupDatabase(_ db: Database) {
for function in functions {
db.add(function: function)
}
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) }
}
}
extension DatabasePool {
@@ -122,7 +139,7 @@ extension DatabasePool {
///
/// - parameter kind: The checkpoint mode (default passive)
public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws {
try write { db in
try writer.sync { db in
// TODO: read https://www.sqlite.org/c3ref/wal_checkpoint_v2.html and
// check whether we need a busy handler on writer and/or readers
// when kind is not .Passive.
@@ -144,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.
write { $0.releaseMemory() }
readerPool.forEach { reader in
reader.sync { $0.releaseMemory() }
}
forEachConnection { $0.releaseMemory() }
readerPool.clear()
}
@@ -164,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) {
@@ -173,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 {
@@ -204,7 +225,7 @@ extension DatabasePool {
/// Changes the passphrase of an encrypted database
public func change(passphrase: String) throws {
try readerPool.clear(andThen: {
try write { try $0.change(passphrase: passphrase) }
try writer.sync { try $0.change(passphrase: passphrase) }
readerConfig.passphrase = passphrase
})
}
@@ -227,14 +248,14 @@ extension DatabasePool : DatabaseReader {
///
/// try dbPool.read { db in
/// // Those two values are guaranteed to be equal, even if the
/// // `wines` table is modified between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// // `wine` table is modified between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// }
///
/// try dbPool.read { db in
/// // Now this value may be different:
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// }
///
/// This method is *not* reentrant.
@@ -250,6 +271,8 @@ extension DatabasePool : DatabaseReader {
// The block isolation comes from the DEFERRED transaction.
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
try db.inTransaction(.deferred) {
// Reset the schema cache before running user code in snapshot isolation
db.schemaCache = SimpleDatabaseSchemaCache()
result = try block(db)
return .commit
}
@@ -267,8 +290,8 @@ extension DatabasePool : DatabaseReader {
/// try dbPool.unsafeRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// }
///
/// Cursor iteration is safe, though:
@@ -287,7 +310,11 @@ extension DatabasePool : DatabaseReader {
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
return try readerPool.get { reader in
try reader.sync(block)
try reader.sync { db in
// No schema cache when snapshot isolation is not established
db.schemaCache = EmptyDatabaseSchemaCache()
return try block(db)
}
}
}
@@ -300,8 +327,8 @@ extension DatabasePool : DatabaseReader {
/// try dbPool.unsafeReentrantRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// }
///
/// Cursor iteration is safe, though:
@@ -312,8 +339,8 @@ extension DatabasePool : DatabaseReader {
/// while let row = try rows.next() { ... }
/// }
///
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
/// This method is reentrant. It is unsafe because it fosters dangerous
/// concurrency practices.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block, or any DatabaseError that would
@@ -323,11 +350,148 @@ extension DatabasePool : DatabaseReader {
return try reader.reentrantSync(block)
} else {
return try readerPool.get { reader in
try reader.sync(block)
try reader.sync { db in
// No schema cache when snapshot isolation is not established
db.schemaCache = EmptyDatabaseSchemaCache()
return try block(db)
}
}
}
}
/// This method is deprecated. Use concurrentRead instead.
///
/// Asynchronously executes a read-only block in a protected dispatch queue,
/// wrapped in a deferred transaction.
///
/// This method must be called from the writing dispatch queue, outside of a
/// transaction. You'll get a fatal error otherwise.
///
/// The *block* argument is guaranteed to see the database in the last
/// committed state at the moment this method is called. Eventual concurrent
/// database updates are *not visible* inside the block.
///
/// try dbPool.write { db in
/// try db.execute("DELETE FROM player")
/// try dbPool.readFromCurrentState { db in
/// // Guaranteed to be zero
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM player")!
/// }
/// try db.execute("INSERT INTO player ...")
/// }
///
/// This method blocks the current thread until the isolation guarantee has
/// been established, and before the block argument has run.
///
/// - 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 {
// 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).
""")
}
// The semaphore that blocks the writing dispatch queue until snapshot
// isolation has been established:
let semaphore = DispatchSemaphore(value: 0)
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.beginSnapshotIsolation()
} catch {
futureResult = .failure(error)
isolationSemaphore.signal()
futureSemaphore.signal()
return
}
// Release the writer queue
isolationSemaphore.signal()
// Reset the schema cache before running user code in snapshot isolation
db.schemaCache = SimpleDatabaseSchemaCache()
// Fetch and release the future
futureResult = Result { try block(db) }
futureSemaphore.signal()
}
} catch {
return Future { throw error }
}
// 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? {
@@ -350,72 +514,10 @@ extension DatabasePool : DatabaseReader {
return readers.first { $0.onValidQueue }
}
// 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
/// }
/// dbPool.add(function: fn)
/// try dbPool.read { db in
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
/// }
public func add(function: DatabaseFunction) {
functions.update(with: function)
write { $0.add(function: function) }
readerPool.forEach { reader in
reader.sync { $0.add(function: function) }
}
}
/// Remove an SQL function.
public func remove(function: DatabaseFunction) {
functions.remove(function)
write { $0.remove(function: function) }
readerPool.forEach { reader in
reader.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)
/// }
/// dbPool.add(collation: collation)
/// try dbPool.write { db in
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
/// }
public func add(collation: DatabaseCollation) {
collations.update(with: collation)
write { $0.add(collation: collation) }
readerPool.forEach { reader in
reader.sync { $0.add(collation: collation) }
}
}
/// Remove a collation.
public func remove(collation: DatabaseCollation) {
collations.remove(collation)
write { $0.remove(collation: collation) }
readerPool.forEach { reader in
reader.sync { $0.remove(collation: collation) }
}
}
}
extension DatabasePool : DatabaseWriter {
// MARK: - Writing in Database
/// Synchronously executes an update block in a protected dispatch queue,
/// and returns its result.
/// wrapped inside a transaction, and returns the result of the block.
///
/// Eventual concurrent database updates are postponed until the block
/// has executed.
@@ -424,16 +526,41 @@ extension DatabasePool : DatabaseWriter {
/// try db.execute(...)
/// }
///
/// To maintain database integrity, and preserve eventual concurrent reads
/// from seeing an inconsistent database state, prefer the
/// writeInTransaction method.
/// Eventual concurrent reads are guaranteed not to see any changes
/// performed in the block until they are all saved in the database.
///
/// This method is *not* reentrant.
///
/// - parameters block: A block that executes SQL statements.
/// - throws: The error thrown by the block, or by the wrapping transaction.
public func write<T>(_ block: (Database) throws -> T) throws -> T {
return try writer.sync { db in
var result: T? = nil
try db.inTransaction {
result = try block(db)
return .commit
}
return result!
}
}
/// Synchronously executes a block that takes a database connection, and
/// returns its result.
///
/// Eventual concurrent database updates are postponed until the block
/// has executed.
///
/// Eventual concurrent reads may see changes performed in the block before
/// the block completes.
///
/// The block is guaranteed to be executed outside of a transaction.
///
/// This method is *not* reentrant.
///
/// - parameters block: A block that executes SQL statements and return
/// either .commit or .rollback.
/// - throws: The error thrown by the block.
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T {
return try writer.sync(block)
}
@@ -452,31 +579,22 @@ extension DatabasePool : DatabaseWriter {
/// return .commit
/// }
///
/// Eventual concurrent readers do not see partial changes:
///
/// dbPool.writeInTransaction { db in
/// // Eventually preserve a zero balance
/// try db.execute(db, "INSERT INTO credits ...", arguments: [amount])
/// try db.execute(db, "INSERT INTO debits ...", arguments: [amount])
/// }
///
/// dbPool.read { db in
/// // Here the balance is guaranteed to be zero
/// }
/// Eventual concurrent reads are guaranteed not to see any changes
/// performed in the block until they are all saved in the database.
///
/// This method is *not* reentrant.
///
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is configuration.defaultTransactionKind, which itself
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
/// for more information.
/// - block: A block that executes SQL statements and return either
/// .commit or .rollback.
/// - throws: The error thrown by the block, or any error establishing the
/// transaction.
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
try write { db in
try writer.sync { db in
try db.inTransaction(kind) {
try block(db)
}
@@ -493,111 +611,155 @@ extension DatabasePool : DatabaseWriter {
/// try db.execute(...)
/// }
///
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
/// Eventual concurrent reads may see changes performed in the block before
/// the block completes.
///
/// This method is reentrant. It is unsafe because it fosters dangerous
/// concurrency practices.
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
return try writer.reentrantSync(block)
}
// MARK: - Reading from Database
// MARK: - Functions
/// Asynchronously executes a read-only block in a protected dispatch queue,
/// wrapped in a deferred transaction.
/// Add or redefine an SQL function.
///
/// This method must be called from the writing dispatch queue.
///
/// 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.
///
/// try dbPool.write { db in
/// try db.execute("DELETE FROM players")
/// try dbPool.readFromCurrentState { db in
/// // Guaranteed to be zero
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
/// return nil
/// }
/// try db.execute("INSERT INTO players ...")
/// return int + 1
/// }
/// dbPool.add(function: fn)
/// try dbPool.read { db in
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
/// }
public func add(function: DatabaseFunction) {
functions.update(with: function)
forEachConnection { $0.add(function: function) }
}
/// Remove an SQL function.
public func remove(function: DatabaseFunction) {
functions.remove(function)
forEachConnection { $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)
/// }
/// dbPool.add(collation: collation)
/// try dbPool.write { db in
/// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
/// }
public func add(collation: DatabaseCollation) {
collations.update(with: collation)
forEachConnection { $0.add(collation: collation) }
}
/// Remove a collation.
public func remove(collation: DatabaseCollation) {
collations.remove(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 {
// MARK: - Snapshots
/// Creates a database snapshot.
///
/// The snapshot sees an unchanging database content, as it existed at the
/// moment it was created.
///
/// When you want to control the latest committed changes seen by a
/// snapshot, create it from the pool's writer protected dispatch queue:
///
/// let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in
/// try Player.deleteAll()
/// return try dbPool.makeSnapshot()
/// }
/// // <- Other threads may modify the database here
/// let snapshot2 = try dbPool.makeSnapshot()
///
/// try snapshot1.read { db in
/// // Guaranteed to be zero
/// try Player.fetchCount(db)
/// }
///
/// This method blocks the current thread until the isolation guarantee has
/// been established, and before the block argument has run.
/// try snapshot2.read { db in
/// // Could be anything
/// try Player.fetchCount(db)
/// }
///
/// - 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.
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
// This method must be called from the writing dispatch queue:
writer.preconditionValidQueue()
// 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
reader.async { db in
do {
try db.beginTransaction(.deferred)
assert(db.isInsideTransaction)
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next()
} catch {
readError = 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
block(db)
_ = try? db.commit() // Ignore commit error
/// It is forbidden to create a snapshot from the writer protected dispatch
/// queue when a transaction is opened, though, because it is likely a
/// programmer error:
///
/// try dbPool.write { db in
/// try db.inTransaction {
/// try Player.deleteAll()
/// // fatal error: makeSnapshot() must not be called from inside a transaction
/// let snapshot = try dbPool.makeSnapshot()
/// return .commit
/// }
/// }
///
/// To avoid this fatal error, create the snapshot *before* or *after* the
/// transaction:
///
/// try dbPool.writeWithoutTransaction { db in
/// // OK
/// let snapshot = try dbPool.makeSnapshot()
///
/// try db.inTransaction {
/// try Player.deleteAll()
/// return .commit
/// }
///
/// // OK
/// let snapshot = try dbPool.makeSnapshot()
/// }
///
/// You can create as many snapshots as you need, regardless of the maximum
/// number of reader connections in the pool.
///
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
public func makeSnapshot() throws -> DatabaseSnapshot {
// Sanity check
if writer.onValidQueue {
writer.execute { db in
GRDBPrecondition(!db.isInsideTransaction, "makeSnapshot() must not be called from inside a transaction.")
}
}
_ = semaphore.wait(timeout: .distantFuture)
if let readError = readError {
// TODO: write a test for this
throw readError
}
let snapshot = try DatabaseSnapshot(
path: path,
configuration: writer.configuration,
defaultLabel: "GRDB.DatabasePool",
purpose: "snapshot.\(snapshotCount.increment())")
snapshot.read { setupDatabase($0) }
return snapshot
}
}
+206 -157
View File
@@ -5,22 +5,22 @@ import UIKit
#endif
/// A DatabaseQueue serializes access to an SQLite database.
public final class DatabaseQueue {
private var serializedDatabase: SerializedDatabase
public final class DatabaseQueue: DatabaseWriter {
private var writer: SerializedDatabase
#if os(iOS)
private weak var application: UIApplication?
#endif
// MARK: - Configuration
/// The database configuration
public var configuration: Configuration {
return serializedDatabase.configuration
return writer.configuration
}
/// The path to the database file; it is ":memory:" for in-memory databases.
public var path: String {
return serializedDatabase.path
return writer.path
}
// MARK: - Initializers
@@ -36,10 +36,11 @@ public final class DatabaseQueue {
/// - configuration: A configuration.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public init(path: String, configuration: Configuration = Configuration()) throws {
serializedDatabase = try SerializedDatabase(
writer = try SerializedDatabase(
path: path,
configuration: configuration,
schemaCache: SimpleDatabaseSchemaCache())
schemaCache: SimpleDatabaseSchemaCache(),
defaultLabel: "GRDB.DatabaseQueue")
}
/// Opens an in-memory SQLite database.
@@ -51,10 +52,11 @@ public final class DatabaseQueue {
/// - parameter configuration: A configuration.
public init(configuration: Configuration = Configuration()) {
// Assume SQLite always succeeds creating an in-memory database
serializedDatabase = try! SerializedDatabase(
writer = try! SerializedDatabase(
path: ":memory:",
configuration: configuration,
schemaCache: SimpleDatabaseSchemaCache())
schemaCache: SimpleDatabaseSchemaCache(),
defaultLabel: "GRDB.DatabaseQueue")
}
#if os(iOS)
@@ -68,56 +70,6 @@ public final class DatabaseQueue {
#endif
}
extension DatabaseQueue {
// MARK: - Database Access
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
/// let players = try dbQueue.inDatabase { db in
/// try Player.fetchAll(...)
/// }
///
/// This method is *not* reentrant.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func inDatabase<T>(_ block: (Database) throws -> T) rethrows -> T {
return try serializedDatabase.sync(block)
}
/// Synchronously executes a block in a protected dispatch queue, wrapped
/// inside a transaction.
///
/// If the block throws an error, the transaction is rollbacked and the
/// error is rethrown. If the block returns .rollback, the transaction is
/// also rollbacked, but no error is thrown.
///
/// try dbQueue.inTransaction { db in
/// db.execute(...)
/// return .commit
/// }
///
/// This method is *not* reentrant.
///
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is configuration.defaultTransactionKind, which itself
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
/// for more information.
/// - block: A block that executes SQL statements and return either
/// .commit or .rollback.
/// - throws: The error thrown by the block.
public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
try inDatabase { db in
try db.inTransaction(kind) {
try block(db)
}
}
}
}
extension DatabaseQueue {
// MARK: - Memory management
@@ -128,7 +80,7 @@ extension DatabaseQueue {
///
/// See also setupMemoryManagement(application:)
public func releaseMemory() {
inDatabase { $0.releaseMemory() }
writer.sync { $0.releaseMemory() }
}
#if os(iOS)
@@ -142,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) {
@@ -151,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 {
@@ -181,60 +141,205 @@ extension DatabaseQueue {
/// Changes the passphrase of an encrypted database
public func change(passphrase: String) throws {
try inDatabase { try $0.change(passphrase: passphrase) }
try writer.sync { try $0.change(passphrase: passphrase) }
}
}
#endif
extension DatabaseQueue : DatabaseReader {
extension DatabaseQueue {
// MARK: - Reading from Database
// MARK: - DatabaseReader Protocol Adoption
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result.
///
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(...)
/// try Player.fetchAll(db)
/// }
///
/// This method is *not* reentrant.
///
/// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and
/// SQLCipher, attempts to write in the database throw a DatabaseError whose
/// resultCode is `SQLITE_READONLY`.
/// 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`.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
return try inDatabase { try readOnly($0, block) }
#else
if #available(iOS 8.2, OSX 10.10, *) {
return try inDatabase { try readOnly($0, block) }
} else {
return try inDatabase(block)
}
#endif
}
/// Alias for `inDatabase`. See `DatabaseReader.unsafeRead`.
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
return try inDatabase(block)
return try writer.sync { db in
try db.readOnly { try block(db) }
}
}
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
/// try dbQueue.unsafeReentrantRead { db in
/// try db.execute(...)
/// let players = try dbQueue.unsafeRead { db in
/// try Player.fetchAll(db)
/// }
///
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try serializedDatabase.reentrantSync(block)
/// This method is *not* reentrant.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
///
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
return try writer.sync(block)
}
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
/// let players = try dbQueue.unsafeReentrantRead { db in
/// try Player.fetchAll(db)
/// }
///
/// This method is reentrant. It is unsafe because it fosters dangerous
/// concurrency practices.
///
/// :nodoc:
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,
/// outside of a transaction. You'll get a fatal error otherwise.
///
/// 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`.
@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
// ... and that no transaction is opened.
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.")
db.readOnly { block(db) }
}
}
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
/// inside a transaction.
///
/// If the block throws an error, the transaction is rollbacked and the
/// error is rethrown.
///
/// try dbQueue.write { db in
/// try Player(...).insert(db)
/// }
///
/// This method is *not* reentrant.
///
/// - 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) throws -> T {
return try writer.sync { db in
var result: T? = nil
try db.inTransaction {
result = try block(db)
return .commit
}
return result!
}
}
/// Synchronously executes a block in a protected dispatch queue, wrapped
/// inside a transaction.
///
/// If the block throws an error, the transaction is rollbacked and the
/// error is rethrown. If the block returns .rollback, the transaction is
/// also rollbacked, but no error is thrown.
///
/// try dbQueue.inTransaction { db in
/// try Player(...).insert(db)
/// return .commit
/// }
///
/// This method is *not* reentrant.
///
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is configuration.defaultTransactionKind, which itself
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
/// for more information.
/// - block: A block that executes SQL statements and return either
/// .commit or .rollback.
/// - throws: The error thrown by the block.
public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
try writer.sync { db in
try db.inTransaction(kind) {
try block(db)
}
}
}
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
/// let players = try dbQueue.writeWithoutTransaction { db in
/// try Player(...).insert(db)
/// }
///
/// This method is *not* reentrant.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
///
/// :nodoc:
public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T {
return try writer.sync(block)
}
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
/// // INSERT INTO player ...
/// let players = try dbQueue.inDatabase { db in
/// try Player(...).insert(db)
/// }
///
/// This method is *not* reentrant.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func inDatabase<T>(_ block: (Database) throws -> T) rethrows -> T {
return try writer.sync(block)
}
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
/// // INSERT INTO player ...
/// try dbQueue.unsafeReentrantWrite { db in
/// try Player(...).insert(db)
/// }
///
/// This method is reentrant. It is unsafe because it fosters dangerous
/// concurrency practices.
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
return try writer.reentrantSync(block)
}
// MARK: - Functions
@@ -248,16 +353,16 @@ extension DatabaseQueue : DatabaseReader {
/// return int + 1
/// }
/// dbQueue.add(function: fn)
/// try dbQueue.inDatabase { db in
/// try dbQueue.read { db in
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
/// }
public func add(function: DatabaseFunction) {
inDatabase { $0.add(function: function) }
writer.sync { $0.add(function: function) }
}
/// Remove an SQL function.
public func remove(function: DatabaseFunction) {
inDatabase { $0.remove(function: function) }
writer.sync { $0.remove(function: function) }
}
// MARK: - Collations
@@ -268,71 +373,15 @@ extension DatabaseQueue : DatabaseReader {
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// dbQueue.add(collation: collation)
/// try dbQueue.inDatabase { db in
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
/// try dbQueue.write { db in
/// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
/// }
public func add(collation: DatabaseCollation) {
inDatabase { $0.add(collation: collation) }
writer.sync { $0.add(collation: collation) }
}
/// Remove a collation.
public func remove(collation: DatabaseCollation) {
inDatabase { $0.remove(collation: collation) }
writer.sync { $0.remove(collation: collation) }
}
}
extension DatabaseQueue : DatabaseWriter {
// MARK: - DatabaseWriter Protocol Adoption
/// Alias for `inDatabase`. See `DatabaseWriter.write`.
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
return try inDatabase(block)
}
/// Synchronously executes *block*.
///
/// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and
/// SQLCipher, attempts to write in the database throw a DatabaseError whose
/// resultCode is `SQLITE_READONLY`.
///
/// This method must be called from the protected database dispatch queue.
/// See `DatabaseWriter.readFromCurrentState`.
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
serializedDatabase.execute { readOnly($0, block) }
#else
if #available(iOS 8.2, OSX 10.10, *) {
serializedDatabase.execute { readOnly($0, block) }
} else {
serializedDatabase.execute(block)
}
#endif
}
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
/// try dbQueue.unsafeReentrantWrite { db in
/// try db.execute(...)
/// }
///
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
return try serializedDatabase.reentrantSync(block)
}
}
private func readOnly<T>(_ db: Database, _ block: (Database) throws -> T) rethrows -> T {
guard !db.configuration.readonly else {
return try block(db)
}
// Assume those pragmas never fail
try! db.execute("PRAGMA query_only = 1")
defer { try! db.execute("PRAGMA query_only = 0") }
return try block(db)
}
+56 -44
View File
@@ -31,14 +31,14 @@ public protocol DatabaseReader : class {
///
/// try reader.read { db in
/// // Those two values are guaranteed to be equal, even if the
/// // `wines` table is modified between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// // `wine` table is modified between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// }
///
/// try reader.read { db in
/// // Now this value may be different:
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// }
///
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
@@ -61,8 +61,8 @@ public protocol DatabaseReader : class {
/// try reader.unsafeRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// }
///
/// Cursor iterations are isolated, though:
@@ -92,8 +92,8 @@ public protocol DatabaseReader : class {
/// try reader.unsafeReentrantRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// }
///
/// Cursor iterations are isolated, though:
@@ -144,11 +144,32 @@ public protocol DatabaseReader : class {
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// reader.add(collation: collation)
/// try reader.execute("SELECT * FROM files ORDER BY name COLLATE localized_standard")
/// try reader.execute("SELECT * FROM file ORDER BY name COLLATE localized_standard")
func add(collation: DatabaseCollation)
/// 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 {
@@ -169,41 +190,8 @@ extension DatabaseReader {
func backup(to writer: DatabaseWriter, afterBackupInit: (() -> ())?, afterBackupStep: (() -> ())?) throws {
try read { dbFrom in
try writer.write { dbDest in
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else {
throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
}
guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else {
throw DatabaseError(resultCode: .SQLITE_ERROR)
}
afterBackupInit?()
do {
backupLoop: while true {
switch sqlite3_backup_step(backup, -1) {
case SQLITE_DONE:
afterBackupStep?()
break backupLoop
case SQLITE_OK:
afterBackupStep?()
case let code:
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
}
}
} catch {
sqlite3_backup_finish(backup)
throw error
}
switch sqlite3_backup_finish(backup) {
case SQLITE_OK:
break
case let code:
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
}
dbDest.clearSchemaCache()
try writer.writeWithoutTransaction { dbDest in
try Database.backup(from: dbFrom, to: dbDest, afterBackupInit: afterBackupInit, afterBackupStep: afterBackupStep)
}
}
}
@@ -223,35 +211,59 @@ public final class AnyDatabaseReader : DatabaseReader {
// MARK: - Reading from Database
/// :nodoc:
public func read<T>(_ block: (Database) throws -> T) throws -> T {
return try base.read(block)
}
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeRead(block)
}
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeReentrantRead(block)
}
// MARK: - Functions
/// :nodoc:
public func add(function: DatabaseFunction) {
base.add(function: function)
}
/// :nodoc:
public func remove(function: DatabaseFunction) {
base.remove(function: function)
}
// MARK: - Collations
/// :nodoc:
public func add(collation: DatabaseCollation) {
base.add(collation: collation)
}
/// :nodoc:
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
// 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)
}
}
+364
View File
@@ -0,0 +1,364 @@
/// DatabaseRegion defines a region in the database. DatabaseRegion is dedicated
/// to help transaction observers recognize impactful database changes in their
/// `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods.
///
/// A database region is the union of any number of "table regions", which can
/// cover a full table, or the combination of columns and rows (identified by
/// their rowids):
///
/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 |
/// |-------| |-------| |-------| |-------| |-------|
/// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | |
/// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | |
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
///
/// You don't create a database region directly. Instead, you use one of
/// those methods:
///
/// - `SelectStatement.databaseRegion`:
///
/// 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]"
///
/// Database regions returned by requests can be more precise than regions
/// returned by select statements. Especially, regions returned by statements
/// don't know about rowids:
///
/// // A plain statement
/// let statement = db.makeSelectStatement("SELECT * FROM player WHERE id = 1")
/// statement.databaseRegion // "player(*)"
///
/// // A query interface request that executes the same statement:
/// let request = Player.filter(key: 1)
/// try request.databaseRegion(db) // "player(*)[1]"
public struct DatabaseRegion: CustomStringConvertible, Equatable {
private let tableRegions: [String: TableRegion]?
private init(tableRegions: [String: TableRegion]?) {
self.tableRegions = tableRegions
}
/// Returns whether the region is empty.
public var isEmpty: Bool {
guard let tableRegions = tableRegions else {
// full database
return false
}
return tableRegions.isEmpty
}
/// The region that covers the full database: all columns and all rows
/// from all tables.
public static let fullDatabase = DatabaseRegion(tableRegions: nil)
/// The empty database region
public init() {
self.init(tableRegions: [:])
}
/// A full table: (all columns in the table) × (all rows)
init(table: String) {
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
}
/// Full columns in a table: (some columns in a table) × (all rows)
init(table: String, columns: Set<String>) {
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)])
}
/// Full rows in a table: (all columns in a table) × (some rows)
init(table: String, rowIds: Set<Int64>) {
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)])
}
/// Returns the intersection of this region and the given one.
///
/// This method is not public because there is no known public use case for
/// this intersection. It is currently only used as support for
/// the isModified(byEventsOfKind:) method.
func intersection(_ other: DatabaseRegion) -> DatabaseRegion {
guard let tableRegions = tableRegions else { return other }
guard let otherTableRegions = other.tableRegions else { return self }
var tableRegionsIntersection: [String: TableRegion] = [:]
for (table, tableRegion) in tableRegions {
guard let otherTableRegion = otherTableRegions
.first(where: { (otherTable, _) in otherTable == table })?
.value else { continue }
let tableRegionIntersection = tableRegion.intersection(otherTableRegion)
guard !tableRegionIntersection.isEmpty else { continue }
tableRegionsIntersection[table] = tableRegionIntersection
}
return DatabaseRegion(tableRegions: tableRegionsIntersection)
}
/// Only keeps those rowIds in the given table
func tableIntersection(_ table: String, rowIds: Set<Int64>) -> DatabaseRegion {
guard var tableRegions = tableRegions else {
return DatabaseRegion(table: table, rowIds: rowIds)
}
guard let tableRegion = tableRegions[table] else {
return self
}
let intersection = tableRegion.intersection(TableRegion(columns: nil, rowIds: rowIds))
if intersection.isEmpty {
tableRegions.removeValue(forKey: table)
} else {
tableRegions[table] = intersection
}
return DatabaseRegion(tableRegions: tableRegions)
}
/// Returns the union of this region and the given one.
public func union(_ other: DatabaseRegion) -> DatabaseRegion {
guard let tableRegions = tableRegions else { return .fullDatabase }
guard let otherTableRegions = other.tableRegions else { return .fullDatabase }
var tableRegionsUnion: [String: TableRegion] = [:]
let tableNames = Set(tableRegions.keys).union(Set(otherTableRegions.keys))
for table in tableNames {
let tableRegion = tableRegions[table]
let otherTableRegion = otherTableRegions[table]
let tableRegionUnion: TableRegion
switch (tableRegion, otherTableRegion) {
case (nil, nil):
preconditionFailure()
case (nil, let tableRegion?), (let tableRegion?, nil):
tableRegionUnion = tableRegion
case (let tableRegion?, let otherTableRegion?):
tableRegionUnion = tableRegion.union(otherTableRegion)
}
tableRegionsUnion[table] = tableRegionUnion
}
return DatabaseRegion(tableRegions: tableRegionsUnion)
}
/// Inserts the given region into this region
public mutating func formUnion(_ other: DatabaseRegion) {
self = union(other)
}
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 {
// MARK: - Database Events
/// Returns whether the content in the region would be impacted if the
/// database were modified by an event of this kind.
public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool {
return intersection(eventKind.modifiedRegion).isEmpty == false
}
/// Returns whether the content in the region is impacted by this event.
///
/// - precondition: event has been filtered by the same region
/// in the TransactionObserver.observes(eventsOfKind:) method, by calling
/// region.isModified(byEventsOfKind:)
public func isModified(by event: DatabaseEvent) -> Bool {
guard let tableRegions = tableRegions else {
// Full database: all changes are impactful
return true
}
if tableRegions.count == 1 {
// Fast path when the region contains a single table.
//
// 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:)")
}
return tableRegion.contains(rowID: event.rowID)
}
}
}
// Equatable
extension DatabaseRegion {
/// :nodoc:
public static func == (lhs: DatabaseRegion, rhs: DatabaseRegion) -> Bool {
switch (lhs.tableRegions, rhs.tableRegions) {
case (nil, nil):
return true
case (let ltableRegions?, let rtableRegions?):
let ltableNames = Set(ltableRegions.keys)
let rtableNames = Set(rtableRegions.keys)
guard ltableNames == rtableNames else {
return false
}
for tableName in ltableNames {
if ltableRegions[tableName]! != rtableRegions[tableName]! {
return false
}
}
return true
default:
return false
}
}
}
// CustomStringConvertible
extension DatabaseRegion {
/// :nodoc:
public var description: String {
guard let tableRegions = tableRegions else {
return "full database"
}
if tableRegions.isEmpty {
return "empty"
}
return tableRegions
.sorted(by: { (l, r) in l.key < r.key })
.map { (table, tableRegion) in
var desc = table
if let columns = tableRegion.columns {
desc += "(" + columns.sorted().joined(separator: ",") + ")"
} else {
desc += "(*)"
}
if let rowIds = tableRegion.rowIds {
desc += "[" + rowIds.sorted().map { "\($0)" }.joined(separator: ",") + "]"
}
return desc
}
.joined(separator: ",")
}
}
private struct TableRegion: Equatable {
var columns: Set<String>? // nil means "all columns"
var rowIds: Set<Int64>? // nil means "all rowids"
var isEmpty: Bool {
if let columns = columns, columns.isEmpty { return true }
if let rowIds = rowIds, rowIds.isEmpty { return true }
return false
}
func intersection(_ other: TableRegion) -> TableRegion {
let columnsIntersection: Set<String>?
switch (self.columns, other.columns) {
case (nil, let columns), (let columns, nil):
columnsIntersection = columns
case (let columns?, let other?):
columnsIntersection = columns.intersection(other)
}
let rowIdsIntersection: Set<Int64>?
switch (self.rowIds, other.rowIds) {
case (nil, let rowIds), (let rowIds, nil):
rowIdsIntersection = rowIds
case (let rowIds?, let other?):
rowIdsIntersection = rowIds.intersection(other)
}
return TableRegion(columns: columnsIntersection, rowIds: rowIdsIntersection)
}
func union(_ other: TableRegion) -> TableRegion {
let columnsUnion: Set<String>?
switch (self.columns, other.columns) {
case (nil, _), (_, nil):
columnsUnion = nil
case (let columns?, let other?):
columnsUnion = columns.union(other)
}
let rowIdsUnion: Set<Int64>?
switch (self.rowIds, other.rowIds) {
case (nil, _), (_, nil):
rowIdsUnion = nil
case (let rowIds?, let other?):
rowIdsUnion = rowIds.union(other)
}
return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion)
}
@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
}
}
+25 -45
View File
@@ -1,12 +1,9 @@
/// The protocol for schema cache.
///
/// This protocol must not contain values that are valid for a single connection
/// only, because several connections can share the same schema cache.
///
/// Statements can't be cached here, for example.
/// The protocol for database schema cache.
protocol DatabaseSchemaCache {
mutating func clear()
var schemaInfo: SchemaInfo? { get set }
func primaryKey(_ table: String) -> PrimaryKeyInfo?
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String)
@@ -21,24 +18,26 @@ protocol DatabaseSchemaCache {
}
/// A thread-unsafe database schema cache
final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
var schemaInfo: SchemaInfo?
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
private var columns: [String: [ColumnInfo]] = [:]
private var indexes: [String: [IndexInfo]] = [:]
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
func clear() {
mutating func clear() {
primaryKeys = [:]
columns = [:]
indexes = [:]
foreignKeys = [:]
schemaInfo = nil
}
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
return primaryKeys[table]
}
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
primaryKeys[table] = primaryKey
}
@@ -46,7 +45,7 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
return columns[table]
}
func set(columns: [ColumnInfo], forTable table: String) {
mutating func set(columns: [ColumnInfo], forTable table: String) {
self.columns[table] = columns
}
@@ -54,7 +53,7 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
return indexes[table]
}
func set(indexes: [IndexInfo], forTable table: String) {
mutating func set(indexes: [IndexInfo], forTable table: String) {
self.indexes[table] = indexes
}
@@ -62,48 +61,29 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
return foreignKeys[table]
}
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
self.foreignKeys[table] = foreignKeys
}
}
/// A thread-safe database schema cache
final class SharedDatabaseSchemaCache: DatabaseSchemaCache {
private let cache = ReadWriteBox(SimpleDatabaseSchemaCache())
/// An always empty database schema cache
struct EmptyDatabaseSchemaCache: DatabaseSchemaCache {
func clear() { }
func clear() {
cache.write { $0.clear() }
var schemaInfo: SchemaInfo? {
get { return nil }
set { }
}
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
return cache.read { $0.primaryKey(table) }
}
func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil }
func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
cache.write { $0.set(primaryKey: primaryKey, forTable: table) }
}
func columns(in table: String) -> [ColumnInfo]? { return nil }
func set(columns: [ColumnInfo], forTable table: String) { }
func columns(in table: String) -> [ColumnInfo]? {
return cache.read { $0.columns(in: table) }
}
func indexes(on table: String) -> [IndexInfo]? { return nil }
func set(indexes: [IndexInfo], forTable table: String) { }
func set(columns: [ColumnInfo], forTable table: String) {
cache.write { $0.set(columns: columns, forTable: table) }
}
func indexes(on table: String) -> [IndexInfo]? {
return cache.read { $0.indexes(on: table) }
}
func set(indexes: [IndexInfo], forTable table: String) {
cache.write { $0.set(indexes: indexes, forTable: table) }
}
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
return cache.read { $0.foreignKeys(on: table) }
}
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
cache.write { $0.set(foreignKeys: foreignKeys, forTable: table) }
}
func foreignKeys(on table: String) -> [ForeignKeyInfo]? { return nil }
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { }
}
+160
View File
@@ -0,0 +1,160 @@
import Dispatch
/// A DatabaseSnapshot sees an unchanging database content, as it existed at the
/// moment it was created.
///
/// See DatabasePool.makeSnapshot()
///
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
public class DatabaseSnapshot : DatabaseReader {
private var serializedDatabase: SerializedDatabase
/// The database configuration
var configuration: Configuration {
return serializedDatabase.configuration
}
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
serializedDatabase = try SerializedDatabase(
path: path,
configuration: configuration,
schemaCache: SimpleDatabaseSchemaCache(),
defaultLabel: defaultLabel,
purpose: purpose)
try serializedDatabase.sync { db in
// Assert WAL mode
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode")
guard journalMode == "wal" else {
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
}
try db.beginSnapshotIsolation()
}
}
deinit {
// Leave snapshot isolation
serializedDatabase.sync { db in
try? db.commit()
}
}
}
// DatabaseReader
extension DatabaseSnapshot {
// MARK: - Reading from Database
/// Synchronously executes a read-only block that takes a database
/// connection, and returns its result.
///
/// let players = try snapshot.read { db in
/// try Player.fetchAll(...)
/// }
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
return try serializedDatabase.sync(block)
}
/// Alias for `read`. See `DatabaseReader.unsafeRead`.
///
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
return try serializedDatabase.sync(block)
}
/// Alias for `read`. See `DatabaseReader.unsafeReentrantRead`.
///
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try serializedDatabase.sync(block)
}
// MARK: - Functions
public func add(function: DatabaseFunction) {
serializedDatabase.sync { $0.add(function: function) }
}
public func remove(function: DatabaseFunction) {
serializedDatabase.sync { $0.remove(function: function) }
}
// MARK: - Collations
public func add(collation: DatabaseCollation) {
serializedDatabase.sync { $0.add(collation: 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) { }
}
+60 -48
View File
@@ -10,7 +10,7 @@ import Foundation
/// DatabaseValue is the intermediate type between SQLite and your values.
///
/// See https://www.sqlite.org/datatype3.html
public struct DatabaseValue {
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpression {
/// The SQLite storage
public let storage: Storage
@@ -121,18 +121,18 @@ public struct DatabaseValue {
/// 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())
@@ -146,9 +146,28 @@ public struct DatabaseValue {
// MARK: - Hashable & Equatable
extension DatabaseValue : Hashable {
// 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 {
case .null:
@@ -164,6 +183,7 @@ extension DatabaseValue : Hashable {
return data.hashValue
}
}
#endif
/// Returns whether two DatabaseValues are equal.
///
@@ -205,6 +225,7 @@ extension DatabaseValue : Hashable {
// 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
@@ -224,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
@@ -258,29 +269,12 @@ 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) })
}
}
extension DatabaseValue : DatabaseValueConvertible {
// DatabaseValueConvertible
extension DatabaseValue {
/// Returns self
public var databaseValue: DatabaseValue {
return self
@@ -292,23 +286,26 @@ extension DatabaseValue : DatabaseValueConvertible {
}
}
extension DatabaseValue : SQLExpressible {
// SQLExpressible
extension DatabaseValue {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var sqlExpression: SQLExpression {
return self
}
}
extension DatabaseValue : SQLExpression {
// SQLExpression
extension DatabaseValue {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
/// :nodoc:
public func expressionSQL(_ context: inout SQLGenerationContext) -> String {
// fast path for NULL
if isNull {
return "NULL"
}
if arguments != nil {
arguments!.values.append(self)
if context.appendArguments([self]) {
return "?"
} else {
// Correctness above all: use SQLite to quote the value.
@@ -318,6 +315,7 @@ extension DatabaseValue : SQLExpression {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var negated: SQLExpression {
switch storage {
case .null:
@@ -341,9 +339,23 @@ extension DatabaseValue : SQLExpression {
return SQLExpressionNot(self)
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
return self
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
return self
}
}
extension DatabaseValue : CustomStringConvertible {
// CustomStringConvertible
extension DatabaseValue {
/// :nodoc:
public var description: String {
switch storage {
case .null:
@@ -355,7 +367,7 @@ extension DatabaseValue : CustomStringConvertible {
case .string(let string):
return String(reflecting: string)
case .blob(let data):
return data.description
return "Data(\(data.description))"
}
}
}
+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)
}
}
+257 -121
View File
@@ -32,6 +32,7 @@ public protocol DatabaseValueConvertible : SQLExpressible {
extension DatabaseValueConvertible {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var sqlExpression: SQLExpression {
return databaseValue
}
@@ -40,8 +41,8 @@ extension DatabaseValueConvertible {
/// A cursor of database values extracted from a single column.
/// For example:
///
/// try dbQueue.inDatabase { db in
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, "SELECT url FROM links")
/// try dbQueue.read { db in
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, "SELECT url FROM link")
/// while let url = urls.next() { // URL
/// print(url)
/// }
@@ -54,24 +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)
}
}
}
@@ -79,8 +101,8 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor
/// A cursor of optional database values extracted from a single column.
/// For example:
///
/// try dbQueue.inDatabase { db in
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, "SELECT url FROM links")
/// try dbQueue.read { db in
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, "SELECT url FROM link")
/// while let url = urls.next() { // URL?
/// print(url)
/// }
@@ -93,24 +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)
}
}
}
@@ -191,64 +234,6 @@ extension DatabaseValueConvertible {
}
}
extension DatabaseValueConvertible {
// MARK: Fetching From Request
/// Returns a cursor over values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let names = try String.fetchCursor(db, request) // Cursor of String
/// for let name = try names.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - request: A fetch request.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseValueCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let names = try String.fetchAll(db, request) // [String]
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
/// Returns a single value fetched from a fetch request.
///
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let name = try String.fetchOne(db, request) // String?
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? {
let (statement, adapter) = try request.prepare(db)
return try fetchOne(statement, adapter: adapter)
}
}
extension DatabaseValueConvertible {
// MARK: Fetching From SQL
@@ -273,7 +258,7 @@ extension DatabaseValueConvertible {
/// - 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 -> DatabaseValueCursor<Self> {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of values fetched from an SQL query.
@@ -288,7 +273,7 @@ extension DatabaseValueConvertible {
/// - returns: An array.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from an SQL query.
@@ -306,10 +291,122 @@ extension DatabaseValueConvertible {
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
return try fetchOne(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
}
}
extension DatabaseValueConvertible {
// MARK: Fetching From FetchRequest
/// Returns a cursor over values fetched from a fetch request.
///
/// let request = Player.select(Column("name"))
/// let names = try String.fetchCursor(db, request) // Cursor of String
/// while let name = try name.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - 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 -> DatabaseValueCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of values fetched from a fetch request.
///
/// let request = Player.select(Column("name"))
/// let names = try String.fetchAll(db, request) // [String]
///
/// - parameters:
/// - db: A database connection.
/// - request: A FetchRequest.
/// - returns: An array.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Self] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
/// Returns a single value fetched from a fetch request.
///
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let request = Player.filter(key: 1).select(Column("name"))
/// let name = try String.fetchOne(db, request) // String?
///
/// - parameters:
/// - db: A database connection.
/// - request: A FetchRequest.
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> Self? {
let (statement, adapter) = try request.prepare(db)
return try fetchOne(statement, adapter: adapter)
}
}
extension FetchRequest where RowDecoder: DatabaseValueConvertible {
// MARK: Fetching Values
/// A cursor over fetched values.
///
/// let request: ... // Some TypedRequest that fetches String
/// let strings = try request.fetchCursor(db) // Cursor of String
/// while let string = try strings.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - 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 -> DatabaseValueCursor<RowDecoder> {
return try RowDecoder.fetchCursor(db, self)
}
/// An array of fetched values.
///
/// let request: ... // Some TypedRequest that fetches String
/// let strings = try request.fetchAll(db) // [String]
///
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
return try RowDecoder.fetchAll(db, self)
}
/// The first fetched value.
///
/// The result is nil if the request returns no row, or if no value can be
/// extracted from the first row.
///
/// let request: ... // Some TypedRequest that fetches String
/// let string = try request.fetchOne(db) // String?
///
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
return try RowDecoder.fetchOne(db, self)
}
}
/// Swift's Optional comes with built-in methods that allow to fetch cursors
/// and arrays of optional DatabaseValueConvertible:
@@ -365,48 +462,6 @@ extension Optional where Wrapped: DatabaseValueConvertible {
}
}
extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: Fetching From Request
/// Returns a cursor over optional values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - requet: A fetch request.
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableDatabaseValueCursor<Wrapped> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of optional values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
}
extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: Fetching From SQL
@@ -431,7 +486,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - 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 -> NullableDatabaseValueCursor<Wrapped> {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of optional values fetched from an SQL query.
@@ -446,6 +501,87 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
}
}
extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: Fetching From FetchRequest
/// Returns a cursor over optional values fetched from a fetch request.
///
/// let request = Player.select(Column("name"))
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - 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 -> NullableDatabaseValueCursor<Wrapped> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of optional values fetched from a fetch request.
///
/// let request = Player.select(Column("name"))
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
///
/// - parameters:
/// - db: A database connection.
/// - request: A FetchRequest.
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Wrapped?] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
}
extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
// MARK: Fetching Optional values
/// A cursor over fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let strings = try request.fetchCursor(db) // Cursor of String?
/// while let string = try strings.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - 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 -> NullableDatabaseValueCursor<RowDecoder._Wrapped> {
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
}
/// An array of fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let strings = try request.fetchAll(db) // [String?]
///
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
}
}
+289 -60
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.
@@ -23,8 +25,13 @@ public protocol DatabaseWriter : DatabaseReader {
/// Eventual concurrent database updates are postponed until the block
/// has executed.
///
/// Eventual concurrent reads are guaranteed not to see any changes
/// performed in the block until they are all saved in the database.
///
/// The block may, or may not, be wrapped inside a transaction.
///
/// This method is *not* reentrant.
func write<T>(_ block: (Database) throws -> T) rethrows -> T
func write<T>(_ block: (Database) throws -> T) throws -> T
/// Synchronously executes a block that takes a database connection, and
/// returns its result.
@@ -32,75 +39,87 @@ public protocol DatabaseWriter : DatabaseReader {
/// Eventual concurrent database updates are postponed until the block
/// has executed.
///
/// Eventual concurrent reads may see changes performed in the block before
/// the block completes.
///
/// The block is guaranteed to be executed outside of a transaction.
///
/// This method is *not* reentrant.
func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T
/// Synchronously executes a block that takes a database connection, and
/// returns its result.
///
/// Eventual concurrent database updates are postponed until the block
/// has executed.
///
/// Eventual concurrent reads may see changes performed in the block before
/// the block completes.
///
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T
// MARK: - Reading from Database
/// This method is deprecated. Use concurrentRead instead.
///
/// Synchronously or asynchronously executes a read-only block that takes a
/// database connection.
///
/// This method must be called from a writing dispatch queue.
/// This method must be called from a writing dispatch queue, outside of any
/// transaction. You'll get a fatal error otherwise.
///
/// The *block* argument is guaranteed to see the database in the state it
/// has at the moment this method is called (see below). Eventual concurrent
/// The *block* argument is guaranteed to see the database in the last
/// committed state at the moment this method is called. Eventual concurrent
/// database updates are *not visible* inside the block.
///
/// What is the "current state" of the database?
/// For example:
///
/// - When this method is called outside of any transaction, the current
/// state is the last committed state.
///
/// try writer.write { db in
/// try db.execute("DELETE FROM players")
/// try writer.readFromCurrentState { db in
/// // Guaranteed to be zero
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
/// }
/// try db.execute("INSERT INTO players ...")
/// try writer.writeWithoutTransaction { db in
/// try db.execute("DELETE FROM player")
/// try writer.readFromCurrentState { db in
/// // Guaranteed to be zero
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM player")!
/// }
///
/// - When this method is called inside an uncommitted transation, the
/// current state depends on the caller:
///
/// DatabasePool.readFromCurrentState runs *block* asynchronously in a
/// concurrent reader dispatch queue, and release the writing dispatch
/// queue early, before the block has finished. In the example below,
/// the insertion runs concurrently with the select, and the select sees
/// the database in its last committed state.
///
/// try dbPool.write { db in
/// try db.execute("DELETE FROM players")
/// db.inTransaction {
/// try db.execute("INSERT INTO players ...")
/// try dbPool.readFromCurrentState { db in
/// // Zero
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
/// }
/// return .commit
/// }
/// }
///
/// DatabaseQueue.readFromCurrentState simply runs *block* synchronously,
/// and returns when the block has completed. In the example below, the
/// select sees the uncommitted state of the database, and the insertion
/// is run after the select.
///
/// try dbQueue.write { db in
/// try db.execute("DELETE FROM players")
/// db.inTransaction {
/// try db.execute("INSERT INTO players ...")
/// try dbQueue.readFromCurrentState { db in
/// // One
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
/// }
/// return .commit
/// }
/// }
///
/// This method is *not* reentrant.
/// try db.execute("INSERT INTO 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 {
@@ -110,17 +129,206 @@ 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
/// is deallocated).
public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) {
write { $0.add(transactionObserver: transactionObserver, extent: extent) }
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
}
/// Remove a transaction observer.
/// Default implementation for the DatabaseReader requirement.
/// :nodoc:
public func remove(transactionObserver: TransactionObserver) {
write { $0.remove(transactionObserver: transactionObserver) }
writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) }
}
// MARK: - Erasing the content of the database
/// Erases the content of the database.
///
/// - precondition: database is not accessed concurrently during the
/// execution of this method.
public func erase() throws {
#if SQLITE_HAS_CODEC
// SQLCipher does not support the backup API: https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
// So we'll drop all database objects one after the other.
try writeWithoutTransaction { db in
// Prevent foreign keys from messing with drop table statements
let foreignKeysEnabled = try Bool.fetchOne(db, "PRAGMA foreign_keys")!
if foreignKeysEnabled {
try db.execute("PRAGMA foreign_keys = OFF")
}
// Remove all database objects, one after the other
do {
try db.inTransaction {
while let row = try Row.fetchOne(db, "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'") {
let type: String = row["type"]
let name: String = row["name"]
try db.execute("DROP \(type) \(name.quotedDatabaseIdentifier)")
}
return .commit
}
// Restore foreign keys if needed
if foreignKeysEnabled {
try db.execute("PRAGMA foreign_keys = ON")
}
} catch {
// Restore foreign keys if needed
if foreignKeysEnabled {
try? db.execute("PRAGMA foreign_keys = ON")
}
throw error
}
}
#else
try DatabaseQueue().backup(to: self)
#endif
}
// MARK: - Claiming Disk Space
/// Rebuilds the database file, repacking it into a minimal amount of
/// disk space.
///
/// See https://www.sqlite.org/lang_vacuum.html for more information.
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()
}
}
@@ -138,48 +346,69 @@ public final class AnyDatabaseWriter : DatabaseWriter {
// MARK: - Reading from Database
/// :nodoc:
public func read<T>(_ block: (Database) throws -> T) throws -> T {
return try base.read(block)
}
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeRead(block)
}
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeReentrantRead(block)
}
/// :nodoc:
@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
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
/// :nodoc:
public func write<T>(_ block: (Database) throws -> T) throws -> T {
return try base.write(block)
}
/// :nodoc:
public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T {
return try base.writeWithoutTransaction(block)
}
/// :nodoc:
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
return try base.unsafeReentrantWrite(block)
}
// MARK: - Functions
/// :nodoc:
public func add(function: DatabaseFunction) {
base.add(function: function)
}
/// :nodoc:
public func remove(function: DatabaseFunction) {
base.remove(function: function)
}
// MARK: - Collations
/// :nodoc:
public func add(collation: DatabaseCollation) {
base.add(collation: collation)
}
/// :nodoc:
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
+250
View File
@@ -0,0 +1,250 @@
// MARK: - FetchRequest
/// The protocol for all requests that run from a single select statement, and
/// tell how fetched rows should be interpreted.
///
/// struct Player: FetchableRecord { ... }
/// let request: ... // Some FetchRequest that fetches Player
/// try request.fetchCursor(db) // Cursor of Player
/// try request.fetchAll(db) // [Player]
/// try request.fetchOne(db) // Player?
public protocol FetchRequest: DatabaseRegionConvertible {
/// The type that tells how fetched database rows should be interpreted.
associatedtype RowDecoder
/// Returns a tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
/// - returns: A prepared statement and an eventual row adapter.
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
/// Returns the number of rows fetched by the request.
///
/// The default implementation builds a naive SQL query based on the
/// statement returned by the `prepare` method:
/// `SELECT COUNT(*) FROM (...)`.
///
/// Adopting types can refine this method in order to use more
/// efficient SQL.
///
/// - parameter db: A database connection.
func fetchCount(_ db: Database) throws -> Int
}
extension FetchRequest {
/// Returns an adapted request.
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest<Self> {
return AdaptedFetchRequest(self, adapter)
}
/// Returns the number of rows fetched by the request.
///
/// This default implementation builds a naive SQL query based on the
/// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
let (statement, _) = try prepare(db)
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
}
/// Returns the database region that the request looks into.
///
/// This default implementation returns a region built from the statement
/// returned by the `prepare` method.
///
/// - parameter db: A database connection.
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
let (statement, _) = try prepare(db)
return statement.databaseRegion
}
}
// MARK: - AdaptedFetchRequest
/// An adapted request.
public struct AdaptedFetchRequest<Base: FetchRequest> : FetchRequest {
public typealias RowDecoder = Base.RowDecoder
private let base: Base
private let adapter: (Database) throws -> RowAdapter
/// Creates an adapted request from a base request and a closure that builds
/// a row adapter from a database connection.
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
self.base = base
self.adapter = adapter
}
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let (statement, baseAdapter) = try base.prepare(db)
if let baseAdapter = baseAdapter {
return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db)))
} else {
return try (statement, adapter(db))
}
}
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try base.fetchCount(db)
}
/// :nodoc:
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
return try base.databaseRegion(db)
}
}
// MARK: - AnyFetchRequest
/// A type-erased FetchRequest.
///
/// An AnyFetchRequest forwards its operations to an underlying request,
/// hiding its specifics.
public struct AnyFetchRequest<T> : FetchRequest {
public typealias RowDecoder = T
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
private let _fetchCount: (Database) throws -> Int
private let _databaseRegion: (Database) throws -> DatabaseRegion
/// Creates a request that wraps and forwards operations to `request`.
public init<Request: FetchRequest>(_ request: Request) {
_prepare = request.prepare
_fetchCount = request.fetchCount
_databaseRegion = request.databaseRegion
}
/// Creates a request whose `prepare()` method wraps and forwards
/// operations the argument closure.
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
_prepare = { db in
try prepare(db)
}
_fetchCount = { db in
let (statement, _) = try prepare(db)
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
}
_databaseRegion = { db in
let (statement, _) = try prepare(db)
return statement.databaseRegion
}
}
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try _prepare(db)
}
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try _fetchCount(db)
}
/// :nodoc:
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
return try _databaseRegion(db)
}
}
// MARK: - SQLRequest
/// A FetchRequest built from raw SQL.
public struct SQLRequest<T> : FetchRequest {
public typealias RowDecoder = T
public var sql: String
public var arguments: StatementArguments?
public var adapter: RowAdapter?
private let cache: Cache?
/// Creates a request from an SQL string, optional arguments, and
/// optional row adapter.
///
/// let request = SQLRequest("SELECT * FROM player")
/// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1])
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: A SQLRequest
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil)
}
/// Creates an SQL request from any other fetch request.
///
/// - parameters:
/// - db: A database connection.
/// - request: A request.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: An SQLRequest
public init<Request: FetchRequest>(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder {
let (statement, adapter) = try request.prepare(db)
self.init(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached)
}
/// Creates an SQL request from an SQL string, optional arguments, and
/// optional row adapter.
///
/// let request = SQLRequest("SELECT * FROM player")
/// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1])
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter.
/// - statementCacheName: Optional statement cache name.
/// - returns: A SQLRequest
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
self.sql = sql
self.arguments = arguments
self.adapter = adapter
self.cache = cache
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
///
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let statement: SelectStatement
switch cache {
case .none:
statement = try db.makeSelectStatement(sql)
case .public?:
statement = try db.cachedSelectStatement(sql)
case .internal?:
statement = try db.internalCachedSelectStatement(sql)
}
if let arguments = arguments {
try statement.setArgumentsWithValidation(arguments)
}
return (statement, adapter)
}
/// There are two statement caches: one for statements generated by the
/// user, and one for the statements generated by GRDB. Those are separated
/// so that GRDB has no opportunity to inadvertently modify the arguments of
/// user's cached statements.
enum Cache {
/// The public cache, for library user
case `public`
/// The internal cache, for grdb
case `internal`
}
}
-583
View File
@@ -1,583 +0,0 @@
/// The protocol for all types that define a way to fetch database rows.
///
/// Requests can feed the fetching methods of any fetchable type (Row,
/// value, record):
///
/// let request: Request = ...
/// try Row.fetchCursor(db, request) // RowCursor
/// try String.fetchAll(db, request) // [String]
/// try Player.fetchOne(db, request) // Player?
public protocol Request {
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
/// The number of rows fetched by the request.
///
/// Default implementation builds a naive SQL query based on the statement
/// returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
///
/// Adopting types can refine this countRequest method and return more
/// efficient SQL.
///
/// - parameter db: A database connection.
func fetchCount(_ db: Database) throws -> Int
}
extension Request {
/// The number of rows fetched by the request.
///
/// This default implementation builds a naive SQL query based on the
/// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
let (statement, _) = try prepare(db)
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
}
/// Returns an equivalent SQLRequest.
///
/// - parameters:
/// - db: A database connection.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: An SQLRequest
public func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest {
let (statement, adapter) = try prepare(db)
return SQLRequest(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached)
}
}
extension Request {
/// Returns a request bound to type T.
///
/// The returned request can fetch if the type T is fetchable (Row,
/// value, record).
///
/// // Int?
/// let maxScore = Player
/// .select(max(scoreColumn))
/// .asRequest(of: Int.self) // <--
/// .fetchOne(db)
///
/// - parameter type: The fetched type T
/// - returns: A typed request bound to type T.
public func asRequest<T>(of type: T.Type) -> AnyTypedRequest<T> {
return AnyTypedRequest { try self.prepare($0) }
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns an adapted request.
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest<Self> {
return AdaptedRequest(self, adapter)
}
}
/// An adapted request.
public struct AdaptedRequest<Base: Request> : Request {
/// Creates an adapted request from a base request and a closure that builds
/// a row adapter from a database connection.
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
self.base = base
self.adapter = adapter
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let (statement, baseAdapter) = try base.prepare(db)
if let baseAdapter = baseAdapter {
return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db)))
} else {
return try (statement, adapter(db))
}
}
/// The number of rows fetched by the request.
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
return try base.fetchCount(db)
}
private let base: Base
private let adapter: (Database) throws -> RowAdapter
}
/// A type-erased Request.
///
/// An instance of AnyRequest forwards its operations to an underlying request,
/// hiding its specifics.
public struct AnyRequest : Request {
/// Creates a new request that wraps and forwards operations to `request`.
public init(_ request: Request) {
self._prepare = { try request.prepare($0) }
}
/// Creates a new request whose `prepare()` method wraps and forwards
/// operations the argument closure.
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
_prepare = prepare
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try _prepare(db)
}
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
}
/// A Request built from raw SQL.
public struct SQLRequest : Request {
public let sql: String
public let arguments: StatementArguments?
public let adapter: RowAdapter?
private let cache: Cache?
/// Creates a new request from an SQL string, optional arguments, and
/// optional row adapter.
///
/// let request = SQLRequest("SELECT * FROM players")
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: A SQLRequest
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil)
}
/// Creates a new request from an SQL string, optional arguments, and
/// optional row adapter.
///
/// let request = SQLRequest("SELECT * FROM players")
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter.
/// - statementCacheName: Optional statement cache name.
/// - returns: A SQLRequest
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
self.sql = sql
self.arguments = arguments
self.adapter = adapter
self.cache = cache
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let statement: SelectStatement
switch cache {
case .none:
statement = try db.makeSelectStatement(sql)
case .public?:
statement = try db.cachedSelectStatement(sql)
case .internal?:
statement = try db.internalCachedSelectStatement(sql)
}
if let arguments = arguments {
try statement.setArgumentsWithValidation(arguments)
}
return (statement, adapter)
}
/// There are two statement caches: one for statements generated by the
/// user, and one for the statements generated by GRDB. Those are separated
/// so that GRDB has no opportunity to inadvertently modify the arguments of
/// user's cached statements.
enum Cache {
/// The public cache, for library user
case `public`
/// The internal cache, for grdb
case `internal`
}
}
/// The protocol for requests that know how to decode database rows.
///
/// Typed requests can fetch if their associated type RowDecoder is able to
/// decode rows (Row, value, record)
///
/// struct Player: RowConvertible { ... }
/// let request: ... // Some TypedRequest that fetches Player
/// try request.fetchCursor(db) // Cursor of Player
/// try request.fetchAll(db) // [Player]
/// try request.fetchOne(db) // Player?
public protocol TypedRequest : Request {
/// The type that can convert raw database rows to fetched values
associatedtype RowDecoder
}
extension TypedRequest {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns an adapted typed request.
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedTypedRequest<Self> {
return AdaptedTypedRequest(self, adapter)
}
}
/// An adapted typed request.
public struct AdaptedTypedRequest<Base: TypedRequest> : TypedRequest {
/// The type that can convert raw database rows to fetched values
public typealias RowDecoder = Base.RowDecoder
/// Creates an adapted request from a base request and a closure that builds
/// a row adapter from a database connection.
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
adaptedRequest = AdaptedRequest(base, adapter)
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try adaptedRequest.prepare(db)
}
/// The number of rows fetched by the request.
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
return try adaptedRequest.fetchCount(db)
}
private let adaptedRequest: AdaptedRequest<Base>
}
/// A type-erased TypedRequest.
///
/// An instance of AnyTypedRequest forwards its operations to an underlying
/// typed request, hiding its specifics.
public struct AnyTypedRequest<T> : TypedRequest {
/// The type that can convert raw database rows to fetched values
public typealias RowDecoder = T
/// Creates a new request that wraps and forwards operations to `request`.
public init<Request>(_ request: Request) where Request: TypedRequest, Request.RowDecoder == RowDecoder {
self._prepare = { try request.prepare($0) }
}
/// Creates a new request whose `prepare()` method wraps and forwards
/// operations the argument closure.
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
_prepare = prepare
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try _prepare(db)
}
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
}
extension TypedRequest where RowDecoder: RowConvertible {
// MARK: Fetching Record and RowConvertible
/// A cursor over fetched records.
///
/// let request: ... // Some TypedRequest that fetches Player
/// let players = try request.fetchCursor(db) // Cursor of Player
/// while let player = try players.next() { // Player
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameter db: A database connection.
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder> {
return try RowDecoder.fetchCursor(db, self)
}
/// An array of fetched records.
///
/// let request: ... // Some TypedRequest that fetches Player
/// let players = try request.fetchAll(db) // [Player]
///
/// - parameter db: A database connection.
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
return try RowDecoder.fetchAll(db, self)
}
/// The first fetched record.
///
/// let request: ... // Some TypedRequest that fetches Player
/// let player = try request.fetchOne(db) // Player?
///
/// - parameter db: A database connection.
/// - returns: An optional record.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
return try RowDecoder.fetchOne(db, self)
}
}
extension TypedRequest where RowDecoder: DatabaseValueConvertible {
// MARK: Fetching Values
/// A cursor over fetched values.
///
/// let request: ... // Some TypedRequest that fetches String
/// let strings = try request.fetchCursor(db) // Cursor of String
/// while let string = try strings.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - 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 -> DatabaseValueCursor<RowDecoder> {
return try RowDecoder.fetchCursor(db, self)
}
/// An array of fetched values.
///
/// let request: ... // Some TypedRequest that fetches String
/// let strings = try request.fetchAll(db) // [String]
///
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
return try RowDecoder.fetchAll(db, self)
}
/// The first fetched value.
///
/// The result is nil if the request returns no row, or if no value can be
/// extracted from the first row.
///
/// let request: ... // Some TypedRequest that fetches String
/// let string = try request.fetchOne(db) // String?
///
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
return try RowDecoder.fetchOne(db, self)
}
}
extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
// MARK: Fetching Values
/// A cursor over fetched values.
///
/// let request: ... // Some TypedRequest that fetches String
/// let strings = try request.fetchCursor(db) // Cursor of String
/// while let string = try strings.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - 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> {
return try RowDecoder.fetchCursor(db, self)
}
/// An array of fetched values.
///
/// let request: ... // Some TypedRequest that fetches String
/// let strings = try request.fetchAll(db) // [String]
///
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
return try RowDecoder.fetchAll(db, self)
}
/// The first fetched value.
///
/// The result is nil if the request returns no row, or if no value can be
/// extracted from the first row.
///
/// let request: ... // Some TypedRequest that fetches String
/// let string = try request.fetchOne(db) // String?
///
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
return try RowDecoder.fetchOne(db, self)
}
}
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
// MARK: Fetching Optional values
/// A cursor over fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let strings = try request.fetchCursor(db) // Cursor of String?
/// while let string = try strings.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - 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 -> NullableDatabaseValueCursor<RowDecoder._Wrapped> {
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
}
/// An array of fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let strings = try request.fetchAll(db) // [String?]
///
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
}
}
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
// MARK: Fetching Optional values
/// A cursor over fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let strings = try request.fetchCursor(db) // Cursor of String?
/// while let string = try strings.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - 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> {
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
}
/// An array of fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let strings = try request.fetchAll(db) // [String?]
///
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
}
}
extension TypedRequest where RowDecoder: Row {
// MARK: Fetching Rows
/// A cursor over fetched rows.
///
/// let request: ... // Some TypedRequest that fetches Row
/// let rows = try request.fetchCursor(db) // RowCursor
/// while let row = try rows.next() { // Row
/// let id: Int64 = row[0]
/// let name: String = row[1]
/// }
///
/// Fetched rows are reused during the cursor iteration: don't turn a row
/// cursor into an array with `Array(rows)` or `rows.filter { ... }` since
/// you would not get the distinct rows you expect. Use `Row.fetchAll(...)`
/// instead.
///
/// For the same reason, make sure you make a copy whenever you extract a
/// row for later use: `row.copy()`.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameter db: A database connection.
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> RowCursor {
return try Row.fetchCursor(db, self)
}
/// An array of fetched rows.
///
/// let request: ... // Some TypedRequest that fetches Row
/// let rows = try request.fetchAll(db)
///
/// - parameter db: A database connection.
/// - returns: An array of fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [Row] {
return try Row.fetchAll(db, self)
}
/// The first fetched row.
///
/// let request: ... // Some TypedRequest that fetches Row
/// let row = try request.fetchOne(db)
///
/// - parameter db: A database connection.
/// - returns: A,n optional rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> Row? {
return try Row.fetchOne(db, self)
}
}
+660 -259
View File
File diff suppressed because it is too large. Load diff
+155 -33
View File
@@ -1,8 +1,50 @@
import Foundation
/// Returns an array of row adapters that split a row according to the input
/// number of columns.
///
/// For example:
///
/// let sql = "SELECT 1, 2,3,4, 5,6, 7,8"
/// // <.><. . .><. .><. .>
/// let adapters = splittingRowAdapters([1, 3, 2])
/// let adapter = ScopeAdapter([
/// "a": adapters[0],
/// "b": adapters[1],
/// "c": adapters[2],
/// "d": adapters[3]])
/// let row = try Row.fetchOne(db, sql, adapter: adapter)
/// row.scopes["a"] // [1]
/// row.scopes["b"] // [2, 3, 4]
/// row.scopes["c"] // [5, 6]
/// row.scopes["d"] // [7, 8]
public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter] {
guard !columnCounts.isEmpty else {
// Identity adapter
return [SuffixRowAdapter(fromIndex: 0)]
}
// [1, 3, 2] -> [0, 1, 4, 6]
let columnIndexes = columnCounts.reduce(into: [0]) { (acc, count) in
acc.append(acc.last! + count)
}
// [0, 1, 4, 6] -> [(0..<1), (1..<4), (4..<6)]
let rangeAdapters = zip(columnIndexes, columnIndexes.suffix(from: 1))
.map { RangeRowAdapter($0..<$1) }
// (6...)
let suffixAdapter = SuffixRowAdapter(fromIndex: columnIndexes.last!)
// [(0..<1), (1..<4), (4..<6), (6...)]
return rangeAdapters + [suffixAdapter]
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// LayoutedColumnMapping is a type that supports the RowAdapter protocol.
///
/// :nodoc:
public struct LayoutedColumnMapping {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -35,7 +77,7 @@ public struct LayoutedColumnMapping {
/// }
/// }
///
/// // <Row foo:"foo" bar: "bar">
/// // [foo:"foo" bar: "bar"]
/// try Row.fetchOne(db, "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter())
public init<S: Sequence>(layoutColumns: S) where S.Iterator.Element == (Int, String) {
self.layoutColumns = Array(layoutColumns)
@@ -56,6 +98,8 @@ public struct LayoutedColumnMapping {
}
/// LayoutedColumnMapping adopts LayoutedRowAdapter
///
/// :nodoc:
extension LayoutedColumnMapping : LayoutedRowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -72,6 +116,7 @@ extension LayoutedColumnMapping : LayoutedRowAdapter {
}
}
/// :nodoc:
extension LayoutedColumnMapping : RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -91,6 +136,8 @@ extension LayoutedColumnMapping : RowLayout {
///
/// GRBD ships with a ready-made type that adopts this protocol:
/// LayoutedColumnMapping.
///
/// :nodoc:
public protocol LayoutedRowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -108,6 +155,8 @@ public protocol LayoutedRowAdapter {
///
/// RowLayout is a protocol that supports the RowAdapter protocol. It describes
/// a layout of a base row.
///
/// :nodoc:
public protocol RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -124,11 +173,13 @@ public protocol RowLayout {
extension SelectStatement : RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var layoutColumns: [(Int, String)] {
return Array(columnNames.enumerated())
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func layoutIndex(ofColumn name: String) -> Int? {
return index(ofColumn: name)
}
@@ -149,7 +200,7 @@ extension SelectStatement : RowLayout {
/// let adapter = SuffixRowAdapter(fromIndex: 2)
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
///
/// // <Row baz:3>
/// // [baz:3]
/// try Row.fetchOne(db, sql, adapter: adapter)
public protocol RowAdapter {
@@ -172,7 +223,7 @@ public protocol RowAdapter {
/// }
/// }
///
/// // <Row foo:1>
/// // [foo:1]
/// try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter
}
@@ -186,7 +237,11 @@ extension RowAdapter {
/// - parameter scopes: A dictionary that maps scope names to
/// row adapters.
public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter {
return ScopeAdapter(mainAdapter: self, scopes: scopes)
if scopes.isEmpty {
return self
} else {
return ScopeAdapter(base: self, scopes: scopes)
}
}
}
@@ -196,12 +251,24 @@ extension RowAdapter {
}
}
/// EmptyRowAdapter is a row adapter that hides all columns.
public struct EmptyRowAdapter: RowAdapter {
/// Creates an EmptyRowAdapter
public init() { }
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return LayoutedColumnMapping(layoutColumns: [])
}
}
/// ColumnMapping is a row adapter that maps column names.
///
/// let adapter = ColumnMapping(["foo": "bar"])
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
///
/// // <Row foo:"bar">
/// // [foo:"bar"]
/// try Row.fetchOne(db, sql, adapter: adapter)
public struct ColumnMapping : RowAdapter {
/// A dictionary from mapped column names to column names in a base row.
@@ -214,6 +281,7 @@ public struct ColumnMapping : RowAdapter {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
let layoutColumns = try mapping
.map { (mappedColumn, baseColumn) -> (Int, String) in
@@ -234,7 +302,7 @@ public struct ColumnMapping : RowAdapter {
/// let adapter = SuffixRowAdapter(fromIndex: 2)
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
///
/// // <Row baz:3>
/// // [baz:3]
/// try Row.fetchOne(db, sql, adapter: adapter)
public struct SuffixRowAdapter : RowAdapter {
/// The suffix index
@@ -250,6 +318,7 @@ public struct SuffixRowAdapter : RowAdapter {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index))
}
@@ -260,7 +329,7 @@ public struct SuffixRowAdapter : RowAdapter {
/// let adapter = RangeRowAdapter(1..<3)
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
///
/// // <Row bar:2 baz: 3>
/// // [bar:2 baz:3]
/// try Row.fetchOne(db, sql, adapter: adapter)
public struct RangeRowAdapter : RowAdapter {
/// The range
@@ -279,6 +348,7 @@ public struct RangeRowAdapter : RowAdapter {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range])
}
@@ -300,37 +370,64 @@ public struct RangeRowAdapter : RowAdapter {
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
///
/// // Scoped rows:
/// if let fooRow = row.scoped(on: "foo") {
/// if let fooRow = row.scopes["foo"] {
/// fooRow["value"] // "foo"
/// }
/// if let barRow = row.scopeed(on: "bar") {
/// if let barRow = row.scopes["bar"] {
/// barRow["value"] // "bar"
/// }
public struct ScopeAdapter : RowAdapter {
/// The main adapter
let mainAdapter: RowAdapter
/// The base adapter
let base: RowAdapter
/// The scope adapters
let scopes: [String: RowAdapter]
/// Creates a scoped adapter.
/// Creates an adapter that preserves row contents and add scoped rows.
///
/// For example:
///
/// let adapter = ScopeAdapter(["suffix": SuffixRowAdapter(fromIndex: 1)])
/// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
/// row // [1, 2, 3]
/// row.scopes["suffix"] // [2, 3]
///
/// - parameter scopes: A dictionary that maps scope names to
/// row adapters.
public init(_ scopes: [String: RowAdapter]) {
self.mainAdapter = SuffixRowAdapter(fromIndex: 0) // Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
self.scopes = scopes
// Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes)
}
init(mainAdapter: RowAdapter, scopes: [String: RowAdapter]) {
self.mainAdapter = mainAdapter
/// Creates an adapter based on the base adapter, and add scoped rows.
///
/// For example:
///
/// let baseAdapter = RangeRowAdapter(0..<1)
/// let adapter = ScopeAdapter(base: baseAdapter, scopes: ["suffix": SuffixRowAdapter(fromIndex: 1)])
/// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
/// row // [1]
/// row.scopes["initial"] // [2, 3]
///
/// If the base adapter already defines scopes, the given scopes replace
/// eventual existing scopes with the same name.
///
/// This initializer is equivalent to `baseAdapter.addingScopes(scopes)`.
///
/// - parameter base: A dictionary that maps scope names to
/// row adapters.
/// - parameter scopes: A dictionary that maps scope names to
/// row adapters.
public init(base: RowAdapter, scopes: [String: RowAdapter]) {
self.base = base
self.scopes = scopes
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
let layoutedAdapter = try mainAdapter.layoutedAdapter(from: layout)
let layoutedAdapter = try base.layoutedAdapter(from: layout)
var layoutedScopes = layoutedAdapter.scopes
for (name, adapter) in scopes {
try layoutedScopes[name] = adapter.layoutedAdapter(from: layout)
@@ -359,7 +456,7 @@ struct ChainedAdapter : RowAdapter {
extension Row {
/// Creates a row from a base row and a statement adapter
convenience init(base: Row, adapter: LayoutedRowAdapter) {
self.init(impl: AdapterRowImpl(base: base, adapter: adapter))
self.init(impl: AdaptedRowImpl(base: base, adapter: adapter))
}
/// Returns self if adapter is nil
@@ -371,7 +468,7 @@ extension Row {
}
}
struct AdapterRowImpl : RowImpl {
struct AdaptedRowImpl : RowImpl {
let base: Row
let adapter: LayoutedRowAdapter
let mapping: LayoutedColumnMapping
@@ -390,12 +487,39 @@ struct AdapterRowImpl : RowImpl {
return base.isFetched
}
var scopes: Row.ScopesView {
return Row.ScopesView(row: base, scopes: adapter.scopes)
}
func hasNull(atUncheckedIndex index: Int) -> Bool {
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return base.impl.hasNull(atUncheckedIndex: mappedIndex)
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return base[mapping.baseColumnIndex(atMappingIndex: index)]
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return base.impl.databaseValue(atUncheckedIndex: mappedIndex)
}
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int) -> Value
{
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return Value.fastDecode(from: base, atUncheckedIndex: mappedIndex)
}
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int) -> Value?
{
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex)
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
return base.dataNoCopy(atIndex: mapping.baseColumnIndex(atMappingIndex: index))
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex)
}
func columnName(atUncheckedIndex index: Int) -> String {
@@ -406,18 +530,16 @@ struct AdapterRowImpl : RowImpl {
return mapping.layoutIndex(ofColumn: name)
}
func scoped(on name: String) -> Row? {
guard let adapter = adapter.scopes[name] else {
return nil
}
return Row(base: base, adapter: adapter)
}
var scopeNames: Set<String> {
return Set(adapter.scopes.keys)
}
func copy(_ row: Row) -> Row {
func copiedRow(_ row: Row) -> Row {
return Row(base: base.copy(), adapter: adapter)
}
func unscopedRow(_ row: Row) -> Row {
assert(adapter.mapping.scopes.isEmpty)
return Row(base: base, adapter: adapter.mapping)
}
func unadaptedRow(_ row: Row) -> Row {
return base.unadapted
}
}
+12 -17
View File
@@ -16,47 +16,42 @@ import Dispatch
/// of the dispatch queue, a SchedulingWatchdog that allows that database only.
///
/// Later on, the queue can be shared by several databases with the method
/// allowing(databases:execute:). See SerializedDatabase.sync() for
/// an example.
/// inheritingAllowedDatabases(from:execute:). See SerializedDatabase.sync()
/// for an example.
///
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
/// dispatch queue.
final class SchedulingWatchdog {
private static let specificKey = DispatchSpecificKey<SchedulingWatchdog>()
private static let watchDogKey = DispatchSpecificKey<SchedulingWatchdog>()
private(set) var allowedDatabases: [Database]
var databaseObservationBroker: DatabaseObservationBroker?
private init(allowedDatabase database: Database) {
allowedDatabases = [database]
}
static func makeSerializedQueue(allowingDatabase database: Database) -> DispatchQueue {
let queue = DispatchQueue(label: "GRDB.SerializedDatabase")
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)
}
// Temporarily allows `databases` while executing `body`
func allowing<T>(databases: [Database], execute body: () throws -> T) rethrows -> T {
func inheritingAllowedDatabases<T>(from other: SchedulingWatchdog, execute body: () throws -> T) rethrows -> T {
let backup = allowedDatabases
allowedDatabases.append(contentsOf: databases)
allowedDatabases.append(contentsOf: other.allowedDatabases)
defer { allowedDatabases = backup }
return try body()
}
static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(allows(db), message, file: file, line: line)
GRDBPrecondition(current?.allows(db) ?? false, message, file: file, line: line)
}
static func allows(_ db: Database) -> Bool {
return current?.allows(db) ?? false
static var current: SchedulingWatchdog? {
return DispatchQueue.getSpecific(key: watchDogKey)
}
func allows(_ db: Database) -> Bool {
return allowedDatabases.contains { $0 === db }
}
static var current: SchedulingWatchdog? {
return DispatchQueue.getSpecific(key: specificKey)
}
}
+51 -21
View File
@@ -16,7 +16,7 @@ final class SerializedDatabase {
/// The dispatch queue
private let queue: DispatchQueue
init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache) 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)
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()
}
@@ -61,27 +62,28 @@ final class SerializedDatabase {
//
// 1. A database is invoked from some queue like the main queue:
//
// dbQueue.inDatabase { db in // <-- we're here
// serializedDatabase.sync { db in // <-- we're here
// }
//
// 2. A database is invoked in a reentrant way:
//
// dbQueue.inDatabase { db in
// dbQueue.inDatabase { db in // <-- we're here
// serializedDatabase.sync { db in
// serializedDatabase.sync { db in // <-- we're here
// }
// }
//
// 3. A database in invoked from another database:
//
// dbQueue1.inDatabase { db1 in
// dbQueue2.inDatabase { db2 in // <-- we're here
// serializedDatabase1.sync { db1 in
// serializedDatabase2.sync { db2 in // <-- we're here
// }
// }
guard let watchdog = SchedulingWatchdog.current else {
// Case 1
return try queue.sync {
try block(db)
defer { preconditionNoUnsafeTransactionLeft(db) }
return try block(db)
}
}
@@ -90,8 +92,9 @@ final class SerializedDatabase {
// Case 3
return try queue.sync {
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
try block(db)
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
defer { preconditionNoUnsafeTransactionLeft(db) }
return try block(db)
}
}
}
@@ -105,39 +108,60 @@ final class SerializedDatabase {
//
// 1. A database is invoked from some queue like the main queue:
//
// dbQueue.inDatabase { db in // <-- we're here
// serializedDatabase.reentrantSync { db in // <-- we're here
// }
//
// 2. A database is invoked in a reentrant way:
//
// dbQueue.inDatabase { db in
// dbQueue.inDatabase { db in // <-- we're here
// serializedDatabase.reentrantSync { db in
// serializedDatabase.reentrantSync { db in // <-- we're here
// }
// }
//
// 3. A database in invoked from another database:
//
// dbQueue1.inDatabase { db1 in
// dbQueue2.inDatabase { db2 in // <-- we're here
// serializedDatabase1.reentrantSync { db1 in
// serializedDatabase2.reentrantSync { db2 in // <-- we're here
// }
// }
guard let watchdog = SchedulingWatchdog.current else {
// Case 1
return try queue.sync {
try block(db)
// Since we are reentrant, a transaction may already be opened.
// In this case, don't check for unsafe transaction at the end.
if db.isInsideTransaction {
return try block(db)
} else {
defer { preconditionNoUnsafeTransactionLeft(db) }
return try block(db)
}
}
}
// Case 2
if watchdog.allows(db) {
return try block(db)
// Since we are reentrant, a transaction may already be opened.
// In this case, don't check for unsafe transaction at the end.
if db.isInsideTransaction {
return try block(db)
} else {
defer { preconditionNoUnsafeTransactionLeft(db) }
return try block(db)
}
}
// Case 3
return try queue.sync {
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
try block(db)
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
// Since we are reentrant, a transaction may already be opened.
// In this case, don't check for unsafe transaction at the end.
if db.isInsideTransaction {
return try block(db)
} else {
defer { preconditionNoUnsafeTransactionLeft(db) }
return try block(db)
}
}
}
}
@@ -146,12 +170,13 @@ final class SerializedDatabase {
func async(_ block: @escaping (Database) -> Void) {
queue.async {
block(self.db)
self.preconditionNoUnsafeTransactionLeft(self.db)
}
}
/// Returns true if any only if the current dispatch queue is valid.
var onValidQueue: Bool {
return SchedulingWatchdog.allows(db)
return SchedulingWatchdog.current?.allows(db) ?? false
}
/// Executes the block in the current queue.
@@ -166,4 +191,9 @@ final class SerializedDatabase {
func preconditionValidQueue(_ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
SchedulingWatchdog.preconditionValidQueue(db, message, file: file, line: line)
}
/// Fatal error if a transaction has been left opened.
private func preconditionNoUnsafeTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message, file: file, line: line)
}
}
+134 -204
View File
@@ -15,16 +15,6 @@ let statementSeparatorCharacterSet = CharacterSet(charactersIn: ";").union(.whit
struct EmptyStatementError : Error {
}
/// A common protocol for UpdateStatement and SelectStatement
protocol AuthorizedStatement {
init(
database: Database,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
}
/// A statement represents an SQL query.
///
/// It is the base class of UpdateStatement that executes *update statements*,
@@ -64,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
@@ -92,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)
}
}
@@ -145,7 +133,7 @@ public class Statement {
_arguments = arguments
argumentsNeedValidation = false
reset()
try! reset()
clearBindings()
var valuesIterator = arguments.values.makeIterator()
@@ -168,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)
@@ -222,6 +210,75 @@ public class Statement {
}
}
// MARK: - AuthorizedStatement
/// A common protocol for UpdateStatement and SelectStatement
protocol AuthorizedStatement {
// This initializer should be a required initializer of Statement.
//
// But Swift requires this required initializer to be public:
// https://bugs.swift.org/browse/SR-2347
//
// We work around SR-2347 with this internal protocol.
//
// TODO: hasn't this bug been fixed in Swift 4.2? https://github.com/apple/swift/blob/master/CHANGELOG.md#swift-42
init(
database: Database,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
}
extension AuthorizedStatement {
// Static function instead of an initializer because initializer doesn't
// compile due to the "capturing of an uninitialized self" in
// `sqlCodeUnits.withUnsafeBufferPointer`.
static func prepare(sql: String, prepFlags: Int32, in database: Database) throws -> Self {
let authorizer = StatementCompilationAuthorizer()
database.authorizer = authorizer
defer { database.authorizer = nil }
let sqlCodeUnits = sql.utf8CString
return try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let statementStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
var statementEnd: UnsafePointer<Int8>? = nil
let statement: Self
do {
statement = try self.init(
database: database,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: prepFlags,
authorizer: authorizer)
} catch is EmptyStatementError {
throw DatabaseError(
resultCode: .SQLITE_ERROR,
message: "empty statement",
sql: sql,
arguments: nil)
}
let remainingData = Data(
bytesNoCopy: UnsafeMutableRawPointer(mutating: statementEnd!),
count: statementStart + sqlCodeUnits.count - statementEnd! - 1,
deallocator: .none)
let remainingSQL = String(data: remainingData, encoding: .utf8)!
.trimmingCharacters(in: statementSeparatorCharacterSet)
guard remainingSQL.isEmpty else {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.",
sql: sql,
arguments: nil)
}
return statement
}
}
}
// MARK: - SelectStatement
@@ -229,14 +286,14 @@ public class Statement {
///
/// You create SelectStatement with the Database.makeSelectStatement() method:
///
/// try dbQueue.inDatabase { db in
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
/// try dbQueue.read { db in
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
/// }
public final class SelectStatement : Statement, AuthorizedStatement {
/// Information about the table and columns read by a SelectStatement
public private(set) var selectionInfo: SelectionInfo
public final class SelectStatement : Statement {
/// The database region that the statement looks into.
public private(set) var databaseRegion: DatabaseRegion
/// Creates a prepared statement.
///
@@ -257,7 +314,7 @@ public final class SelectStatement : Statement, AuthorizedStatement {
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
{
self.selectionInfo = SelectionInfo()
self.databaseRegion = DatabaseRegion()
try super.init(
database: database,
statementStart: statementStart,
@@ -267,7 +324,7 @@ public final class SelectStatement : Statement, AuthorizedStatement {
GRDBPrecondition(authorizer.invalidatesDatabaseSchemaCache == false, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
GRDBPrecondition(authorizer.transactionEffect == nil, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
self.selectionInfo = authorizer.selectionInfo
self.databaseRegion = authorizer.databaseRegion
}
/// The number of columns in the resulting rows.
@@ -297,86 +354,27 @@ public final class SelectStatement : Statement, AuthorizedStatement {
/// 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()
}
/// Information about the table and columns read by a SelectStatement
public struct SelectionInfo : CustomStringConvertible {
/// Selection is unknown when a statement uses the COUNT function,
/// and SQLite version < 3.19:
///
/// `SELECT COUNT(*) FROM t1` -> unknown selection
private let isUnknown: Bool
/// `SELECT a, b FROM t1` -> ["t1": ["a", "b"]]
private var columns: [String: Set<String>] = [:]
/// `SELECT COUNT(*) FROM t1` -> ["t1"]
private var tables: Set<String> = []
/// The unknown selection
static let unknown = SelectionInfo(isUnknown: true)
mutating func insert(allColumnsOfTable table: String) {
tables.insert(table)
}
mutating func insert(column: String, ofTable table: String) {
columns[table, default: []].insert(column)
}
/// Returns true if isUnknown is true
func contains(anyColumnFrom table: String) -> Bool {
if isUnknown { return true }
return tables.contains(table) || columns.index(forKey: table) != nil
}
/// Returns true if isUnknown is true
func contains(anyColumnIn columns: Set<String>, from table: String) -> Bool {
if isUnknown { return true }
return tables.contains(table) || !(self.columns[table]?.isDisjoint(with: columns) ?? true)
}
init() {
self.init(isUnknown: false)
}
private init(isUnknown: Bool) {
self.isUnknown = isUnknown
}
public var description: String {
if isUnknown {
return "unknown"
}
return tables.union(columns.keys)
.sorted()
.map { table -> String in
if let columns = columns[table] {
return "\(table)(\(columns.sorted().joined(separator: ",")))"
} else {
return "\(table)(*)"
}
}
.joined(separator: ",")
}
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.inDatabase { db in
/// let statement = db.makeSelectStatement("SELECT * FROM players")
/// let cursor: StatementCursor = statement.cursor()
/// try dbQueue.read { db in
/// let statement = db.makeSelectStatement("SELECT * FROM player")
/// let cursor: StatementCursor = statement.makeCursor()
/// }
public final class StatementCursor: Cursor {
public let statement: SelectStatement
@@ -387,11 +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
@@ -413,12 +422,12 @@ public final class StatementCursor: Cursor {
/// You create UpdateStatement with the Database.makeUpdateStatement() method:
///
/// try dbQueue.inTransaction { db in
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)")
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
/// return .commit
/// }
public final class UpdateStatement : Statement, AuthorizedStatement {
public final class UpdateStatement : Statement {
enum TransactionEffect {
case beginTransaction
case commitTransaction
@@ -432,10 +441,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
/// is executed.
private(set) var invalidatesDatabaseSchemaCache: Bool
/// If true, the statement needs support from TruncateOptimizationBlocker
/// when executed
private(set) var needsTruncateOptimizationPreventionDuringExecution: Bool
private(set) var transactionEffect: TransactionEffect?
private(set) var databaseEventKinds: [DatabaseEventKind]
@@ -459,7 +464,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
authorizer: StatementCompilationAuthorizer) throws
{
self.invalidatesDatabaseSchemaCache = false
self.needsTruncateOptimizationPreventionDuringExecution = false
self.databaseEventKinds = []
try super.init(
database: database,
@@ -467,7 +471,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
statementEnd: statementEnd,
prepFlags: prepFlags)
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
self.needsTruncateOptimizationPreventionDuringExecution = authorizer.needsTruncateOptimizationPreventionDuringExecution
self.transactionEffect = authorizer.transactionEffect
self.databaseEventKinds = authorizer.databaseEventKinds
}
@@ -479,13 +482,9 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
public func execute(arguments: StatementArguments? = nil) throws {
SchedulingWatchdog.preconditionValidQueue(database)
prepare(withArguments: arguments)
reset()
try reset()
database.updateStatementWillExecute(self)
if needsTruncateOptimizationPreventionDuringExecution {
database.authorizer = TruncateOptimizationBlocker()
}
while true {
switch sqlite3_step(sqliteStatement) {
case SQLITE_ROW:
@@ -508,12 +507,10 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
continue
case SQLITE_DONE:
database.authorizer = nil
try database.updateStatementDidExecute(self)
return
case let code:
database.authorizer = nil
try database.updateStatementDidFail(self)
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
}
@@ -521,6 +518,9 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
}
}
// Hide AuthorizedStatement from Jazzy
extension UpdateStatement: AuthorizedStatement { }
// MARK: - StatementArguments
@@ -588,16 +588,24 @@ public final class UpdateStatement : Statement, 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 <Row two:2 foo:"foo" one:1 foo2:"foo" bar:"bar">
public struct StatementArguments {
var values: [DatabaseValue] = []
var namedValues: [String: DatabaseValue] = [:]
/// // 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] = [:]
public var isEmpty: Bool {
return values.isEmpty && namedValues.isEmpty
@@ -881,7 +889,8 @@ public struct StatementArguments {
}
}
extension StatementArguments : ExpressibleByArrayLiteral {
// ExpressibleByArrayLiteral
extension StatementArguments {
/// Returns a StatementArguments from an array literal:
///
/// db.selectRows("SELECT ...", arguments: ["Arthur", 41])
@@ -890,7 +899,8 @@ extension StatementArguments : ExpressibleByArrayLiteral {
}
}
extension StatementArguments : ExpressibleByDictionaryLiteral {
// ExpressibleByDictionaryLiteral
extension StatementArguments {
/// Returns a StatementArguments from a dictionary literal:
///
/// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "score": 41])
@@ -899,7 +909,9 @@ extension StatementArguments : ExpressibleByDictionaryLiteral {
}
}
extension StatementArguments : CustomStringConvertible {
// CustomStringConvertible
extension StatementArguments {
/// :nodoc:
public var description: String {
let valuesDescriptions = values.map { $0.description }
let namedValuesDescriptions = namedValues.map { (key, value) -> String in
@@ -908,85 +920,3 @@ extension StatementArguments : CustomStringConvertible {
return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]"
}
}
extension StatementArguments : Equatable {
public static func == (lhs: StatementArguments, rhs: StatementArguments) -> Bool {
if lhs.values != rhs.values { return false }
if lhs.namedValues != rhs.namedValues { return false }
return true
}
}
/// A thread-unsafe statement cache
struct StatementCache {
unowned let db: Database
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)
}
}
}
+26 -24
View File
@@ -1,3 +1,6 @@
#if os(Linux)
import Glibc
#endif
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
@@ -18,7 +21,7 @@ protocol StatementAuthorizer : class {
/// A class that gathers information about one statement during its compilation.
final class StatementCompilationAuthorizer : StatementAuthorizer {
/// What this statements reads
var selectionInfo = SelectStatement.SelectionInfo()
var databaseRegion = DatabaseRegion()
/// What this statements writes
var databaseEventKinds: [DatabaseEventKind] = []
@@ -32,9 +35,6 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
/// savepoint statement.
var transactionEffect: UpdateStatement.TransactionEffect?
/// True if statement may trigger the truncate optimization
var needsTruncateOptimizationPreventionDuringExecution = false
private var isDropStatement = false
func authorize(
@@ -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
@@ -69,10 +69,10 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
if columnName.isEmpty {
// SELECT COUNT(*) FROM table
selectionInfo.insert(allColumnsOfTable: tableName)
databaseRegion.formUnion(DatabaseRegion(table: tableName))
} else {
// SELECT column FROM table
selectionInfo.insert(column: columnName, ofTable: tableName)
databaseRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
}
return SQLITE_OK
@@ -84,12 +84,17 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
case SQLITE_DELETE:
if isDropStatement { return SQLITE_OK }
guard let cString1 = cString1 else { return SQLITE_OK }
// Deletions from sqlite_master and sqlite_temp_master are not like
// other deletions: the update hook does not notify them, and they
// are prevented when the truncate optimization is disabled.
// Let's authorize such deletions by returning SQLITE_OK:
guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK }
guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK }
// Now we prevent the truncate optimization so that transaction
// observers are notified of individual row deletions.
databaseEventKinds.append(.delete(tableName: String(cString: cString1)))
// Prevent the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
// See also TruncateOptimizationBlocker
needsTruncateOptimizationPreventionDuringExecution = true
return SQLITE_IGNORE
case SQLITE_UPDATE:
@@ -129,11 +134,11 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
// Before SQLite 3.19.0, `SELECT COUNT(*) FROM table` does not
// trigger any authorization callback that tells about the
// counted table: any use of the COUNT function makes the
// selection undetermined.
// region undetermined (the full database).
guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK }
guard let cString2 = cString2 else { return SQLITE_OK }
if sqlite3_stricmp(cString2, "COUNT") == 0 {
selectionInfo = .unknown
databaseRegion = .fullDatabase
}
return SQLITE_OK
@@ -159,11 +164,8 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
/// which makes transaction observers unable to observe individual deletions
/// when user runs `DELETE FROM t` statements.
//
/// Warning: to perform well, this authorizer requires that:
//
/// - It is used during statement execution, not during statement compilation.
/// - Statement compilation was authorized with a StatementCompilationAuthorizer
/// that has set its needsTruncateOptimizationPreventionDuringExecution flag.
/// Warning: to perform well, this authorizer must be used during statement
/// execution, not during statement compilation.
final class TruncateOptimizationBlocker : StatementAuthorizer {
func authorize(
_ actionCode: Int32,
+253 -138
View File
@@ -53,13 +53,13 @@ public protocol StatementColumnConvertible {
/// A cursor of database values extracted from a single column.
/// For example:
///
/// try dbQueue.inDatabase { db in
/// let names: ColumnCursor<String> = try String.fetchCursor(db, "SELECT name FROM players")
/// try dbQueue.read { db in
/// let names: ColumnCursor<String> = try String.fetchCursor(db, "SELECT name FROM player")
/// while let name = names.next() { // String
/// 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
@@ -67,27 +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)
@@ -95,16 +103,19 @@ 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:
///
/// try dbQueue.inDatabase { db in
/// let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, "SELECT email FROM players")
/// try dbQueue.read { db in
/// let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, "SELECT email FROM player")
/// while let email = emails.next() { // String?
/// 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
@@ -112,23 +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)
@@ -136,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.
@@ -165,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.
@@ -197,69 +223,11 @@ 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
}
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
// MARK: Fetching From Request
/// Returns a cursor over values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let names = try String.fetchCursor(db, request) // Cursor of String
/// while let name = try names.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - request: A fetch request.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> ColumnCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let names = try String.fetchAll(db, request) // [String]
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
/// Returns a single value fetched from a fetch request.
///
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let name = try String.fetchOne(db, request) // String?
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? {
let (statement, adapter) = try request.prepare(db)
return try fetchOne(statement, adapter: adapter)
}
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
// MARK: Fetching From SQL
@@ -283,8 +251,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(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> ColumnCursor<Self> {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
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))
}
/// Returns an array of values fetched from an SQL query.
@@ -299,7 +267,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from an SQL query.
@@ -314,10 +282,119 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
return try fetchOne(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
}
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
// MARK: Fetching From FetchRequest
/// Returns a cursor over values fetched from a fetch request.
///
/// let request = Player.select(Column("name"))
/// let names = try String.fetchCursor(db, request) // Cursor of String
/// while let name = try names.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - 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 -> FastDatabaseValueCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of values fetched from a fetch request.
///
/// let request = Player.select(Column("name"))
/// let names = try String.fetchAll(db, request) // [String]
///
/// - parameters:
/// - db: A database connection.
/// - request: A FetchRequest.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Self] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
/// Returns a single value fetched from a fetch request.
///
/// let request = Player.filter(key: 1).select(Column("name"))
/// let name = try String.fetchOne(db, request) // String?
///
/// - parameters:
/// - db: A database connection.
/// - request: A FetchRequest.
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> Self? {
let (statement, adapter) = try request.prepare(db)
return try fetchOne(statement, adapter: adapter)
}
}
extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
// MARK: Fetching Values
/// A cursor over fetched values.
///
/// let request: ... // Some TypedRequest that fetches String
/// let strings = try request.fetchCursor(db) // Cursor of String
/// while let string = try strings.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - 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 -> FastDatabaseValueCursor<RowDecoder> {
return try RowDecoder.fetchCursor(db, self)
}
/// An array of fetched values.
///
/// let request: ... // Some TypedRequest that fetches String
/// let strings = try request.fetchAll(db) // [String]
///
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
return try RowDecoder.fetchAll(db, self)
}
/// The first fetched value.
///
/// The result is nil if the request returns no row, or if no value can be
/// extracted from the first row.
///
/// let request: ... // Some TypedRequest that fetches String
/// let string = try request.fetchOne(db) // String?
///
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
return try RowDecoder.fetchOne(db, self)
}
}
/// Swift's Optional comes with built-in methods that allow to fetch cursors
/// and arrays of optional DatabaseValueConvertible:
@@ -353,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.
@@ -373,48 +450,6 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
}
}
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
// MARK: Fetching From Request
/// Returns a cursor over optional values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - requet: A fetch request.
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableColumnCursor<Wrapped> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of optional values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
}
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
// MARK: Fetching From SQL
@@ -438,8 +473,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(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor<Wrapped> {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
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))
}
/// Returns an array of optional values fetched from an SQL query.
@@ -454,6 +489,86 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
}
}
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
// MARK: Fetching From FetchRequest
/// Returns a cursor over optional values fetched from a fetch request.
///
/// let request = Player.select(Column("name"))
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - 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 -> FastNullableDatabaseValueCursor<Wrapped> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of optional values fetched from a fetch request.
///
/// let request = Player.select(Column("name"))
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
///
/// - parameters:
/// - db: A database connection.
/// - request: A FetchRequest.
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Wrapped?] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
}
extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
// MARK: Fetching Optional values
/// A cursor over fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let strings = try request.fetchCursor(db) // Cursor of String?
/// while let string = try strings.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - 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 -> FastNullableDatabaseValueCursor<RowDecoder._Wrapped> {
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
}
/// An array of fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let strings = try request.fetchAll(db) // [String?]
///
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
}
}
@@ -1,3 +1,4 @@
#if canImport(CoreGraphics)
import CoreGraphics
/// CGFloat adopts DatabaseValueConvertible
@@ -16,3 +17,4 @@ extension CGFloat : DatabaseValueConvertible {
return CGFloat(double)
}
}
#endif
+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
}
}
@@ -1,8 +1,13 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// DatabaseDateComponents reads and stores DateComponents in the database.
public struct DatabaseDateComponents : DatabaseValueConvertible {
public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumnConvertible {
/// The available formats for reading and storing date components.
public enum Format : String {
@@ -53,21 +58,36 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
/// Creates a DatabaseDateComponents from a DateComponents and a format.
///
/// The result is nil if and only if *dateComponents* is nil.
///
/// - parameters:
/// - dateComponents: An optional DateComponents.
/// - format: The format used for storing the date components in
/// the database.
/// - returns: An optional DatabaseDateComponents.
public init?(_ dateComponents: DateComponents?, format: Format) {
guard let dateComponents = dateComponents else {
return nil
}
public init(_ dateComponents: DateComponents, format: Format) {
self.format = format
self.dateComponents = dateComponents
}
// MARK: - StatementColumnConvertible adoption
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
guard let cString = sqlite3_column_text(sqliteStatement, index) else {
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 {
fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
}
self.dateComponents = components.dateComponents
self.format = components.format
}
// MARK: - DatabaseValueConvertible adoption
@@ -79,7 +99,7 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
let year = dateComponents.year ?? 0
let month = dateComponents.month ?? 1
let day = dateComponents.day ?? 1
dateString = NSString(format: "%04d-%02d-%02d", year, month, day) as String
dateString = String(format: "%04d-%02d-%02d", year, month, day)
default:
dateString = nil
}
@@ -89,23 +109,23 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
case .YMD_HM, .HM:
let hour = dateComponents.hour ?? 0
let minute = dateComponents.minute ?? 0
timeString = NSString(format: "%02d:%02d", hour, minute) as String
timeString = String(format: "%02d:%02d", hour, minute)
case .YMD_HMS, .HMS:
let hour = dateComponents.hour ?? 0
let minute = dateComponents.minute ?? 0
let second = dateComponents.second ?? 0
timeString = NSString(format: "%02d:%02d:%02d", hour, minute, second) as String
timeString = String(format: "%02d:%02d:%02d", hour, minute, second)
case .YMD_HMSS, .HMSS:
let hour = dateComponents.hour ?? 0
let minute = dateComponents.minute ?? 0
let second = dateComponents.second ?? 0
let nanosecond = dateComponents.nanosecond ?? 0
timeString = NSString(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) as String
timeString = String(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0)))
default:
timeString = nil
}
return [dateString, timeString].flatMap { $0 }.joined(separator: " ").databaseValue
return [dateString, timeString].compactMap { $0 }.joined(separator: " ").databaseValue
}
/// Returns a DatabaseDateComponents if *dbValue* contains a
@@ -131,158 +151,6 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
return nil
}
var dateComponents = DateComponents()
let scanner = Scanner(string: string)
scanner.charactersToBeSkipped = CharacterSet()
let hasDate: Bool
// YYYY or HH
var initialNumber: Int = 0
if !scanner.scanInt(&initialNumber) {
return nil
}
switch scanner.scanLocation {
case 2:
// HH
hasDate = false
let hour = initialNumber
if hour >= 0 && hour <= 23 {
dateComponents.hour = hour
} else {
return nil
}
case 4:
// YYYY
hasDate = true
let year = initialNumber
if year >= 0 && year <= 9999 {
dateComponents.year = year
} else {
return nil
}
// -
if !scanner.scanString("-", into: nil) {
return nil
}
// MM
var month: Int = 0
if scanner.scanInt(&month) && month >= 1 && month <= 12 {
dateComponents.month = month
} else {
return nil
}
// -
if !scanner.scanString("-", into: nil) {
return nil
}
// DD
var day: Int = 0
if scanner.scanInt(&day) && day >= 1 && day <= 31 {
dateComponents.day = day
} else {
return nil
}
// YYYY-MM-DD
if scanner.isAtEnd {
return DatabaseDateComponents(dateComponents, format: .YMD)
}
// T/space
if !scanner.scanString("T", into: nil) && !scanner.scanString(" ", into: nil) {
return nil
}
// HH
var hour: Int = 0
if scanner.scanInt(&hour) && hour >= 0 && hour <= 23 {
dateComponents.hour = hour
} else {
return nil
}
default:
return nil
}
// :
if !scanner.scanString(":", into: nil) {
return nil
}
// MM
var minute: Int = 0
if scanner.scanInt(&minute) && minute >= 0 && minute <= 59 {
dateComponents.minute = minute
} else {
return nil
}
// [YYYY-MM-DD] HH:MM
if scanner.isAtEnd {
if hasDate {
return DatabaseDateComponents(dateComponents, format: .YMD_HM)
} else {
return DatabaseDateComponents(dateComponents, format: .HM)
}
}
// :
if !scanner.scanString(":", into: nil) {
return nil
}
// SS
var second: Int = 0
if scanner.scanInt(&second) && second >= 0 && second <= 59 {
dateComponents.second = second
} else {
return nil
}
// [YYYY-MM-DD] HH:MM:SS
if scanner.isAtEnd {
if hasDate {
return DatabaseDateComponents(dateComponents, format: .YMD_HMS)
} else {
return DatabaseDateComponents(dateComponents, format: .HMS)
}
}
// .
if !scanner.scanString(".", into: nil) {
return nil
}
// SSS
var millisecondDigits: NSString? = nil
if scanner.scanCharacters(from: .decimalDigits, into: &millisecondDigits), var millisecondDigits = millisecondDigits {
if millisecondDigits.length > 3 {
millisecondDigits = NSString(string: millisecondDigits.substring(to: 3))
}
dateComponents.nanosecond = millisecondDigits.integerValue * 1_000_000
} else {
return nil
}
// [YYYY-MM-DD] HH:MM:SS.SSS
if scanner.isAtEnd {
if hasDate {
return DatabaseDateComponents(dateComponents, format: .YMD_HMSS)
} else {
return DatabaseDateComponents(dateComponents, format: .HMSS)
}
}
// Unknown format
return nil
return SQLiteDateParser().components(from: string)
}
}
+30
View File
@@ -1,5 +1,11 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
#if !os(Linux)
/// NSDate is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension NSDate : DatabaseValueConvertible {
@@ -26,6 +32,7 @@ extension NSDate : DatabaseValueConvertible {
return cast(date)
}
}
#endif
/// Date is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
@@ -108,6 +115,29 @@ extension Date : DatabaseValueConvertible {
}
}
extension Date: StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_INTEGER, SQLITE_FLOAT:
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 {
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
}
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
default:
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
}
}
}
/// The DatabaseDate date formatter for stored dates.
private let storageDateFormatter: DateFormatter = {
let formatter = DateFormatter()
@@ -1,3 +1,4 @@
#if !os(Linux)
import Foundation
/// NSData is convertible to and from DatabaseValue.
@@ -17,3 +18,4 @@ extension NSData : DatabaseValueConvertible {
return cast(data)
}
}
#endif
@@ -1,3 +1,4 @@
#if !os(Linux)
import Foundation
private let integerRoundingBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
@@ -65,3 +66,4 @@ extension NSNumber : DatabaseValueConvertible {
}
}
}
#endif
@@ -1,3 +1,4 @@
#if !os(Linux)
import Foundation
/// NSString adopts DatabaseValueConvertible
@@ -16,3 +17,4 @@ extension NSString : DatabaseValueConvertible {
return self.init(string: string)
}
}
#endif
@@ -0,0 +1,140 @@
import Foundation
// inspired by: http://jordansmith.io/performant-date-parsing/
class SQLiteDateParser {
private struct ParserComponents {
var year: Int32 = 0
var month: Int32 = 0
var day: Int32 = 0
var hour: Int32 = 0
var minute: Int32 = 0
var second: Int32 = 0
var nanosecond = ContiguousArray<CChar>(repeating: 0, count: 10) // 9 digits, and trailing \0
}
func components(from dateString: String) -> DatabaseDateComponents? {
return dateString.withCString { cString in
components(cString: cString, length: strlen(cString))
}
}
func components(cString: UnsafePointer<CChar>, length: Int) -> DatabaseDateComponents? {
assert(strlen(cString) == length)
guard length >= 5 else { return nil }
if cString.advanced(by: 4).pointee == 45 /* '-' */ {
return datetimeComponents(cString: cString, length: length)
}
if cString.advanced(by: 2).pointee == 58 /* ':' */ {
return timeComponents(cString: cString, length: length)
}
return nil
}
// - 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
private func datetimeComponents(cString: UnsafePointer<CChar>, length: Int) -> DatabaseDateComponents? {
var parserComponents = ParserComponents()
// TODO: Get rid of this pyramid when SE-0210 has shipped
let parseCount = withUnsafeMutablePointer(to: &parserComponents.year) { yearP in
withUnsafeMutablePointer(to: &parserComponents.month) { monthP in
withUnsafeMutablePointer(to: &parserComponents.day) { dayP in
withUnsafeMutablePointer(to: &parserComponents.hour) { hourP in
withUnsafeMutablePointer(to: &parserComponents.minute) { minuteP in
withUnsafeMutablePointer(to: &parserComponents.second) { secondP in
parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in
withVaList([yearP, monthP, dayP, hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in
vsscanf(cString, "%4d-%2d-%2d%*1[ T]%2d:%2d:%2d.%9s", pointer)
}
}
}
}
}
}
}
}
guard parseCount >= 3 else { return nil }
var components = DateComponents()
components.year = Int(parserComponents.year)
components.month = Int(parserComponents.month)
components.day = Int(parserComponents.day)
guard parseCount >= 5 else { return DatabaseDateComponents(components, format: .YMD) }
components.hour = Int(parserComponents.hour)
components.minute = Int(parserComponents.minute)
guard parseCount >= 6 else { return DatabaseDateComponents(components, format: .YMD_HM) }
components.second = Int(parserComponents.second)
guard parseCount >= 7 else { return DatabaseDateComponents(components, format: .YMD_HMS) }
components.nanosecond = nanosecondsInt(for: parserComponents.nanosecond)
return DatabaseDateComponents(components, format: .YMD_HMSS)
}
// - HH:MM
// - HH:MM:SS
// - HH:MM:SS.SSS
private func timeComponents(cString: UnsafePointer<CChar>, length: Int) -> DatabaseDateComponents? {
var parserComponents = ParserComponents()
// TODO: Get rid of this pyramid when SE-0210 has shipped
let parseCount = withUnsafeMutablePointer(to: &parserComponents.hour) { hourP in
withUnsafeMutablePointer(to: &parserComponents.minute) { minuteP in
withUnsafeMutablePointer(to: &parserComponents.second) { secondP in
parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in
withVaList([hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in
vsscanf(cString, "%2d:%2d:%2d.%9s", pointer)
}
}
}
}
}
guard parseCount >= 2 else { return nil }
var components = DateComponents()
components.hour = Int(parserComponents.hour)
components.minute = Int(parserComponents.minute)
guard parseCount >= 3 else { return DatabaseDateComponents(components, format: .HM) }
components.second = Int(parserComponents.second)
guard parseCount >= 4 else { return DatabaseDateComponents(components, format: .HMS) }
guard let nanoseconds = nanosecondsInt(for: parserComponents.nanosecond) else { return nil }
components.nanosecond = nanoseconds
return DatabaseDateComponents(components, format: .HMSS)
}
private func nanosecondsInt(for nanosecond: ContiguousArray<CChar>) -> Int? {
// truncate after the third digit
var result = 0
let multipliers = [100_000_000, 10_000_000, 1_000_000, 100_000, 10_000, 1_000, 100, 10, 1]
for (char, multiplier) in zip(nanosecond.prefix(3), multipliers) {
if char == 0 { return result }
let digit = Int(char) - 48 /* '0' */
guard (0...9).contains(digit) else { return nil }
result += multiplier * digit
}
return result
}
}
+2
View File
@@ -1,5 +1,6 @@
import Foundation
#if !os(Linux)
/// NSURL stores its absoluteString in the database.
extension NSURL : DatabaseValueConvertible {
@@ -17,6 +18,7 @@ extension NSURL : DatabaseValueConvertible {
return cast(URL(string: string))
}
}
#endif
/// URL stores its absoluteString in the database.
extension URL : DatabaseValueConvertible { }
+70 -8
View File
@@ -1,9 +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
@@ -12,14 +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
}
}
}
#endif
/// UUID adopts 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
}
return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self))
}
}
/// UUID adopts DatabaseValueConvertible
extension UUID : DatabaseValueConvertible { }
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:
+388 -131
View File
@@ -29,13 +29,12 @@ extension Database {
/// Registers a closure to be executed after the next or current
/// transaction completion.
///
/// dbQueue.inTransaction { db in
/// try dbQueue.write { db in
/// db.afterNextTransactionCommit { _ in
/// print("commit did succeed")
/// print("success")
/// }
/// ...
/// return .commit // prints "commit did succeed"
/// }
/// } // prints "success"
///
/// If the transaction is rollbacked, the closure is not executed.
///
@@ -51,11 +50,7 @@ extension Database {
// Ignore individual changes and transaction rollbacks
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false }
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
func databaseDidChange(with event: DatabaseEvent) { }
func databaseWillCommit() throws { }
func databaseDidRollback(_ db: Database) { }
// On commit, run closure
@@ -80,6 +75,8 @@ extension Database {
}
}
// MARK: - DatabaseObservationBroker
/// This class provides support for transaction observers.
///
/// Let's have a detailed look at how a transaction observer is notified:
@@ -102,11 +99,11 @@ extension Database {
///
/// Then a statement is executed:
///
/// try db.execute("INSERT INTO documents ...")
/// try db.execute("INSERT INTO document ...")
///
/// The observation process starts when the statement is *compiled*:
/// sqlite3_set_authorizer tells that the statement performs insertion into the
/// `documents` table. Generally speaking, statements may have many effects, by
/// `document` table. Generally speaking, statements may have many effects, by
/// the mean of foreign key actions and SQL triggers. SQLite takes care of
/// exposing all those effects to sqlite3_set_authorizer.
///
@@ -131,7 +128,7 @@ extension Database {
///
/// Then another statement is executed:
///
/// try db.execute("INSERT INTO documents ...")
/// try db.execute("INSERT INTO document ...")
///
/// This time, when the statement is *executed* and SQLite tells that a row has
/// been inserted, the broker buffers the change event instead of immediately
@@ -163,74 +160,138 @@ extension Database {
/// After the statement *has been executed*, the broker calls
/// observer.databaseDidCommit().
class DatabaseObservationBroker {
unowned var database: Database
var savepointStack = SavepointStack()
var transactionState: TransactionState = .none
var transactionObservations = [TransactionObservation]()
var activeTransactionObservations = [TransactionObservation]()
private unowned var database: Database
private var savepointStack = SavepointStack()
private var transactionState: TransactionState = .none
private var transactionObservations: [TransactionObservation] = []
private var statementObservations: [StatementObservation] = [] {
didSet { observesDatabaseChanges = !statementObservations.isEmpty }
}
private var observesDatabaseChanges: Bool = false {
didSet {
if observesDatabaseChanges == oldValue { return }
if observesDatabaseChanges {
installUpdateHook()
} else {
uninstallUpdateHook()
}
}
}
init(_ database: Database) {
self.database = database
}
func setup() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
do {
try broker.databaseWillCommit()
broker.transactionState = .commit
// Next step: updateStatementDidExecute()
return 0
} catch {
broker.transactionState = .cancelledCommit(error)
// Next step: sqlite3_rollback_hook callback
return 1
}
}, brokerPointer)
sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
switch broker.transactionState {
case .cancelledCommit:
// Next step: updateStatementDidFail()
break
default:
broker.transactionState = .rollback
// Next step: updateStatementDidExecute()
}
}, brokerPointer)
}
// MARK: - Transaction observers
func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent) {
transactionObservations.append(TransactionObservation(observer: transactionObserver, extent: extent))
if transactionObservations.count == 1 {
installUpdateHook()
}
}
func remove(transactionObserver: TransactionObserver) {
transactionObservations.removeFirst { $0.isWrapping(transactionObserver) }
if transactionObservations.isEmpty {
uninstallUpdateHook()
}
func disableUntilNextTransaction(transactionObserver: TransactionObserver) {
if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver)}) {
observation.isDisabled = true
statementObservations.removeFirst { $0.0 === observation }
}
}
// MARK: - Statement execution
func updateStatementWillExecute(_ statement: UpdateStatement) {
// Activate the transaction observers that are interested in the actions
// performed by the statement.
let databaseEventKinds = statement.databaseEventKinds
activeTransactionObservations = transactionObservations.filter { observer in
return databaseEventKinds.contains(where: observer.observes)
// As statement executes, it may trigger database changes that will
// be notified to transaction observers. As a consequence, observers
// may disable themselves with stopObservingDatabaseChangesUntilNextTransaction()
//
// This method takes no argument, and requires access to the "current
// broker", which is a per-thread global stored in
// SchedulingWatchdog.current:
SchedulingWatchdog.current!.databaseObservationBroker = self
// Fill statementObservations with observations that are interested in
// the kind of events performed by the statement.
//
// Those statementObservations will be notified of individual changes
// in databaseWillChange() and databaseDidChange().
let eventKinds = statement.databaseEventKinds
// If any observer observes row deletions, we'll have to disable
// [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
// so that observers are notified.
var observesRowDeletion = false
switch eventKinds.count {
case 0:
// Statement has no effect on any database table.
//
// For example: PRAGMA foreign_keys = ON
statementObservations = []
case 1:
// We'll execute a simple statement without any side effect.
// Eventual database events will thus all have the same kind. All
// detabase events can be notified to interested observations.
//
// For example, if one observes all deletions in the table T, then
// all individual deletions of DELETE FROM T are notified:
let eventKind = eventKinds[0]
statementObservations = transactionObservations.compactMap { observation in
guard observation.observes(eventsOfKind: eventKind) else {
// observation is not interested
return nil
}
if case .delete = eventKind {
observesRowDeletion = true
}
// observation will be notified of all individual events
return (observation, DatabaseEventPredicate.true)
}
default:
// We'll execute a complex statement with side effects performed by
// an SQL trigger or a foreign key action. Eventual database events
// may not all have the same kind: we need to filter them before
// notifying interested observations.
//
// For example, if DELETE FROM T1 generates deletions in T1 and T2
// by the mean of a foreign key action, then when one only observes
// deletions in T1, one must not be notified of deletions in T2:
statementObservations = transactionObservations.compactMap { observation in
let observedKinds = eventKinds.filter(observation.observes)
if observedKinds.isEmpty {
// observation is not interested
return nil
}
for eventKind in observedKinds {
if case .delete = eventKind {
observesRowDeletion = true
break
}
}
// observation will only be notified of individual events that
// match one of the observed kinds.
return (observation, DatabaseEventPredicate.matching(observedKinds))
}
}
if observesRowDeletion {
database.authorizer = TruncateOptimizationBlocker()
} else {
database.authorizer = nil
}
}
func updateStatementDidFail(_ statement: UpdateStatement) throws {
// Wait for next statement
activeTransactionObservations = []
// Undo updateStatementWillExecute
statementObservations = []
database.authorizer = nil
SchedulingWatchdog.current!.databaseObservationBroker = nil
// Reset transactionState before databaseDidRollback eventually
// executes other statements.
let transactionState = self.transactionState
@@ -251,9 +312,11 @@ class DatabaseObservationBroker {
}
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
// Wait for next statement
activeTransactionObservations = []
// Undo updateStatementWillExecute
statementObservations = []
database.authorizer = nil
SchedulingWatchdog.current!.databaseObservationBroker = nil
// Has statement any effect on transaction/savepoints?
if let transactionEffect = statement.transactionEffect {
switch transactionEffect {
@@ -267,7 +330,7 @@ class DatabaseObservationBroker {
// BEGIN DEFERRED TRANSACTION; COMMIT
//
// This special case has a dedicated handling:
return try emptyDeferredTransactionDidCommit()
return try databaseDidCommitEmptyDeferredTransaction()
}
case .rollbackTransaction:
@@ -287,7 +350,7 @@ class DatabaseObservationBroker {
// SAVEPOINT foo; RELEASE SAVEPOINT foo
//
// This special case has a dedicated handling:
return try emptyDeferredTransactionDidCommit()
return try databaseDidCommitEmptyDeferredTransaction()
}
if savepointStack.isEmpty {
@@ -319,30 +382,41 @@ class DatabaseObservationBroker {
private func databaseWillChange(with event: DatabasePreUpdateEvent) {
if savepointStack.isEmpty {
// Notify now
for observation in activeTransactionObservations {
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
observation.databaseWillChange(with: event)
}
} else {
// Buffer
savepointStack.eventsBuffer.append((event: event.copy(), observations: activeTransactionObservations))
savepointStack.eventsBuffer.append((event: event.copy(), statementObservations: statementObservations))
}
}
#endif
// Called from sqlite3_update_hook
private func databaseDidChange(with event: DatabaseEvent) {
// We're about to call the databaseDidChange(with:) method of
// transaction observers. In this method, observers may disable
// themselves with stopObservingDatabaseChangesUntilNextTransaction()
//
// This method takes no argument, and requires access to the "current
// broker", which is a per-thread global stored in
// SchedulingWatchdog.current:
assert(SchedulingWatchdog.current?.databaseObservationBroker != nil)
if savepointStack.isEmpty {
// Notify now
for observation in activeTransactionObservations {
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
observation.databaseDidChange(with: event)
}
} else {
// Buffer
savepointStack.eventsBuffer.append((event: event.copy(), observations: activeTransactionObservations))
savepointStack.eventsBuffer.append((event: event.copy(), statementObservations: statementObservations))
}
}
// Called from sqlite3_commit_hook and emptyDeferredTransactionDidCommit()
// MARK: - End of transaction
// Called from sqlite3_commit_hook and databaseDidCommitEmptyDeferredTransaction()
private func databaseWillCommit() throws {
notifyBufferedEvents()
for observation in transactionObservations {
@@ -350,17 +424,6 @@ class DatabaseObservationBroker {
}
}
private func notifyBufferedEvents() {
let eventsBuffer = savepointStack.eventsBuffer
savepointStack.clear()
for (event, observations) in eventsBuffer {
for observation in observations {
event.send(to: observation)
}
}
}
// Called from updateStatementDidExecute
private func databaseDidCommit() {
savepointStack.clear()
@@ -368,11 +431,11 @@ class DatabaseObservationBroker {
for observation in transactionObservations {
observation.databaseDidCommit(database)
}
cleanupTransactionObservations()
databaseDidEndTransaction()
}
// Called from updateStatementDidExecute
private func emptyDeferredTransactionDidCommit() throws {
private func databaseDidCommitEmptyDeferredTransaction() throws {
// A statement that ends a transaction has been executed. But for
// SQLite, no transaction at all has started, and sqlite3_commit_hook
// was not triggered:
@@ -404,6 +467,7 @@ class DatabaseObservationBroker {
// even if we actually execute an empty deferred transaction.
//
// For better or for worse, let's simulate a transaction:
do {
try databaseWillCommit()
databaseDidCommit()
@@ -422,11 +486,115 @@ class DatabaseObservationBroker {
observation.databaseDidRollback(database)
}
}
cleanupTransactionObservations()
databaseDidEndTransaction()
}
/// Remove transaction observers that have stopped observing transaction,
/// and uninstall SQLite update hooks if there is no remaining observers.
private func databaseDidEndTransaction() {
transactionObservations = transactionObservations.filter { $0.isObserving }
// Undo disableUntilNextTransaction(transactionObserver:)
for observation in transactionObservations {
observation.isDisabled = false
}
}
private func notifyBufferedEvents() {
// We're about to call the databaseDidChange(with:) method of
// transaction observers. In this method, observers may disable
// themselves with stopObservingDatabaseChangesUntilNextTransaction()
//
// This method takes no argument, and requires access to the "current
// broker", which is a per-thread global stored in
// SchedulingWatchdog.current.
//
// Normally, notifyBufferedEvents() is called as part of statement
// execution, and the current broker has been set in
// updateStatementWillExecute(). An assertion should be enough:
//
// assert(SchedulingWatchdog.current?.databaseObservationBroker != nil)
//
// But we have to deal with a particular case:
//
// let journalMode = String.fetchOne(db, "PRAGMA journal_mode = wal")
//
// It runs a SelectStatement, not an UpdateStatement. But this not why
// this case is particular. What is unexpected is that it triggers
// the commit hook when the "PRAGMA journal_mode = wal" statement is
// finalized, long after it has executed:
//
// 1. Statement.deinit()
// 2. sqlite3_finalize()
// 3. commit hook
// 4. DatabaseObservationBroker.databaseWillCommit()
// 5. DatabaseObservationBroker.notifyBufferedEvents()
//
// I don't know if this behavior is something that can be relied
// upon. One would naively expect, for example, that changing the
// journal mode would trigger the commit hook in sqlite3_step(),
// not in sqlite3_finalize().
//
// Anyway: in this scenario, updateStatementWillExecute() has not been
// called, and the current broker is nil.
//
// Let's not try to outsmart SQLite, and build a complex state machine.
// Instead, let's just make sure that the current broker is set to self
// when this method is called.
let watchDog = SchedulingWatchdog.current!
watchDog.databaseObservationBroker = self
defer {
watchDog.databaseObservationBroker = nil
}
// Now we can safely notify:
let eventsBuffer = savepointStack.eventsBuffer
savepointStack.clear()
for (event, statementObservations) in eventsBuffer {
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
event.send(to: observation)
}
}
}
// MARK: - SQLite hooks
func installCommitAndRollbackHooks() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
do {
try broker.databaseWillCommit()
broker.transactionState = .commit
// Next step: updateStatementDidExecute()
return 0
} catch {
broker.transactionState = .cancelledCommit(error)
// Next step: sqlite3_rollback_hook callback
return 1
}
}, brokerPointer)
sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
switch broker.transactionState {
case .cancelledCommit:
// Next step: updateStatementDidFail()
break
default:
broker.transactionState = .rollback
// Next step: updateStatementDidExecute()
}
}, brokerPointer)
}
private func installUpdateHook() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_update_hook(database.sqliteConnection, { (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
broker.databaseDidChange(with: DatabaseEvent(
@@ -457,16 +625,7 @@ class DatabaseObservationBroker {
#endif
}
/// Remove transaction observers that have stopped observing transaction,
/// and uninstall SQLite update hooks if there is no remaining observers.
private func cleanupTransactionObservations() {
transactionObservations = transactionObservations.filter { $0.isObserving }
if transactionObservations.isEmpty {
uninstallUpdateHook()
}
}
/// The states that keep track of transaction completions
/// The various states of SQLite transactions
enum TransactionState {
case none
case commit
@@ -475,6 +634,8 @@ class DatabaseObservationBroker {
}
}
// MARK: - TransactionObserver
/// A transaction observer is notified of all changes and transactions committed
/// or rollbacked on a database.
///
@@ -487,13 +648,18 @@ public protocol TransactionObserver : class {
/// Notifies a database change (insert, update, or delete).
///
/// The change is pending until the end of the current transaction, notified
/// to databaseWillCommit, databaseDidCommit and databaseDidRollback.
/// The change is pending until the current transaction ends. See
/// databaseWillCommit, databaseDidCommit and databaseDidRollback.
///
/// This method is called on the database queue.
/// This method is called in a protected dispatch queue, serialized will all
/// database updates.
///
/// The event is only valid for the duration of this method call. If you
/// need to keep it longer, store a copy of its properties.
/// need to keep it longer, store a copy: `event.copy()`
///
/// The observer has an opportunity to stop receiving further change events
/// from the current transaction by calling the
/// stopObservingDatabaseChangesUntilNextTransaction() method.
///
/// - warning: this method must not change the database.
func databaseDidChange(with event: DatabaseEvent)
@@ -530,34 +696,80 @@ public protocol TransactionObserver : class {
/// This callback is mostly useful for calculating detailed change
/// information for a row, and provides the initial / final values.
///
/// This method is called on the database queue.
/// This method is called in a protected dispatch queue, serialized will all
/// database updates.
///
/// The event is only valid for the duration of this method call. If you
/// need to keep it longer, store a copy of its properties.
/// need to keep it longer, store a copy: `event.copy()`
///
/// - warning: this method must not change the database.
///
/// Availability Info:
/// **Availability Info**
///
/// Requires SQLite 3.13.0 +
/// Compiled with option SQLITE_ENABLE_PREUPDATE_HOOK
/// Requires SQLite 3.13.0 +
/// Compiled with option SQLITE_ENABLE_PREUPDATE_HOOK
///
/// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library
/// does not have this enabled, so you'll need to compile your own
/// copy using GRDBCustomSQLite. See the README.md in /SQLiteCustom/
///
/// The databaseDidChangeWithEvent callback is always available,
/// and may provide most/all of what you need.
/// (For example, FetchedRecordsController is built without using
/// this functionality.)
/// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library
/// does not have this enabled, so you'll need to compile your own
/// copy using GRDBCustomSQLite. See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md
///
/// The databaseDidChangeWithEvent callback is always available,
/// and may provide most/all of what you need.
/// (For example, FetchedRecordsController is built without databaseWillChange)
func databaseWillChange(with event: DatabasePreUpdateEvent)
#endif
}
extension TransactionObserver {
/// Default implementation does nothing
public func databaseWillCommit() throws {
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
/// Default implementation does nothing
public func databaseWillChange(with event: DatabasePreUpdateEvent) {
}
#endif
/// After this method has been called, the `databaseDidChange(with:)`
/// method won't be called until the next transaction.
///
/// For example:
///
/// class PlayerObserver: TransactionObserver {
/// var playerTableWasModified = false
///
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
/// return eventKind.tableName == "player"
/// }
///
/// func databaseDidChange(with event: DatabaseEvent) {
/// playerTableWasModified = true
///
/// // It is pointless to keep on tracking further changes:
/// stopObservingDatabaseChangesUntilNextTransaction()
/// }
/// }
///
/// - precondition: This method must be called from `databaseDidChange(with:)`.
public func stopObservingDatabaseChangesUntilNextTransaction() {
guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else {
fatalError("stopObservingDatabaseChangesUntilNextTransaction must be called from the databaseDidChange method")
}
broker.disableUntilNextTransaction(transactionObserver: self)
}
}
// MARK: - TransactionObservation
/// This class manages the observation extent of a transaction observer
final class TransactionObservation {
let extent: Database.TransactionObservationExtent
// A disabled observation is not interested in individual database changes.
// It is still interested in transactions commits & rollbacks.
var isDisabled: Bool = false
private weak var weakObserver: TransactionObserver?
private var strongObserver: TransactionObserver?
private var observer: TransactionObserver? { return strongObserver ?? weakObserver }
@@ -584,10 +796,19 @@ final class TransactionObservation {
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
if isDisabled { return false }
return observer?.observes(eventsOfKind: eventKind) ?? false
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) {
if isDisabled { return }
observer?.databaseWillChange(with: event)
}
#endif
func databaseDidChange(with event: DatabaseEvent) {
if isDisabled { return }
observer?.databaseDidChange(with: event)
}
@@ -601,7 +822,7 @@ final class TransactionObservation {
observer?.databaseDidCommit(db)
case .nextTransaction:
if let observer = self.observer {
// Observer most not get any further notification.
// Observer must not get any further notification.
// So we "forget" the observer before its `databaseDidCommit`
// implementation eventually triggers another database change.
strongObserver = nil
@@ -616,7 +837,7 @@ final class TransactionObservation {
observer?.databaseDidRollback(db)
case .nextTransaction:
if let observer = self.observer {
// Observer most not get any further notification.
// Observer must not get any further notification.
// So we "forget" the observer before its `databaseDidRollback`
// implementation eventually triggers another database change.
strongObserver = nil
@@ -624,16 +845,14 @@ final class TransactionObservation {
}
}
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) {
observer?.databaseWillChange(with: event)
}
#endif
}
/// A kind of database event. See Database.add(transactionObserver:)
/// and DatabaseWriter.add(transactionObserver:).
typealias StatementObservation = (TransactionObservation, DatabaseEventPredicate)
// MARK: - Database events
/// A kind of database event. See the TransactionObserver protocol for
/// more information.
public enum DatabaseEventKind {
/// The insertion of a row in a database table
case insert(tableName: String)
@@ -644,19 +863,16 @@ public enum DatabaseEventKind {
/// The update of a set of columns in a database table
case update(tableName: String, columnNames: Set<String>)
/// Returns whether event has any impact on tables and columns described
/// by selectionInfo.
public func impacts(_ selectionInfo: SelectStatement.SelectionInfo) -> Bool {
var modifiedRegion: DatabaseRegion {
switch self {
case .delete(let tableName):
return selectionInfo.contains(anyColumnFrom: tableName)
return DatabaseRegion(table: tableName)
case .insert(let tableName):
return selectionInfo.contains(anyColumnFrom: tableName)
return DatabaseRegion(table: tableName)
case .update(let tableName, let updatedColumnNames):
return selectionInfo.contains(anyColumnIn: updatedColumnNames, from: tableName)
return DatabaseRegion(table: tableName, columns: updatedColumnNames)
}
}
}
extension DatabaseEventKind {
@@ -672,6 +888,7 @@ extension DatabaseEventKind {
protocol DatabaseEventProtocol {
func send(to observer: TransactionObservation)
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool
}
/// A database event, notified to TransactionObserver.
@@ -689,6 +906,8 @@ public struct DatabaseEvent {
case update = 23
}
private let impl: DatabaseEventImpl
/// The event kind
public let kind: Kind
@@ -722,14 +941,22 @@ public struct DatabaseEvent {
init(kind: Kind, rowID: Int64, databaseNameCString: UnsafePointer<Int8>?, tableNameCString: UnsafePointer<Int8>?) {
self.init(kind: kind, rowID: rowID, impl: MetalDatabaseEventImpl(databaseNameCString: databaseNameCString, tableNameCString: tableNameCString))
}
private let impl: DatabaseEventImpl
}
extension DatabaseEvent : DatabaseEventProtocol {
func send(to observer: TransactionObservation) {
observer.databaseDidChange(with: self)
}
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool {
switch (kind, databaseEventKind) {
case (.insert, .insert(let tableName)): return self.tableName == tableName
case (.delete, .delete(let tableName)): return self.tableName == tableName
case (.update, .update(let tableName, _)): return self.tableName == tableName
default:
return false
}
}
}
/// Protocol for internal implementation of DatabaseEvent
@@ -883,6 +1110,16 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
func send(to observer: TransactionObservation) {
observer.databaseWillChange(with: self)
}
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool {
switch (kind, databaseEventKind) {
case (.insert, .insert(let tableName)): return self.tableName == tableName
case (.delete, .delete(let tableName)): return self.tableName == tableName
case (.update, .update(let tableName, _)): return self.tableName == tableName
default:
return false
}
}
}
/// Protocol for internal implementation of DatabaseEvent
@@ -1008,6 +1245,25 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
#endif
// A predicate that filters database events
enum DatabaseEventPredicate {
// Yes filter
case `true`
// Only events that match one of those kinds
case matching([DatabaseEventKind])
func evaluate(_ event: DatabaseEventProtocol) -> Bool {
switch self {
case .true:
return true
case .matching(let kinds):
return kinds.contains { event.matchesKind($0) }
}
}
}
// MARK: - SavepointStack
/// The SQLite savepoint stack is described at
/// https://www.sqlite.org/lang_savepoint.html
///
@@ -1018,8 +1274,8 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
/// notifying transaction observers of database events that could be
/// rollbacked.
class SavepointStack {
/// The buffered events. See Database.didChange(with:)
var eventsBuffer: [(event: DatabaseEventProtocol, observations: [TransactionObservation])] = []
/// The buffered events (see DatabaseObservationBroker.databaseDidChange(with:))
var eventsBuffer: [(event: DatabaseEventProtocol, statementObservations: [StatementObservation])] = []
/// The savepoint stack, as an array of tuples (savepointName, index in the eventsBuffer array).
/// Indexes let us drop rollbacked events from the event buffer.
@@ -1072,3 +1328,4 @@ class SavepointStack {
}
}
}
Loaded 100 of 388 files, more files were not shown because too many files have changed in this diff. Show more