Compare commits

...
Author SHA1 Message Date
Gwendal Roué 4c2290f84b Move Design Notes 2021-01-28 08:29:48 +01:00
Gwendal Roué efc8e4bbf9 Fetching players 2021-01-28 08:27:41 +01:00
Gwendal Roué 5c986b142b Saving playerrs 2021-01-28 08:10:30 +01:00
Gwendal Roué 4ec77f8d02 TODO 2021-01-28 08:10:30 +01:00
Gwendal Roué d7dfb4c2ed Precise documentation 2021-01-28 08:10:30 +01:00
Gwendal Roué f4a32edbb9 TODO 2021-01-28 08:10:30 +01:00
Gwendal Roué 8bb9ef0849 Indent raw SQL versions 2021-01-28 08:10:30 +01:00
Gwendal Roué 0210144ea9 Extract Player definition 2021-01-28 08:10:30 +01:00
Gwendal Roué 2842bc92ca Wording 2021-01-28 08:10:30 +01:00
Gwendal Roué 2ca857d895 Fix typo 2021-01-28 08:10:30 +01:00
Gwendal Roué 95ec107134 Group design notes at the end of the chapter 2021-01-28 08:10:30 +01:00
Gwendal Roué 18c65eecb6 Wording 2021-01-28 08:10:30 +01:00
Gwendal Roué 3c1ab47843 Group design notes at the end of the chapter 2021-01-28 08:10:30 +01:00
Gwendal Roué 6b706bbc85 Group design notes 2021-01-28 08:10:30 +01:00
Gwendal Roué e6435ade96 Talk about sample code 2021-01-28 08:10:30 +01:00
Gwendal Roué c854b5a88a Wording 2021-01-28 08:10:30 +01:00
Gwendal Roué f2d51d2feb The Database Service rewrite 2021-01-28 08:10:30 +01:00
Gwendal Roué 95cd6f3c4f Introduction 2021-01-28 08:10:30 +01:00
Gwendal Roué 4a0d8602e2 Clarify the tutorial scope 2021-01-28 08:10:30 +01:00
Gwendal Roué a83f76be10 Remove a missing logical link 2021-01-28 08:10:30 +01:00
Gwendal Roué 10420e6426 Wording 2021-01-28 08:10:30 +01:00
Gwendal Roué 5ab90c1b6c More achievements 2021-01-28 08:10:30 +01:00
Gwendal Roué 5c70477a04 SwiftUI use in-memory databases 2021-01-28 08:10:30 +01:00
Gwendal Roué cb4a0f349e Rename the tutorial 2021-01-28 08:10:30 +01:00
Gwendal Roué 9a0db52c9b The Initial Application State 2021-01-28 08:10:30 +01:00
Gwendal Roué 7cf7300129 Fix typo and wording 2021-01-28 08:10:30 +01:00
Gwendal Roué 6fbeed1a2a Wording 2021-01-28 08:10:30 +01:00
Gwendal Roué 1defe3aaf1 Why columns are hidden 2021-01-28 08:10:30 +01:00
Gwendal Roué 074af18152 Wording 2021-01-28 08:10:30 +01:00
Gwendal Roué 43c9aa3474 Wording 2021-01-28 08:10:30 +01:00
Gwendal Roué d95a76a47a Compare with ActiveRecord 2021-01-28 08:10:30 +01:00
Gwendal Roué ae8c1f11a9 Player requests 2021-01-28 08:10:30 +01:00
Gwendal Roué 4decdd7dea SQL Interpolation: add support for collations 2021-01-28 08:10:30 +01:00
Gwendal Roué 1d41807e25 Add link 2021-01-28 08:10:30 +01:00
Gwendal Roué 571a70e073 Organization 2021-01-28 08:10:30 +01:00
Gwendal Roué 2822c959f8 Repurpose the focus of the tutorial 2021-01-28 08:10:30 +01:00
Gwendal Roué d8c5d85fcb Postpone name collation until the fetch 2021-01-28 08:10:30 +01:00
Gwendal Roué 3f493fa7a8 Mention ACID robustness against errors and crashes 2021-01-28 08:10:29 +01:00
Gwendal Roué cecc3cffdc Emphasis 2021-01-28 08:10:29 +01:00
Gwendal Roué 5ea0cf6cdd Introduce fetchable records 2021-01-28 08:10:29 +01:00
Gwendal Roué 3ebbddb9f3 Tip about helper methods 2021-01-28 08:10:29 +01:00
Gwendal Roué 238f01725b SQL version of AppDatabase.refreshPlayers() 2021-01-28 08:10:29 +01:00
Gwendal Roué 51b975e872 Fix typo 2021-01-28 08:10:29 +01:00
Gwendal Roué 4b9643daf2 Modifying Players chapter 2021-01-28 08:10:29 +01:00
Gwendal Roué 6daf078fc3 Fix focus 2021-01-28 08:10:29 +01:00
Gwendal Roué 7aced9b925 Documentation 2021-01-28 08:10:29 +01:00
Gwendal Roué 16fc88ba09 Wording 2021-01-28 08:10:29 +01:00
Gwendal Roué 4ac7e3d15c Avoid "such as" repetition 2021-01-28 08:10:29 +01:00
Gwendal Roué 48b8c1ee14 More notes about SQL injection prevention 2021-01-28 08:10:29 +01:00
Gwendal Roué 1af981255d How to deal with missing Swift versions of SQLite functions or operators? 2021-01-28 08:10:29 +01:00
Gwendal Roué 6a07361614 Indent design notes 2021-01-28 08:10:29 +01:00
Gwendal Roué f32f5e2d7b Describe the tutorial audience 2021-01-28 08:10:29 +01:00
Gwendal Roué 322959f1c4 Deleting players 2021-01-28 08:10:29 +01:00
Gwendal Roué eaca12aed1 Fix typo 2021-01-28 08:10:29 +01:00
Gwendal Roué 96a8b46214 Wording 2021-01-28 08:10:29 +01:00
Gwendal Roué 7f2f4fdfcc Wording 2021-01-28 08:10:29 +01:00
Gwendal Roué ceccbb38fb Wording 2021-01-28 08:10:29 +01:00
Gwendal Roué af21c82dd6 Better explain why id is autoincremented 2021-01-28 08:10:29 +01:00
Gwendal Roué b2573a12bc Explain why id is autoincremented 2021-01-28 08:10:29 +01:00
Gwendal Roué d00de45e4f Links & wording 2021-01-28 08:10:29 +01:00
Gwendal Roué 6512e7bf61 Fix typo 2021-01-28 08:10:29 +01:00
Gwendal Roué 1cd88114ec Rewrite introduction to migrations 2021-01-28 08:10:29 +01:00
Gwendal Roué 86cf024a78 AppDatabase error handling suggestion 2021-01-28 08:10:29 +01:00
Gwendal Roué afdde192cd Rewrite the AppDatabase introduction 2021-01-28 08:10:29 +01:00
Gwendal Roué 0b321dfedf Rewrite the introduction 2021-01-28 08:10:29 +01:00
Gwendal Roué 7617bb258d Getting Started tutorial 2021-01-28 08:10:29 +01:00
Gwendal Roué 104466170b Demo app feeds from a single observation 2021-01-28 08:10:29 +01:00
Gwendal Roué 4b5a1340aa Demo apps: store the database in its own folder
This is a recommended good practice
2021-01-28 08:10:29 +01:00
Gwendal Roué 6ea56060a2 Merge branch 'master' into development 2021-01-27 19:46:16 +01:00
Gwendal Roué 3733648598 [skip travis] Remove all details about SPM installation (#913) 2021-01-27 14:05:08 +01:00
Gwendal Roué 40341d4e98 Merge branch 'master' into development 2021-01-23 17:47:04 +01:00
Gwendal Roué 5393d97033 [skip travis] Update BRAG.md 2021-01-23 17:45:54 +01:00
Gwendal Roué 8bf9e5e30f Decouple associations from TableRecord
Associations is generic for type safety, not for defining the association (just as QueryInterfaceRequest)
2021-01-23 09:48:18 +01:00
Gwendal Roué bc5ba1fda5 Merge branch 'development' 2021-01-21 08:23:18 +01:00
Gwendal Roué 034cf065c1 Merge pull request #912 from groue/dev/demo-test
Add tests to the demo apps
2021-01-21 08:22:47 +01:00
Gwendal Roué d7743d0a56 Documentation 2021-01-21 08:21:48 +01:00
Gwendal Roué 5ed0a4a6ed Test that the SwiftUI demo app feeds on immediate publishers 2021-01-21 08:17:02 +01:00
Gwendal Roué dd2e8bb063 Documentation 2021-01-21 08:04:19 +01:00
Gwendal Roué 790b678c74 Documentation 2021-01-20 19:51:03 +01:00
Gwendal Roué abb50a0786 Restore fileprivate Player.Columns 2021-01-20 19:47:04 +01:00
Gwendal Roué 2862edcea8 Documentation 2021-01-20 19:42:32 +01:00
Gwendal Roué 91c17aca41 GRDBCombineDemo tests 2021-01-20 19:14:27 +01:00
Gwendal Roué fc546e25e2 GRDBDemoiOS tests 2021-01-20 19:14:02 +01:00
Gwendal Roué a5b6a0a51f [skip travis] Merge branch 'development' 2021-01-20 07:52:24 +01:00
Gwendal Roué befeb07234 Clarify FTS5Pattern(matchingPrefixPhrase:) behavior 2021-01-20 07:51:00 +01:00
Gwendal Roué 8fe3d41d18 Cleanup and harmonize demo apps 2021-01-20 07:48:05 +01:00
Gwendal Roué 9628eaffb9 Documentation improvement 2021-01-09 17:55:15 +01:00
Gwendal Roué 7be7e1cade Merge branch 'development' 2021-01-09 17:10:55 +01:00
Gwendal Roué db54c567de Performance tests: upgrade Realm, and set deployment target to macOS 10.15 2021-01-09 16:59:34 +01:00
Gwendal Roué db6ea3b85e Change demo app bundle ID
Xcode would no longer accept the previous one.
2021-01-09 16:33:12 +01:00
Gwendal Roué 33f3e868da v5.3.0 2021-01-09 15:47:00 +01:00
Gwendal Roué d4e380c35b Update thank you notice 2021-01-09 14:44:23 +01:00
Gwendal Roué 0dd78f1580 CHANGELOG 2021-01-09 14:43:40 +01:00
Gwendal Roué 267bfb29fe Merge pull request #892 from eburns-vmware/dev/data_passphrase
Provide SQLCipher passphrase as Data
2021-01-09 14:33:46 +01:00
Gwendal Roué 4e551c8c6e Fix Swiftlint errors 2021-01-09 13:09:44 +01:00
Gwendal Roué 554a84cf28 CHANGELOG 2021-01-09 12:57:26 +01:00
Gwendal Roué 2cfd51401a Merge pull request #903 from chrisballinger/patch-2
Fix SPM installation instructions
2021-01-06 09:06:06 +01:00
Chris Ballinger 948f9d3f22 Fix SPM installation instructions 2021-01-05 14:00:20 -08:00
Gwendal Roué 728efd3d67 Update the thank you notice 2021-01-01 13:59:42 +01:00
Gwendal Roué 1b0dd4ae25 CHANGELOG 2021-01-01 13:59:32 +01:00
Gwendal Roué e1b91e0642 Makefile documentation 2021-01-01 13:57:52 +01:00
Gwendal Roué 74b71b024b Merge pull request #901 from wuyuehyang/development
Fix creation of FTS5 tokenizer with arguments
2021-01-01 13:55:08 +01:00
wuyueyang c86d2d654f Fix failed to create unicode61 tokenizer as a wrapped tokenizer 2021-01-01 02:13:11 +08:00
wuyueyang ff6bdc38ef Add test case for custom tokenizer with a unicode61 tokenizer of multiple arguments wrapped 2021-01-01 00:44:00 +08:00
Gwendal Roué ef5b284f11 Remove TODO warning 2020-12-23 12:39:57 +01:00
Gwendal Roué 836efb120f Xcode 12.3 formatting 2020-12-23 12:13:05 +01:00
Gwendal Roué 3a76b84eae Documentation 2020-12-23 11:16:09 +01:00
Gwendal Roué ae17e9f893 Documentation 2020-12-23 11:11:27 +01:00
Gwendal Roué 6ea1e6aeaf Test that pragma tables are not tracked 2020-12-23 10:41:03 +01:00
Gwendal Roué ed32e44bc2 DRY 2020-12-23 10:31:16 +01:00
Gwendal Roué 60a9494434 Fix Swiftlint warnings 2020-12-23 10:10:10 +01:00
Gwendal Roué 51991213ef Stop observing pragma tables 2020-12-23 10:09:00 +01:00
Gwendal Roué dc16fae72e Documentation 2020-12-23 10:08:30 +01:00
Gwendal Roué b485d4d3dc forSingleResult is no longer mandatory 2020-12-23 10:08:16 +01:00
Gwendal Roué 7634d3f950 Documentation 2020-12-23 09:23:37 +01:00
Gwendal Roué 6abbf82a89 So long, visitor pattern! 2020-12-23 09:02:17 +01:00
Ed Burns 2de9b2d9ed Cleaned up documentation and addressed review comments. 2020-12-22 11:29:26 -06:00
Gwendal Roué cc0611847d Remove the CocoaPods lint job from Travis
It's too slow, and nearly always fails
2020-12-20 08:52:12 +01:00
Gwendal Roué c844438dd6 Xcode 12.2 touch 2020-12-20 08:51:42 +01:00
Gwendal Roué 0d6f68646c Turn warning into a TODO 2020-12-19 13:07:24 +01:00
Gwendal Roué af55215356 Travis: test with Xcode 12.2 2020-12-19 13:02:24 +01:00
Gwendal Roué f4f44c51d9 Makefile: support for Xcode 12.3 2020-12-19 11:18:46 +01:00
Ed Burns 77a1becba1 Fixed error in README. Sorry. 2020-12-17 17:17:26 -06:00
Ed Burns 5546961c8c Test fixes and cleanup. 2020-12-17 17:10:39 -06:00
Ed Burns d09571c0ad Added option to specify passphrase as a Data object, added section to README. 2020-12-17 11:19:05 -06:00
Gwendal Roué 9b15011f17 Move singularity test to SQLAssociationCardinality 2020-12-13 18:29:48 +01:00
Gwendal Roué e72007c1dd Make SQLiteral.subquery a promise
This allows us to postpone CTEs definition until a db connection is available
2020-12-13 18:29:43 +01:00
Gwendal Roué ab502baa20 CommonTableExpression.contains(_:) 2020-12-13 18:29:28 +01:00
Gwendal Roué eb0e0d4cdd Merge pull request #885 from groue/dev/cte+871
Robustness of eager loading of to-many associations based on compound foreign keys
2020-12-12 13:31:28 +01:00
Gwendal Roué c8818c1d44 CTEs are experimental 2020-12-12 12:47:44 +01:00
Gwendal Roué 1ff825c861 CHANGELOG 2020-12-12 12:41:10 +01:00
Gwendal Roué 13946f1d8d Remove unclear recommentation 2020-12-12 12:40:50 +01:00
Gwendal Roué 6a68e31903 Clarify handling of NULL in foreign keys 2020-12-12 12:40:50 +01:00
Gwendal Roué 618be9b5e4 Do not support null in foreign keys more than SQLite itself 2020-12-12 12:40:50 +01:00
Gwendal Roué 4a6a2c5495 Fix typo 2020-12-12 12:40:50 +01:00
Gwendal Roué 6082fc4e54 Tests for nullable compound foreign keys 2020-12-12 12:40:50 +01:00
Gwendal Roué 4e8d129162 Only use the CTE technique if foreign key columns are not null 2020-12-12 12:40:50 +01:00
Gwendal Roué 472b5bc604 Test two levels of include(all:) with compound foreign keys 2020-12-12 12:40:50 +01:00
Gwendal Roué cad788e59e Revert "Prefer CommonTableExpression.contains(_:)"
This reverts commit 87a0921586e319ccd4ee02e991ec555c6a915c13.
2020-12-12 12:40:49 +01:00
Gwendal Roué 2cb4cf51c3 TODO 2020-12-12 12:40:49 +01:00
Gwendal Roué 5eff2448bb Documentation 2020-12-12 12:40:49 +01:00
Gwendal Roué aabf6e6247 Prefer CommonTableExpression.contains(_:) 2020-12-12 12:40:49 +01:00
Gwendal Roué 23c93eebdf Remove fixed caveat from documentation 2020-12-12 12:40:49 +01:00
Gwendal Roué 732ec36b67 Documentation 2020-12-12 12:40:49 +01:00
Gwendal Roué f1196bf924 Limit availability of _SQLRowValue.isAvailable 2020-12-12 12:40:49 +01:00
Gwendal Roué fcd6a453f0 Replace CTE request with its table name 2020-12-12 12:40:49 +01:00
Gwendal Roué 85af2deced Document TODOs with row values 2020-12-12 12:40:49 +01:00
Gwendal Roué b70f85d94b Fix #871 2020-12-12 12:40:49 +01:00
Gwendal Roué b715206502 Row values 2020-12-12 12:40:49 +01:00
Gwendal Roué 18885d4ca1 CHANGELOG 2020-12-12 12:40:32 +01:00
Gwendal Roué 555ed025bc CHANGELOG 2020-12-12 12:30:45 +01:00
Gwendal Roué d0e4d536d9 Merge pull request #880 from groue/dev/cte
Common Table Expressions
2020-12-12 11:56:01 +01:00
Gwendal Roué 8c225105c2 Documentation 2020-12-12 11:21:49 +01:00
Gwendal Roué c36539adb3 CTEs can enter UPDATE and DELETE queries 2020-12-12 11:06:51 +01:00
Gwendal Roué b636c391df Fix typo 2020-12-11 08:33:13 +01:00
Gwendal Roué 659af2cd2a Documentation 2020-12-11 08:28:44 +01:00
Gwendal Roué f70e2b4e37 Mention that recursive CTEs require SQL 2020-12-11 08:24:05 +01:00
Gwendal Roué b16e12cb6e Documentation 2020-12-11 08:18:33 +01:00
Gwendal Roué df5c62d2d9 Documentation
Mention the CTE blog post found by @bellebethcooper
2020-12-11 08:17:12 +01:00
Gwendal Roué b89d11f8ec TODO 2020-12-09 09:23:42 +01:00
Gwendal Roué 992f2a2d83 Revert "CommonTableExpression.contains(_:)"
This reverts commit f94cecb329.

We can't expose a raw table name like that, because it may be used several times, and need an alias.
2020-12-08 18:36:51 +01:00
Gwendal Roué f94cecb329 CommonTableExpression.contains(_:) 2020-12-06 19:22:30 +01:00
Gwendal Roué 89c117425e Mention minimal SQLite version in README 2020-12-06 16:40:40 +01:00
Gwendal Roué 26c7441b49 Documentation 2020-12-06 13:16:27 +01:00
Gwendal Roué a6d80ce208 Update Makefile for Xcode 12.2 2020-12-06 13:11:36 +01:00
Gwendal Roué c287449258 Documentation 2020-12-05 20:50:58 +01:00
Gwendal Roué f9c98b4a1f Fix documentation typo 2020-12-05 20:47:59 +01:00
Gwendal Roué 86cfee4e23 Fix typo 2020-12-05 19:57:54 +01:00
Gwendal Roué a3351513ce Optimize inclusion of CTE association
In order to count the selected columns of a CTE, we do not need to have SQLite compile the whole CTE request when we have information about the selected columns.
2020-12-05 19:50:47 +01:00
Gwendal Roué 95be9b7bb6 Documentation 2020-12-05 19:17:47 +01:00
Gwendal Roué 1c2dd8617b Fix Documentation typo 2020-12-05 19:15:20 +01:00
Gwendal Roué 7f71174159 Fix typo 2020-12-05 18:26:46 +01:00
Gwendal Roué 098ddf27ec Documentation 2020-12-05 18:25:51 +01:00
Gwendal Roué bbce741688 Documentation 2020-12-05 18:22:26 +01:00
Gwendal Roué c56382f04a Documentation 2020-12-05 18:19:01 +01:00
Gwendal Roué 71841f0a07 Documentation 2020-12-05 18:16:20 +01:00
Gwendal Roué e43fae2a63 Fix sample code 2020-12-05 18:13:42 +01:00
Gwendal Roué 022a06b4bc Documentation 2020-12-05 18:10:13 +01:00
Gwendal Roué 7df77aa2d0 Documentation 2020-12-05 18:05:52 +01:00
Gwendal Roué f18bcb67e4 Documentation 2020-12-05 17:56:39 +01:00
Gwendal Roué cc68ef5872 Caveat documentation 2020-12-05 16:13:48 +01:00
Gwendal Roué 5b3eee53c2 SQL interpolation of CTEs 2020-12-05 16:13:24 +01:00
Gwendal Roué 63255cabf8 SQL interpolation of CTEs 2020-12-05 13:40:56 +01:00
Gwendal Roué 9d1bcec132 Cleanup filtering of trivially true joining conditions 2020-12-05 12:49:31 +01:00
Gwendal Roué b60f39e7cc Merge branch 'development' into dev/cte
# Conflicts:
#	GRDB/QueryInterface/Request/Association/Association.swift
#	GRDB/QueryInterface/Request/QueryInterfaceRequest.swift
#	GRDB/QueryInterface/SQL/SQLQuery.swift
#	GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift
#	GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift
2020-12-05 12:31:52 +01:00
Gwendal Roué 5464d64180 Prevent an infinite loop of self-proxying TableAlias I saw once 2020-12-05 12:24:05 +01:00
Gwendal Roué 1e2d07a16f Simplify SQLSource
SQLSource used to be more or less able to deal with subqueries, as in SELECT ... FROM (SELECT ...).

But we had only one use case for it, the "trivial count query": SELECT COUNT(*) FROM (SELECT ...). And many opportunities for fatal errors, because such subqueries were not generally supported.

So we simplify SQLSource, and implement the trivial count query in another way.
2020-12-05 12:21:14 +01:00
Gwendal Roué 66b23d423f Cleanup JoinAssociation 2020-12-05 10:54:31 +01:00
Gwendal Roué 3094c274df Enhance error message 2020-12-05 10:34:32 +01:00
Gwendal Roué 378279ee1a Move the isRecursive flag where it belongs 2020-12-05 10:32:46 +01:00
Gwendal Roué e509d7af65 Merge branch 'development' into dev/cte 2020-12-04 07:10:12 +01:00
Gwendal Roué 9da4bc09c3 Fix typos 2020-12-04 07:09:54 +01:00
Gwendal Roué 462461c1c9 Merge pull request #883 from professordeng/patch-1
Update README.md
2020-12-04 05:34:41 +01:00
peofessordeng 7ded56dfc4 Update README.md 2020-12-04 11:07:37 +08:00
Gwendal Roué 836a0a5e37 Documentation 2020-12-03 19:15:57 +01:00
Gwendal Roué 91dd13e2be Merge cte support into AllColumns 2020-12-03 18:51:26 +01:00
Gwendal Roué a1f0f2c9b7 TODO 2020-12-03 09:24:56 +01:00
Gwendal Roué 6f409f2140 Fix typo 2020-12-03 09:22:15 +01:00
Gwendal Roué 64776682fe Drop USING clause until actually needed 2020-12-03 09:21:19 +01:00
Gwendal Roué a21e6575d8 _AllCTEColumns delegates to AllColumns and _SQLQualifiedAllColumns 2020-12-03 08:37:55 +01:00
Gwendal Roué 4ee6f3293a CTE columns are provided as strings 2020-12-03 08:34:43 +01:00
Gwendal Roué 17b884b3dc Recursive CTEs 2020-12-03 08:28:14 +01:00
Gwendal Roué 0f6d36bfc2 Cleanup 2020-12-03 07:07:39 +01:00
Gwendal Roué 0dc9215df6 Documentation 2020-12-02 22:15:50 +01:00
Gwendal Roué 333ffc1ebe Documentation 2020-12-02 21:55:51 +01:00
Gwendal Roué 181c930e39 Cleanup 2020-12-02 19:29:35 +01:00
Gwendal Roué 65337e74d9 Solve #856 with a CTE :-) 2020-12-02 19:14:53 +01:00
Gwendal Roué 69c116507b Fetch straight from a CTE 2020-12-02 18:40:58 +01:00
Gwendal Roué 2b82de42d8 Merge branch 'development' into dev/cte 2020-12-02 18:30:31 +01:00
Gwendal Roué 10dfa3fba9 Merge pull request #881 from felixscheinost/patch-1
Fix try-catch blocks in documentation
2020-12-02 10:41:06 +01:00
Felix Scheinost 339062f01f Fix try-catch blocks in documentation 2020-12-02 10:08:55 +01:00
Gwendal Roué eb2346dfce Couting requests with CTE uses trivial SQL 2020-12-02 08:26:35 +01:00
Gwendal Roué 1d0adaacf6 including(all:) accepts associations based on the .using condition 2020-12-02 08:20:50 +01:00
Gwendal Roué 5e8f95ca09 Improve CTE columns counting 2020-12-02 08:09:07 +01:00
Gwendal Roué b085a29c8c Cleanup 2020-12-02 08:02:42 +01:00
Gwendal Roué 992e8f3423 Remove header 2020-12-02 06:25:18 +01:00
Gwendal Roué 49e6923156 Prepare recursive CTEs 2020-12-02 06:22:55 +01:00
Gwendal Roué a7a4858364 Refactor CommonTableExpression initializers 2020-12-02 06:12:55 +01:00
Gwendal Roué 3a38cbe87f Create CTE without request 2020-12-02 06:00:04 +01:00
Gwendal Roué 2c42d0129c CTE columns: WITH cte(a, b) AS ... 2020-12-02 05:36:56 +01:00
Gwendal Roué da5ef961d6 Expose CTE creation method at a documented level 2020-12-02 05:14:26 +01:00
Gwendal Roué d35373dcdf Fix typo 2020-12-01 20:48:40 +01:00
Gwendal Roué adc6ba1226 Delete dead code 2020-12-01 20:45:11 +01:00
Gwendal Roué b1d162c14e Filter, order, alias CTE 2020-12-01 20:38:37 +01:00
Gwendal Roué 2b6c3fb868 Remove misleading comment 2020-12-01 20:38:19 +01:00
Gwendal Roué a70b42cbf5 Extract SQLAssociationCondition.using 2020-12-01 20:30:36 +01:00
Gwendal Roué 06000abbfd Type-safe CTE associations, part 2 2020-12-01 20:04:35 +01:00
Gwendal Roué 67bc47c3b5 Type-safe CTE associations 2020-12-01 20:00:04 +01:00
Gwendal Roué 5c34ab19e2 API rationalization 2020-12-01 19:50:16 +01:00
Gwendal Roué 6d14f792e6 Remove dead code 2020-12-01 19:36:50 +01:00
Gwendal Roué 1238843a44 Cleanup 2020-12-01 19:33:43 +01:00
Gwendal Roué 8000332ec4 Gather CTE methods 2020-12-01 19:29:39 +01:00
Gwendal Roué 9896607dff Test for filtered CTE 2020-12-01 19:17:47 +01:00
Gwendal Roué 1be0a6cd5c Add JoinAssociation to GRDBCustom 2020-12-01 19:17:34 +01:00
Gwendal Roué 0191676063 Using clause for CTE associations 2020-12-01 09:17:05 +01:00
Gwendal Roué c16da693df More cte association api experiments 2020-12-01 08:38:39 +01:00
Gwendal Roué f31dd0033c Remove non-composable cte association methods 2020-12-01 08:21:04 +01:00
Gwendal Roué b7b89c5fa9 CTE associations 2020-11-30 21:51:17 +01:00
Gwendal Roué c776ee8d47 Association: remove TableRecord requirement 2020-11-30 21:50:18 +01:00
Gwendal Roué c36fc2813b Include a raw SQL CTE 2020-11-30 19:29:54 +01:00
Gwendal Roué ec2640a459 CommonTableExpression is a table, after all 2020-11-30 19:21:46 +01:00
Gwendal Roué 755782759a Cleanup 2020-11-30 18:14:03 +01:00
Gwendal Roué 9275d4ddf8 Need to deal with CTE subqueries 2020-11-30 18:10:21 +01:00
Gwendal Roué 96951b3d4e Remove dead code 2020-11-30 18:10:06 +01:00
Gwendal Roué 36a8cd1352 CTE merging WIP: we need to postpone TableAlias creation 2020-11-29 19:33:46 +01:00
Gwendal Roué 2bb9f5ce0d First joins with CommonTableExpression 2020-11-29 19:05:12 +01:00
Gwendal Roué e1d3c1d7dc Give CommonTableExpression a key, for joins 2020-11-29 18:23:41 +01:00
Gwendal Roué 00a7eb53e8 First successful SQL generation with CTE 2020-11-29 16:51:52 +01:00
Gwendal Roué e7dcf25063 CTE aliases 2020-11-29 15:49:55 +01:00
Gwendal Roué d2b7b4240a CTE basis 2020-11-29 15:06:45 +01:00
Gwendal Roué b6ef89c116 Prefetch cleanup 2020-11-29 11:58:15 +01:00
Gwendal Roué 2a917823ed Merge branch 'development' 2020-11-29 06:59:23 +01:00
Gwendal Roué 2135f8e768 v5.2.0 2020-11-28 13:46:26 +01:00
Gwendal Roué 2c45ecf56c CHANGELOG 2020-11-28 13:41:50 +01:00
Gwendal Roué 52f831936e Document the including(all:) caveat with compound foreign keys 2020-11-28 13:26:21 +01:00
Gwendal Roué 28f6b64f67 Document the including(all:) caveat with compound foreign keys 2020-11-28 13:24:25 +01:00
Gwendal Roué cc0365d794 Document the including(all:) caveat with compound foreign keys 2020-11-28 13:21:12 +01:00
Gwendal Roué 59ad47d640 Merge pull request #872 from groue/dev/timezone
Parse time zones
2020-11-14 18:33:42 +01:00
Gwendal Roué 27662f99b0 [skip travis] profile date parsing 2020-11-14 13:18:21 +01:00
Gwendal Roué 4c5c2dfb6c [skip travis] CHANGELOG 2020-11-14 13:16:38 +01:00
Gwendal Roué 517a7b2984 Update documentation 2020-11-14 11:16:47 +01:00
Gwendal Roué 10bb596b7c Update documentation 2020-11-14 11:15:09 +01:00
Gwendal Roué 6913f1e39b Update documentation 2020-11-14 10:51:30 +01:00
Gwendal Roué fe8e32586b Parse time zones 2020-11-14 10:35:04 +01:00
Gwendal Roué e0c91ed2ee Merge pull request #868 from groue/dev/varying-region
ValueObservation optimization is opt-in
2020-11-08 11:15:41 +01:00
Gwendal Roué 428433672c Documentation 2020-11-07 13:55:57 +01:00
Gwendal Roué f71a2f7cd8 CHANGELOG 2020-11-07 13:39:49 +01:00
Gwendal Roué 102b037c7d Update documentation 2020-11-07 13:02:47 +01:00
Gwendal Roué 46c3839ea0 ValueObservation tracks a varying database region by defaut 2020-11-07 13:01:51 +01:00
Gwendal Roué 2c51c04708 Merge branch 'development' 2020-11-01 13:27:29 +01:00
Gwendal Roué d0a7a49c19 v5.1.0 2020-11-01 13:27:04 +01:00
Gwendal Roué 0024a4e654 Merge pull request #864 from groue/dev/filter-ergonomics
Prevent filter misuse with a deprecation warning
2020-11-01 13:18:05 +01:00
Gwendal Roué d66a3f4ab3 Fix Swiftlint warning 2020-11-01 10:39:48 +01:00
Gwendal Roué 645aa1d67b CHANGELOG 2020-11-01 10:34:21 +01:00
Gwendal Roué 06db4af649 Enhance warning 2020-11-01 10:33:05 +01:00
Gwendal Roué baf1ef32d1 Document why filter(_:) prefers SQLSpecificExpressible over SQLExpressible 2020-11-01 10:29:07 +01:00
Gwendal Roué d5638f8e53 Update tests and replace filter(value) with filter(databaseValue) 2020-11-01 09:44:13 +01:00
Gwendal Roué c65b5b28b9 Update tests and replace filter(value) with filter { _ in value }
We just want to make sure that no nasty overload alters the meaning of expressions such as `2 + 2`
2020-11-01 09:43:37 +01:00
Gwendal Roué 1301e16f6e Update tests and replace filter(false) with none() 2020-11-01 09:42:00 +01:00
Gwendal Roué caa382f41b Deprecate filter(value)
Some people use Player.filter(id) instead of Player.filter(key: id). This is what this commit prevents.
2020-11-01 09:41:16 +01:00
Gwendal Roué 24fd69a9be [skip travis] CHANGELOG 2020-10-31 19:56:25 +01:00
Gwendal Roué 2389ec691b Merge pull request #855 from mallman/generated_columns
SQLite 3.33.0 + Support for generated columns
2020-10-31 18:56:34 +01:00
Gwendal Roué b8dd2ce2f4 Generate columns from query interface expressions
This allows to avoid SQL injection
2020-10-31 14:16:04 +01:00
Gwendal Roué 5114cc4d6d Fix documentation 2020-10-31 13:56:22 +01:00
Gwendal Roué 57036c4470 Use SQLite ergonomics, and create virtual generated columns by default 2020-10-31 13:55:07 +01:00
Gwendal Roué 81166432a8 Documentation for generatedAs(sql:) 2020-10-31 13:45:58 +01:00
Gwendal Roué 5dc8502c8b Test that update(_:) and insert(_:) throw when persisting generated columns 2020-10-31 13:23:42 +01:00
Gwendal Roué 67e10926db Restore logic 2020-10-31 13:09:49 +01:00
Gwendal Roué e971e210a3 Update documentation about PRAGMA table_info and table_xinfo 2020-10-31 13:09:05 +01:00
Gwendal Roué f7e6169c23 Test that TableRecord.numberOfSelectedColumns(_:) includes generated columns 2020-10-31 13:07:58 +01:00
Gwendal Roué 6fc4e31dfb Test that Database.columns(in:) returns generated columns 2020-10-31 12:55:56 +01:00
Gwendal Roué dfc22bdf00 Skip tests for generated columns unless custom SQLite build 2020-10-31 12:14:52 +01:00
Gwendal Roué 54b5f47ffa Upgrade custom SQLite builds to v3.33.0 2020-10-31 12:09:49 +01:00
Gwendal Roué 62a4251f90 Merge pull request #862 from groue/dev/fix-861
Improve documentation of observations of varying regions
2020-10-31 11:34:07 +01:00
Gwendal Roué a41c12252a Documentation 2020-10-30 09:12:47 +01:00
Gwendal Roué e7cf816062 Documentation 2020-10-30 06:25:20 +01:00
Gwendal Roué ff28cadd57 More tests for optimized regions 2020-10-30 06:20:50 +01:00
Gwendal Roué 9039b18b84 Documentation 2020-10-30 06:05:52 +01:00
Gwendal Roué 480381deb5 Documentation 2020-10-30 05:59:20 +01:00
Gwendal Roué 84dbace4af Documentation 2020-10-30 05:56:58 +01:00
Gwendal Roué 44f80f4c7c Wording 2020-10-30 05:49:42 +01:00
Gwendal Roué 1cb9e52123 Legibility 2020-10-29 19:12:29 +01:00
Gwendal Roué 4d7ddb9c26 Wording 2020-10-29 19:07:31 +01:00
Gwendal Roué 1b29d7eca3 CHANGELOG 2020-10-29 19:02:00 +01:00
Gwendal Roué 5c779b11db Improve documentation of observations of a varying region 2020-10-29 18:47:34 +01:00
Gwendal Roué dc344c07de Wording 2020-10-29 18:16:37 +01:00
Gwendal Roué b7b3c3ab32 Wording 2020-10-29 18:15:23 +01:00
Gwendal Roué 6fa20284ec Wording 2020-10-29 18:14:14 +01:00
Gwendal Roué 978b570826 FAQ: Why is ValueObservation not publishing value changes? 2020-10-29 18:13:06 +01:00
Gwendal Roué 688e393ed1 Don't track prefetched associations when the parent is provably empty 2020-10-29 17:05:26 +01:00
Gwendal Roué 8ede868068 More tests for empty regions of empty requests 2020-10-29 16:05:35 +01:00
Gwendal Roué 667d42eeb4 [skip travis] Fix release date 2020-10-28 07:43:01 +01:00
Michael Allman 1f87d5a375 Add rudimentary tests for the generated column table definition API 2020-10-25 12:19:01 -07:00
Michael Allman 4f0a6cf9e1 Extract common filter predicate in AssociationPrefetchingSQLTests into a
reusable method
2020-10-25 11:55:49 -07:00
Michael Allman 3318858b80 Wrap the generatedAs column definition API with the GRDBCUSTOMSQLITE
Swift compiler flag
2020-10-25 11:44:09 -07:00
Michael Allman 9c6f19f55f Condition table column info query on SQLite version 2020-10-25 11:42:43 -07:00
Gwendal Roué 48ee93c244 CHANGELOG 2020-10-25 10:38:22 +01:00
Gwendal Roué ee4197bcc0 Merge branch 'development' 2020-10-25 10:33:57 +01:00
Gwendal Roué 079c476148 v5.0.3 2020-10-25 10:33:32 +01:00
Gwendal Roué aa909b7635 Merge branch 'master' into development 2020-10-25 10:33:21 +01:00
Gwendal Roué 9167ebda98 Merge pull request #859 from groue/dev/deinit-change
Database.close() is idempotent
2020-10-25 10:15:49 +01:00
Gwendal Roué 38682c69da CHANGELOG 2020-10-25 10:15:27 +01:00
Gwendal Roué 2a7f41c494 Database.close() is idempotent
This change addresses https://bugs.swift.org/browse/SR-13746
2020-10-25 10:12:42 +01:00
Michael Allman 071bbc7905 Initial commit for generated column support 2020-10-19 21:25:36 -07:00
Gwendal Roué ca18f509e7 Merge pull request #850 from DiligentRobot/development
Add buildActiveScheme to playground settings so they'll build under Xcode 12
2020-10-15 17:57:34 +02:00
Matt Tancock 5e2bb1d57a Add buildActiveScheme to playground settings so they'll build under Xcode 12 2020-10-15 15:10:28 +01:00
Gwendal Roué dd2950e4ca [skip travis] Merge pull request #849 from MarshalGeazipp/MarshalGeazipp-fix-grammar
Fix grammar mistake AssociationsBasics.md
2020-10-08 17:42:40 +02:00
Sebastian Nicklas 34f3097616 Update AssociationsBasics.md 2020-10-08 17:19:17 +02:00
Gwendal Roué 948e91126a Merge branch 'development' 2020-10-06 19:21:43 +02:00
Gwendal Roué 85b781bf0e v5.0.2 2020-10-06 14:10:06 +02:00
Gwendal Roué bd853a8bc0 CHANGELOG 2020-10-06 14:08:21 +02:00
Gwendal Roué bfc76b96f3 Fix #844 2020-10-06 14:03:41 +02:00
Gwendal Roué 99ea59ee06 Demo app builds in Debug configuration 2020-10-06 14:03:41 +02:00
Gwendal Roué f8a0e8e4b5 Merge pull request #847 from groue/dev/remove-snapshots
Remove dependency on SQLITE_ENABLE_SNAPSHOT
2020-10-06 13:32:26 +02:00
Gwendal Roué 14e32a2bd1 [skip travis] CHANGELOG 2020-10-06 13:31:52 +02:00
Gwendal Roué f84e25f929 Remove dependency on SQLITE_ENABLE_SNAPSHOT
Address #845 and #846
2020-10-06 08:30:41 +02:00
Gwendal Roué 6884bf10b0 Merge branch 'development' 2020-09-27 15:52:03 +02:00
Gwendal Roué 8803eafe31 v5.0.1 2020-09-27 15:20:42 +02:00
Gwendal Roué 9909ca4c96 [skip travis] CHANGELOG 2020-09-27 15:17:12 +02:00
Gwendal Roué 5d36d5735d [skip travis] Update GRDBCombineDemo for iOS 14
Address both #842 and #843
2020-09-27 14:46:43 +02:00
Gwendal Roué ef368a2bc2 Merge pull request #841 from groue/dev/840
Fix GRDB 5 regression with indexes on expressions
2020-09-27 12:06:02 +02:00
Gwendal Roué 8433b09650 [skip travis] CHANGELOG 2020-09-27 12:04:40 +02:00
Gwendal Roué d2eb92d1a2 Travis: test Xcode 12 2020-09-26 15:27:49 +02:00
Gwendal Roué ba98aab046 Fix failing test for #840 2020-09-26 14:46:39 +02:00
Gwendal Roué 00d15339b6 Failing test for #840 2020-09-26 14:45:49 +02:00
Gwendal Roué 1ea4a44bb8 Merge branch 'development' 2020-09-20 16:47:45 +02:00
Gwendal Roué 5119c065bd v5.0.0 2020-09-20 15:54:56 +02:00
Gwendal Roué 8be6aa7358 Fix GRDBCombineDemo on the device 2020-09-20 15:35:25 +02:00
Gwendal Roué 438f99deff GRDBCombineDemo Xcode 12 changes 2020-09-20 15:27:52 +02:00
Gwendal Roué c556c056d8 GRDBCombineDemo: animate list changes 2020-09-20 15:27:36 +02:00
Gwendal Roué 613baf30f9 GRDBCombineDemo: fix compiler error 2020-09-20 15:27:10 +02:00
Gwendal Roué 0ac7e2d299 Xcode 12 2020-09-20 15:05:20 +02:00
Gwendal Roué 929465eb52 UIKit demo: use UITableViewDiffableDataSource 2020-09-20 15:05:07 +02:00
Gwendal Roué 13de0a5cce Demo apps: move from unfamiliar World-based dependency injection to plain shared global 2020-09-20 14:37:01 +02:00
Gwendal Roué c12f42b385 Fix warnings 2020-09-20 14:11:29 +02:00
Gwendal Roué 2ccd01299c In performance report, the hardware model and Xcode version are dynamic 2020-09-20 14:05:08 +02:00
Gwendal Roué fb2efb8df9 Upgrade Realm 2020-09-20 14:04:24 +02:00
Gwendal Roué 795daf284f Remove performance database resources 2020-09-20 13:31:11 +02:00
Gwendal Roué 354b815835 Remove obsolete todos 2020-09-20 11:38:37 +02:00
Gwendal Roué 7d8e20685d CHANGELOG 2020-09-20 11:19:11 +02:00
Gwendal Roué 5050c36c4e Fix wording of root key decoding error 2020-09-19 15:52:50 +02:00
Gwendal Roué 6348c6f151 Merge branch 'dev/decodingErrorAmbiguity' into development 2020-09-19 15:50:35 +02:00
Gwendal Roué 8cb468cf05 Fix failing test for #836 2020-09-19 15:50:21 +02:00
Gwendal Roué 55c9e48a21 Failing test for #836 2020-09-19 15:50:07 +02:00
Gwendal Roué db3ae357ea Merge branch 'dev/indexIfNotExists' into development 2020-09-19 13:12:30 +02:00
Gwendal Roué f62b952d70 Fix failing test for #838 2020-09-19 13:11:44 +02:00
Gwendal Roué bf1c025612 Failing test for #838 2020-09-19 13:11:30 +02:00
Gwendal Roué ba253dcbf2 [skip travis] fix indentation 2020-09-11 14:36:41 +02:00
Gwendal Roué 1829706faa [skip travis] don’t talk about "misuse" when it’s all about an SQLite misfeature 2020-09-11 14:34:55 +02:00
Gwendal Roué f9f16df065 [skip travis] don’t talk about "misuse" when it’s all about an SQLite misfeature 2020-09-11 14:33:40 +02:00
Gwendal Roué 66173b345f [skip travis] wording 2020-09-11 14:30:25 +02:00
Gwendal Roué ac54c808c5 [skip travis] fix documentation layout 2020-09-11 13:37:52 +02:00
Gwendal Roué 7761b137ba Fix wording 2020-09-11 13:37:04 +02:00
Gwendal Roué 3d144b9e5d [skip travis] FAQ about SQLite error 1 "no such column" 2020-09-11 13:27:30 +02:00
Gwendal Roué b2f5d425b6 Merge branch 'development' 2020-09-07 13:42:58 +02:00
Gwendal Roué 64028e03dc v5.0.0-beta.11 2020-09-07 13:36:44 +02:00
Gwendal Roué e52047d82e Fix #828 2020-09-07 13:29:13 +02:00
Gwendal Roué 5adbd9b3e3 Merge pull request #831 from groue/dev/more-preparation
Improve Configuration.prepareDatabase
2020-09-07 13:26:50 +02:00
Gwendal Roué fd21f97007 Update migration guide 2020-09-06 18:40:15 +02:00
Gwendal Roué d74c5264d3 Update documentation for functions, collations, and tokenizers 2020-09-06 18:28:22 +02:00
Gwendal Roué 654611c365 Fix OTHER_SWIFT_FLAGS 2020-09-06 14:38:30 +02:00
Gwendal Roué 18e09ec061 Configuration.prepareDatabase updates 2020-09-06 14:06:25 +02:00
Gwendal Roué 8e2fb1fb22 Update tests 2020-09-06 13:57:16 +02:00
Gwendal Roué 7a2c1413fe Fix DatabaseSnapshot 2020-09-06 13:40:03 +02:00
Gwendal Roué 3c38aa1996 Functions, Collations, and tokenizers are no longer available on DatabaseQueue, Pool, and Snapshot 2020-09-06 13:18:58 +02:00
Gwendal Roué 886f75bbea Configuration.prepareDatabase in now a method 2020-09-06 13:15:51 +02:00
Gwendal Roué 5820b30cc6 DatabaseError.description: output SQLite message before statement #820 2020-08-25 19:48:00 +02:00
Gwendal Roué ce4bfb9df6 [skip travis] Explain that date and uuid strategies do not apply to requests (#821) 2020-08-23 11:07:02 +02:00
Gwendal Roué be787d3e8a [skip travis] Tell that demo apps are not templates. Addresses #823 2020-08-23 10:36:44 +02:00
Gwendal Roué ededd8668a Merge branch 'development' 2020-07-30 08:29:47 +02:00
Gwendal Roué 7b788e3988 v5.0.0-beta.10 2020-07-30 08:29:27 +02:00
Gwendal Roué 0eb854cebd Merge pull request #817 from groue/dev/boolean-checks
Allow query planner to optimize some boolean tests
2020-07-30 08:24:36 +02:00
Gwendal Roué 9529939262 Documentation 2020-07-27 06:40:18 +02:00
Gwendal Roué 6ee7db48c8 Take care of indexes on expressions as well
sqlite> create table t(a,b);
sqlite> create index i on t(a like '%a', a, b);
sqlite> explain query plan select * from t where a like '%a';
QUERY PLAN
`--SCAN TABLE t
sqlite> explain query plan select * from t where a not like '%a';
QUERY PLAN
`--SCAN TABLE t
sqlite> explain query plan select * from t where (a like '%a') = 1;
QUERY PLAN
`--SEARCH TABLE t USING COVERING INDEX i (<expr>=?)
sqlite> explain query plan select * from t where (a like '%a') = 0;
QUERY PLAN
`--SEARCH TABLE t USING COVERING INDEX i (<expr>=?)
2020-07-26 16:04:02 +02:00
Gwendal Roué 8cc82ae2b7 Update migration guide 2020-07-26 15:16:19 +02:00
Gwendal Roué 474c2c3a76 Thank you notice 2020-07-26 15:09:43 +02:00
Gwendal Roué 843624044c CHANGELOG 2020-07-26 15:08:21 +02:00
Gwendal Roué 454b9d5546 More tests for boolean tests 2020-07-26 14:19:46 +02:00
Gwendal Roué c532b8709c Refactor boolean tests (fix #816) 2020-07-26 14:19:31 +02:00
Gwendal Roué bf1d6038e1 Failing tests for #816 2020-07-26 13:33:35 +02:00
Gwendal Roué 86b9616dd7 DatabasePool readers don't invalidate their database schema cache until schema is actually changed. 2020-07-25 18:20:43 +02:00
Gwendal Roué bc993f63f5 Merge branch 'development' 2020-07-24 06:07:54 +02:00
Gwendal Roué 531d732437 Travis: bump to Xcode 11.6 2020-07-23 20:38:19 +02:00
Gwendal Roué 24f9b2c01b Makefile: add support for Xcode 11.6 2020-07-23 20:27:05 +02:00
Gwendal Roué c4991176f4 v5.0.0-beta.9 2020-07-23 19:04:58 +02:00
Gwendal Roué 0ea70d6bfc CHANGELOG 2020-07-23 19:00:58 +02:00
Gwendal Roué 845ae7e0e4 Merge pull request #814 from groue/dev/views
Fix regression with views
2020-07-23 18:59:16 +02:00
Gwendal Roué dc8d74b609 Merge pull request #813 from groue/dev/SQLite3.31.1
Expose SQLite 3.31.1 APIs to iOS, macOS, tvOS, watchOS
2020-07-23 18:58:56 +02:00
Gwendal Roué 2f54eda08a Fix #812 2020-07-23 08:46:05 +02:00
Gwendal Roué a526351b4c Failing test for #812 2020-07-23 08:31:53 +02:00
Gwendal Roué d08d3b311f Fix for GRDB+SQLCipher 2020-07-23 07:55:34 +02:00
Gwendal Roué 25baecdc39 CHANGELOG 2020-07-22 20:36:32 +02:00
Gwendal Roué e2816905bb OSX 11 is OSX 10.16 2020-07-22 20:22:03 +02:00
Gwendal Roué ee2d8eae50 Expose ascNullLast and descNullFirst
This is because iOS 14 runs SQLite 3.31.1
2020-07-22 20:17:52 +02:00
Gwendal Roué 1823e11090 Expose remove_diacritics=2 option of unicode61 FTS5 tokenizer
This is because iOS 14 runs SQLite 3.31.1
2020-07-22 20:07:27 +02:00
Gwendal Roué 294ed772c1 Expose remove_diacritics=2 option of unicode61 FTS tokenizer
This is because iOS 14 runs SQLite 3.31.1
2020-07-22 20:07:27 +02:00
Gwendal Roué 62f33e1d55 Dictionary(grouping:by:) with Cursor 2020-07-22 08:39:45 +02:00
Gwendal Roué e3f1992536 [skip travis] Mention update with primary key 2020-07-19 13:42:12 +02:00
Gwendal Roué baf3a8ec26 [skip travis] Simplify introduction to record protocols 2020-07-19 13:26:56 +02:00
Gwendal Roué a9ca4450f8 [skip travis] Mention unadapted 2020-07-19 13:09:27 +02:00
Gwendal Roué 54ceba6dfa [skip travis] Update observation usage 2020-07-19 13:00:29 +02:00
Gwendal Roué fc64d868ef [skip travis] Update observation usage 2020-07-19 12:53:48 +02:00
Gwendal Roué 45fdb50dc2 [skip travis] Mention RenameColumnAdapter in the migration guide 2020-07-19 12:27:49 +02:00
299 changed files with 11417 additions and 6086 deletions

No files matched your search

+1
View File
@@ -2,6 +2,7 @@ included:
- GRDB
disabled_rules:
- comment_spacing
- cyclomatic_complexity
- duplicate_enum_cases
- file_length
+115 -96
View File
@@ -28,18 +28,128 @@ jobs:
include:
###########################################
## Test GRDB Xcode 11.4
## Test GRDB Xcode 12.2
- name: "Test GRDB Xcode 11.4 - GRDBOSX"
- name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
osx_image: xcode12.2
script: make test_framework_GRDBOSX_maxSwift
- name: "Test GRDB Xcode 11.4 - GRDBWatchOS"
- name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.2"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
osx_image: xcode12.2
script: make test_framework_GRDBOSX_minSwift
- name: "Test GRDB Xcode 12.2 - GRDBWatchOS"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBWatchOS
- name: "Test GRDB Xcode 12.2 - GRDBiOS iOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 12.2 - GRDBiOS iOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBiOS_minTarget
- name: "Test GRDB Xcode 12.2 - GRDBtvOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 12 - GRDBtvOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBtvOS_minTarget
- name: "Test GRDB Xcode 12.2 - SPM"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_SPM
###########################################
## Test GRDBCustom Xcode 12.2
- name: "Test GRDBCustom Xcode 12.2 - GRDBOSX"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBCustomSQLiteOSX
- name: "Test GRDBCustom Xcode 12.2 - GRDBiOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
- name: "Test GRDBCustom Xcode 12.2 - GRDBiOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test SQLCipher Xcode 12.2
- name: "Test SQLCipher Xcode 12.2 - SQLCipher 3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_SQLCipher3
- name: "Test SQLCipher Xcode 12.2 - SQLCipher 4"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_SQLCipher4
###########################################
## Test Installation Xcode 12.2
# Manual Install
- name: "Test Installation Xcode 12.2 - Manual Install"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_manual
# Travis is much too slow, and always fail this job
# # CocoaPods Lint
# - name: "Test Installation Xcode 12.2 - CocoaPods Lint"
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode12.2
# script: make test_CocoaPodsLint_GRDB
# CocoaPods Install GRDB
- name: "Test Installation Xcode 12.2 - CocoaPods Framework"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- name: "Test Installation Xcode 12.2 - CocoaPods Static"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_GRDB_CocoaPods_static
# SPM Install
- name: "Test Installation Xcode 12.2 - SPM Package"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_SPM_Package
# SPM Install
- name: "Test Installation Xcode 12.2 - SPM Package in Xcode Project"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_SPM_Project
# Custom SQLite Install
- name: "Test Installation Xcode 12.2 - Custom SQLite"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_customSQLite
###########################################
## Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - GRDBiOS iOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
@@ -49,94 +159,3 @@ jobs:
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_framework_GRDBiOS_minTarget
- name: "Test GRDB Xcode 11.4 - GRDBtvOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 11.4 - GRDBtvOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_framework_GRDBtvOS_minTarget
- name: "Test GRDB Xcode 11.4 - SPM"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_SPM
###########################################
## Test GRDBCustom Xcode 11.4
- name: "Test GRDBCustom Xcode 11.4 - GRDBOSX"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_framework_GRDBCustomSQLiteOSX
- name: "Test GRDBCustom Xcode 11.4 - GRDBiOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
- name: "Test GRDBCustom Xcode 11.4 - GRDBiOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test SQLCipher Xcode 11.4
- name: "Test SQLCipher Xcode 11.4 - SQLCipher 3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_framework_SQLCipher3
- name: "Test SQLCipher Xcode 11.4 - SQLCipher 4"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_framework_SQLCipher4
###########################################
## Test Installation Xcode 11.4
# Manual Install
- name: "Test Installation Xcode 11.4 - Manual Install"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_install_manual
# CocoaPods Lint
- name: "Test Installation Xcode 11.4 - CocoaPods Lint"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_CocoaPodsLint_GRDB
# CocoaPods Install GRDB
- name: "Test Installation Xcode 11.4 - CocoaPods Framework"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- name: "Test Installation Xcode 11.4 - CocoaPods Static"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_install_GRDB_CocoaPods_static
# SPM Install
- name: "Test Installation Xcode 11.4 - SPM Package"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_install_SPM_Package
# SPM Install
- name: "Test Installation Xcode 11.4 - SPM Package in Xcode Project"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_install_SPM_Project
# Custom SQLite Install
- name: "Test Installation Xcode 11.4 - Custom SQLite"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_install_customSQLite
+6
View File
@@ -4,6 +4,12 @@ Here is a list of people who were happy to meet GRDB :-)
---
https://twitter.com/peres/status/1352219836508729346
> Just the occasional reminder that GRDB and its documentation is the gold standard. That's it.
---
https://twitter.com/steipete/status/1275305583718129664
> This is the future of Core Data
+93 -9
View File
@@ -5,14 +5,13 @@ All notable changes to this project will be documented in this file.
GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library.
<!--
[Next Release](#next-release)
-->
#### 5.x Releases
- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) | [5.0.0-beta.5](#500-beta5) | [5.0.0-beta.6](#500-beta6) | [5.0.0-beta.7](#500-beta7) | [5.0.0-beta.7](#500-beta8)
- `5.3.x` Releases - [5.3.0](#530)
- `5.2.x` Releases - [5.2.0](#520)
- `5.1.x` Releases - [5.1.0](#510)
- `5.0.x` Releases - [5.0.0](#500) | [5.0.1](#501) | [5.0.2](#502) | [5.0.3](#503)
- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) | [5.0.0-beta.5](#500-beta5) | [5.0.0-beta.6](#500-beta6) | [5.0.0-beta.7](#500-beta7) | [5.0.0-beta.8](#500-beta8) | [5.0.0-beta.9](#500-beta9) | [5.0.0-beta.10](#500-beta10) | [5.0.0-beta.11](#500-beta11)
#### 4.x Releases
@@ -70,9 +69,94 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- [0.110.0](#01100), ...
<!--
## Next Release
-->
## 5.3.0
Released January 9, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.2.0...v5.3.0)
- **New**: [#880](https://github.com/groue/GRDB.swift/pull/880): Common Table Expressions
- **New**: [#892](https://github.com/groue/GRDB.swift/pull/892) by [@eburns-vmware](https://github.com/eburns-vmware): Provide SQLCipher passphrase as Data
- **Fixed**: [#881](https://github.com/groue/GRDB.swift/pull/881) by [@felixscheinost](https://github.com/felixscheinost) and [#883](https://github.com/groue/GRDB.swift/pull/883) by [@professordeng](https://github.com/professordeng): Documentation improvements
- **Fixed**: [#885](https://github.com/groue/GRDB.swift/pull/885): Robustness of eager loading of to-many associations based on compound foreign keys
- **Fixed**: [#901](https://github.com/groue/GRDB.swift/pull/901) by [@wuyuehyang](https://github.com/wuyuehyang): Fix creation of FTS5 tokenizer with arguments
- **Fixed**: [#903](https://github.com/groue/GRDB.swift/pull/903) by [@chrisballinger](https://github.com/chrisballinger): Fix SPM installation instructions
- **Documentation update**: A new guide: [Common Table Expressions](https://github.com/groue/GRDB.swift/blob/master/Documentation/CommonTableExpressions.md)
- **Documentation update**: The [Foreign Keys](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#foreign-keys) chapter of the Associations Guide clarifies the behavior of SQLite and GRDB regarding the presence of NULL if compound foreign keys.
## 5.2.0
Released November 29, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.1.0...v5.2.0)
- **New**: [#868](https://github.com/groue/GRDB.swift/pull/868): ValueObservation optimization is opt-in.
- **New**: [#872](https://github.com/groue/GRDB.swift/pull/872): Parse time zones
- **Documentation update**: The [ValueObservation Performance](https://github.com/groue/GRDB.swift/blob/master/README.md#valueobservation-performance) chapter was extended with a tip for observations that track a constant database region.
- **Documentation update**: The [Date and DateComponents](https://github.com/groue/GRDB.swift/blob/master/README.md#date-and-datecomponents) chapter describes the support for time zones.
- **Documentation update**: A caveat ([#871](https://github.com/groue/GRDB.swift/issues/871)) with the `including(all:)` method, which may fail with a database error of code [`SQLITE_ERROR`](https://www.sqlite.org/rescode.html#error) (1) "Expression tree is too large" when you use a compound foreign key and there are a lot of parent records, is detailed in the [Joining And Prefetching Associated Records](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#joining-and-prefetching-associated-records) chapter.
## 5.1.0
Released November 1, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.3...v5.1.0)
- **New**: Clarifications on [ValueObservation that track a varying database region](https://github.com/groue/GRDB.swift/blob/master/README.md#observing-a-varying-database-region).
- **New**: FAQ [Why is ValueObservation not publishing value changes?](https://github.com/groue/GRDB.swift/blob/master/README.md#why-is-valueobservation-not-publishing-value-changes)
- **New**: [#855](https://github.com/groue/GRDB.swift/pull/855) by [@mallman](https://github.com/mallman): Support for generated columns with custom SQLite build, and upgrade custom SQLite builds to version 3.33.0
- **New**: [#864](https://github.com/groue/GRDB.swift/pull/864): Prevent filter misuse with a deprecation warning
## 5.0.3
Released October 25, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.2...v5.0.3)
- **Fixed**: [#859](https://github.com/groue/GRDB.swift/pull/859): Database.close() is idempotent
- **Fixed**: [#850](https://github.com/groue/GRDB.swift/pull/850) by [@mtancock](https://github.com/mtancock): Add buildActiveScheme to playground settings so they'll build under Xcode 12
- **Fixed**: [#849](https://github.com/groue/GRDB.swift/pull/849) by [@MarshalGeazipp](https://github.com/MarshalGeazipp): Fix grammar mistake AssociationsBasics.md
## 5.0.2
Released October 6, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.1...v5.0.2)
- **Fixed**: [#844](https://github.com/groue/GRDB.swift/issues/844): Fix a crash in the demo app
- **Fixed**: [#847](https://github.com/groue/GRDB.swift/issues/847): Remove dependency on SQLITE_ENABLE_SNAPSHOT
## 5.0.1
Released September 27, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0...v5.0.1)
- **Fixed**: [#841](https://github.com/groue/GRDB.swift/issues/841): Fix GRDB 5 regression with indexes on expressions
- The [GRDBCombineDemo](Documentation/DemoApps/GRDBCombineDemo/README.md) Combine + SwiftUI demo application was updated for the SwiftUI App lifecycle introduced in iOS 14.
## 5.0.0
Released September 20, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.11...v5.0.0)
- **Fixed**: [#838](https://github.com/groue/GRDB.swift/issues/838): Have indexed colums inherit the `ifNotExists` flag from table creation.
## 5.0.0-beta.11
Released September 7, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.10...v5.0.0-beta.11)
- **Breaking Change**: [#831](https://github.com/groue/GRDB.swift/pull/831): Improve Configuration.prepareDatabase
## 5.0.0-beta.10
Released July 30, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.9...v5.0.0-beta.10)
- **New**: DatabasePool readers don't invalidate their database schema cache until schema is actually changed.
- **Breaking Change**: [#817](https://github.com/groue/GRDB.swift/pull/817): Allow query planner to optimize some boolean tests
## 5.0.0-beta.9
Released July 23, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.8...v5.0.0-beta.9)
- **New**: [#813](https://github.com/groue/GRDB.swift/pull/813): Expose SQLite 3.31.1 APIs to iOS, macOS, tvOS, watchOS
- **Fixed**: [#814](https://github.com/groue/GRDB.swift/pull/814): Fix regression with views
## 5.0.0-beta.8
+14 -6
View File
@@ -11,6 +11,7 @@ GRDB Associations
- [HasOneThrough]
- [Choosing Between BelongsTo and HasOne]
- [Self Joins]
- [Associations to Common Table Expressions]
- [Associations and the Database Schema]
- [Convention for Database Table Names]
- [Convention for the BelongsTo Association]
@@ -116,7 +117,7 @@ Loading all books from an existing author is now easier:
let books = try author.books.fetchAll(db)
```
As for loading all pairs of books and authors, it is not only easier, but also *far much efficient*:
As for loading all pairs of books and authors, it is not only easier, but also *much more efficient*:
```swift
struct BookInfo: FetchableRecord, Decodable {
@@ -191,18 +192,21 @@ Generally speaking, associations use the [TableRecord], [FetchableRecord], and [
The Types of Associations
=========================
GRDB handles five types of associations:
GRDB handles several types of associations:
- **BelongsTo**
- **HasMany**
- **HasOne**
- **HasManyThrough**
- **HasOneThrough**
- **Associations to common table expressions**
An association declares a link from a record type to another, as in "one book **belongs to** its author". It instructs GRDB to use the foreign keys declared in the database as support for Swift methods.
An association generally declares a link from a record type to another, as in "one book **belongs to** its author". It instructs GRDB to use the foreign keys declared in the database as support for Swift methods.
Each one of these associations is appropriate for a particular database situation.
Associations to [common table expressions] are specific enough and are documented in [Associations to Common Table Expressions].
- [BelongsTo]
- [HasMany]
- [HasOne]
@@ -693,7 +697,7 @@ See [Foreign Keys] for more information.
**Associations can automatically infer the foreign keys that define how two database tables are linked together.**
In the example below, the `book.authorId` column is automatically used to link a book to its author:
In the example below, the `book.authorId` column is automatically used to link a book to its author, because the database schema defines a foreign key between the book and author database tables (see [Convention for the BelongsTo Association]).
![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/master/Documentation/Images/Associations2/BelongsToSchema.svg)
@@ -707,7 +711,9 @@ struct Author: TableRecord {
}
```
But this requires the database schema to define a foreign key between the book and author database tables (see [Convention for the BelongsTo Association]).
> :point_up: **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns.
>
> :warning: **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either.
Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another.
@@ -2373,7 +2379,7 @@ See [Good Practices for Designing Record Types] for more information.
.including(all: Country.passports
.including(required: Passport.citizen))
```
Come [discuss](http://twitter.com/groue) for more information, or if you wish to help turning those missing features into reality.
---
@@ -2476,3 +2482,5 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[database observation tools]: ../README.md#database-changes-observation
[ValueObservation]: ../README.md#valueobservation
[FAQ]: ../README.md#faq-associations
[common table expressions]: CommonTableExpressions.md
[Associations to Common Table Expressions]: CommonTableExpressions.md#associations-to-common-table-expressions
+423
View File
@@ -0,0 +1,423 @@
Common Table Expressions
========================
[**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features)
---
**Common table expressions** (CTEs) can generally be seen as *SQL views that you define on the fly*.
A certain level of familiarity with SQL databases is helpful before you dive into this guide. The starting point is obviously the [SQLite documentation](https://sqlite.org/lang_with.html). Many CTE tutorials exist online as well, including [this good one](https://blog.expensify.com/2015/09/25/the-simplest-sqlite-common-table-expression-tutorial/).
In this guide, you will learn how to:
- [Define Common Table Expressions]
- [Embed Common Table Expressions in Requests]
- [Fetch Values From Common Table Expressions]
- Join CTEs with [Associations to Common Table Expressions]
> :point_up: **Note**: most code examples will be trivial, and not very "useful". This is because the goal of this guide is to stay focused on the GRDB support for CTEs. Rich setup would just be distracting. So bring your own good ideas with you!
## Define Common Table Expressions
You will create a `CommonTableExpression` definition first. Choose a **name**, and a **request** that provides the content of the common table expression.
The CTE name is like a regular table name: pick one that does not conflict with the names of existing tables.
The CTE request can be provided as a [query interface request]:
```swift
// WITH playerName AS (SELECT name FROM player) ...
let playerNameCTE = CommonTableExpression<Void>(
named: "playerName",
request: Player.select(Column("name")))
```
You can feed a CTE with raw SQL as well (second and third examples use [SQL Interpolation]):
```swift
let name = "O'Brien"
// WITH playerName AS (SELECT 'O''Brien') ...
let playerNameCTE = CommonTableExpression<Void>(
named: "playerName",
sql: "SELECT ?", arguments: [name])
// WITH playerName AS (SELECT 'O''Brien') ...
let playerNameCTE = CommonTableExpression<Void>(
named: "playerName",
literal: "SELECT \(name)")
// WITH playerName AS (SELECT 'O''Brien') ...
let request: SQLRequest<String> = "SELECT \(name)"
let playerNameCTE = CommonTableExpression<Void>(
named: "playerName",
request: requests)
```
All CTEs can be provided with explicit column names:
```swift
// WITH pair(a, b) AS (SELECT 1, 2) ...
let pairCTE = CommonTableExpression<Void>(
named: "pair",
columns: ["a", "b"],
sql: "SELECT 1, 2")
```
Recursive CTEs need the `recursive` flag. The example below selects all integers between 1 and 1000:
```swift
// WITH RECURSIVE counter(x) AS
// (VALUES(1) UNION ALL SELECT x+1 FROM counter WHERE x<1000)
let counterCTE = CommonTableExpression<Int>(
recursive: true,
named: "counter",
columns: ["x"],
sql: """
VALUES(1)
UNION ALL
SELECT x+1 FROM counter WHERE x<1000
""")
```
> :point_up: **Note**: many recursive CTEs use the `UNION ALL` SQL operator. The query interface does not provide any Swift support for it, so you'll generally have to write SQL in your definitions of recursive CTEs.
As you can see in all above examples, `CommonTableExpression` is a generic type: `CommonTableExpression<Void>`, `CommonTableExpression<Int>`. The generic argument (`Void`, `Int`) turns useful when you [join common table expressions](#associations-to-common-table-expressions), or when you [fetch values directly from a common table expression](#fetch-values-from-common-table-expressions). Otherwise, you can just use `Void`.
## Embed Common Table Expressions in Requests
A typical SQLite query that uses a common table expression first *defines* the CTE and then *uses* the CTE by mentioning its table name. We'll see below Swift apis that match those two steps.
We will use the (simple) query below as a target. It is the query we'll want to generate in this chapter. It defines a CTE, and uses it in a subquery:
```sql
WITH playerName AS (SELECT 'O''Brien')
SELECT * FROM player
WHERE name = (SELECT * FROM playerName)
```
We first build a `CommonTableExpression`:
```swift
let name = "O'Brien"
let playerNameCTE = CommonTableExpression<Void>(
named: "playerName",
literal: "SELECT \(name)")
```
We can then embed the definition of the CTE in a [query interface request] by calling the `with(_:)` method:
```swift
// WITH playerName AS (SELECT 'O''Brien')
// SELECT * FROM player ...
let request = Player
.with(playerNameCTE)...
```
And we can then filter the `player` table with a subquery:
```swift
// WITH playerName AS (SELECT 'O''Brien')
// SELECT * FROM player
// WHERE name = (SELECT * FROM playerName)
let request = Player
.with(playerNameCTE)
.filter(Column("name") == playerNameCTE.all())
```
> :point_up: **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request.
>
> :point_up: **Note**: the `with(_:)` method can be called at any time, as all request methods: `Player.with(...).filter(...).with(...)`.
>
> :point_up: **Note**: the `with(_:)` method replaces any previously embedded CTE that has the same table name. This allows you to embed the same CTE several times if you feel like it.
>
> :point_up: **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be mismatched with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
>
> ```swift
> cte.all().select(...).filter(...).group(...).order(...)
> ```
Common table expressions can also be embedded in [SQLRequest] with [SQL Interpolation]:
```swift
// WITH playerName AS (SELECT 'O''Brien')
// SELECT * FROM player
// WHERE name = (SELECT * FROM playerName)
let request: SQLRequest<Player> = """
WITH \(definitionFor: playerNameCTE)
SELECT * FROM player
WHERE name = (SELECT * FROM \(playerNameCTE))
"""
// WITH playerName AS (SELECT 'O''Brien')
// SELECT * FROM player
// WHERE name = (SELECT * FROM playerName)
let request: SQLRequest<Player> = """
WITH \(definitionFor: playerNameCTE)
SELECT * FROM player
WHERE name = (\(playerNameCTE.all()))
"""
```
Common table expressions can also be used as subqueries, when you update or delete rows in the database:
```swift
// WITH playerName AS (SELECT 'O''Brien')
// UPDATE player SET name = (SELECT * FROM playerName)
try Player
.with(playerNameCTE)
.updateAll(db, Column("name").set(to: playerNameCTE.all()))
// WITH playerName AS (SELECT 'O''Brien')
// DELETE FROM player WHERE name = (SELECT * FROM playerName)
try Player
.with(playerNameCTE)
.filter(Column("name") == playerNameCTE.all())
.deleteAll(db)
```
## Fetch Values From Common Table Expressions
In the previous chapter, a common table expression was embedded as a subquery, with the `CommonTableExpression.all()` method.
`all()` builds a regular [query interface request] that you can filter, sort, etc, like all query interface requests. You can also fetch from it, but only as long as it is provided with the definition of the CTE.
This will generally give requests of the form `cte.all().with(cte)`. In SQL, this would give: `WITH cte AS (...) SELECT * FROM cte`.
The generic type of `CommonTableExpression<...>` now turns out useful, so that you can fetch the desired outcome (database [rows](../README.md#row-queries), simple [values](../README.md#value-queries), or custom [records](../README.md#records)).
For example, let's fetch a range of integer:
```swift
func counterRequest(range: ClosedRange<Int>) -> QueryInterfaceRequest<Int> {
// WITH RECURSIVE counter(x) AS
// (VALUES(...) UNION ALL SELECT x+1 FROM counter WHERE x<...)
// SELECT * FROM counter
let counter = CommonTableExpression<Int>(
recursive: true,
named: "counter",
columns: ["x"],
literal: """
VALUES(\(range.lowerBound)) \
UNION ALL \
SELECT x+1 FROM counter WHERE x < \(range.upperBound)
""")
return counter.all().with(counter)
}
let values = try dbQueue.read { db in
try counterRequest(range: 3...7).fetchAll(db)
}
print(values) // prints "[3, 4, 5, 6, 7]"
```
When you have to fetch from a `CommonTableExpression` which does not have the desired generic type, you can still use the `asRequest(of:)` method:
```swift
let cte: CommonTableExpression<Void> = ...
let rows: [Row] = try dbQueue.read { db in
try cte.all().with(cte)
.asRequest(of: Row.self)
.fetchAll(db)
}
```
## Associations to Common Table Expressions
GRDB [associations] define "to-one" and "to-many" relationships between two database tables. Here we will define associations between regular tables and common table expressions.
We recommend familiarity with the "joining methods", described in [Joining And Prefetching Associated Records]:
```swift
// SELECT parent.* FROM parent LEFT JOIN child ON ...
Parent.joining(optional: childAssociation)
// SELECT parent.* FROM parent JOIN child ON ...
Parent.joining(required: childAssociation)
// SELECT parent.*, child.* FROM parent LEFT JOIN child ON ...
Parent.including(optional: childAssociation)
// SELECT parent.*, child.* FROM parent JOIN child ON ...
Parent.including(required: childAssociation)
```
> :point_up: **Note**: common table expressions currently only define "to-one" associations, so the `including(all:)` joining method is unavailable.
CTE associations are generally built with the `association(to:on:)` method, which needs:
- The two sides of the association: a `CommonTableExpression` instance, and another CTE or a type that conforms to the [TableRecord] protocol.
- A function that returns the condition that joins the two sides of the association.
The condition function plays the same role as the **foreign key** that defines regular table [associations] such as **BelongsTo** or **HasMany**. It accepts two [TableAlias], from which you can build a joining expression:
For example:
```swift
// An association from LeftRecord to rightCTE
let rightCTE = ...
let association = LeftRecord.association(
to: rightCTE,
on: { left, right in
left[Column("x")] = right[Column("y")]
})
```
Now this association can be used with a joining method:
```swift
// WITH rightCTE AS (...)
// SELECT leftRecord.*, rightCTE.*
// FROM leftRecord
// JOIN rightCTE ON leftRecord.x = rightCTE.y
LeftRecord
.with(rightCTE)
.including(required: association)
```
### CTE Association Example: a Chat App
As an example, let's build the classical main screen of a chat application: a list of all latest messages from all conversations.
The database schema of the chat app contains a `chat` and a `message` table. The application defines the following records:
```swift
struct Chat: Codable, FetchableRecord, PersistableRecord {
var id: Int64
...
}
struct Message: Codable, FetchableRecord, PersistableRecord {
var chatID: Int64
var date: Date
...
}
```
To feed the main app screen, we want to fetch a list of `ChatInfo` records:
```swift
struct ChatInfo: Decodable, FetchableRecord {
/// The chat
var chat: Chat
/// The latest chat message, if any
var latestMessage: Message?
}
```
The SQL request that we want to run is below. It uses an SQLite-specific [special processing](https://sqlite.org/lang_select.html) of `MAX()` that helps the selection of latest messages from all chats:
```sql
WITH latestMessage AS
(SELECT *, MAX(date) FROM message GROUP BY chatID)
SELECT chat.*, latestMessage.*
FROM chat
LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
ORDER BY latestMessage.date DESC
```
We start by defining the CTE request, which loads the latest messages of all chats:
```swift
// SELECT *, MAX(date) FROM message GROUP BY chatID
let latestMessageRequest = Message
.annotated(with: max(Column("date")))
.group(Column("chatID"))
```
We can now define the CTE for the latest messages:
```swift
// WITH latestMessage AS
// (SELECT *, MAX(date) FROM message GROUP BY chatID)
let latestMessageCTE = CommonTableExpression<Void>(
named: "latestMessage",
request: latestMessageRequest)
```
The association from a chat to its latest message follows:
```swift
// ... JOIN latestMessage ON chat.id = latestMessage.chatID
let latestMessage = Chat.association(
to: latestMessageCTE,
on: { chat, latestMessage in
chat[Column("id")] == latestMessage[Column("chatID")]
})
.order(Column("date").desc)
```
The final request can now be defined:
```swift
// WITH latestMessage AS
// (SELECT *, MAX(date) FROM message GROUP BY chatID)
// SELECT chat.*, latestMessage.*
// FROM chat
// LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
// ORDER BY latestMessage.date DESC
let request = Chat
.with(latestMessageCTE)
.including(optional: latestMessage)
.asRequest(of: ChatInfo.self)
```
And we can fetch the data that feeds our application screen:
```swift
let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
```
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, our go-to `CommonTableExpression<Void>` CTEs can work against type safety. So when you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your `CommonTableExpression` with a type instead of `Void`.
>
> You can use an existing record type, or an ad-hoc enum. For example:
>
> ```swift
> enum CTE1 { }
> let cte1 = CommonTableExpression<CTE1>(...)
>
> enum CTE2 { }
> let cte2 = CommonTableExpression<CTE2>(...)
>
> let assoc1 = BaseRecord.association(to: cte1, on: ...)
> let assoc2 = cte1.association(to: cte2, on: ...)
> let assoc3 = cte2.association(to: FarRecord.self, on: ...)
>
> // WITH ...
> // SELECT base.* FROM base
> // JOIN cte1 ON ...
> // JOIN cte2 ON ...
> // JOIN far ON ...
> let request = BaseRecord
> .with(cte1).with(cte2)
> .joining(required: assoc1
> .joining(required: assoc2
> .joining(required: assoc3)))
>
> // Compiler error
> let request = BaseRecord.joining(required: assoc2)
> ```
[query interface request]: ../README.md#requests
[query interface requests]: ../README.md#requests
[SQLRequest]: ../README.md#custom-requests
[SQLiteral]: SQLInterpolation.md
[SQL Interpolation]: SQLInterpolation.md
[associations]: AssociationsBasics.md
[Joining And Prefetching Associated Records]: AssociationsBasics.md#joining-and-prefetching-associated-records
[Define Common Table Expressions]: #define-common-table-expressions
[Embed Common Table Expressions in Requests]: #embed-common-table-expressions-in-requests
[Fetch Values From Common Table Expressions]: #fetch-values-from-common-table-expressions
[Associations to Common Table Expressions]: #associations-to-common-table-expressions
[TableRecord]: ../README.md#tablerecord-protocol
[TableAlias]: AssociationsBasics.md#table-aliases
+1 -1
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.28.0](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.33.0](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks).
@@ -7,263 +7,329 @@
objects = {
/* Begin PBXBuildFile section */
563F3E7124A78BD400982CF8 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F3E7024A78BD400982CF8 /* AppDelegate.swift */; };
563F3E7324A78BD400982CF8 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F3E7224A78BD400982CF8 /* SceneDelegate.swift */; };
563F3E7724A78BD700982CF8 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 563F3E7624A78BD700982CF8 /* Assets.xcassets */; };
563F3E7A24A78BD700982CF8 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 563F3E7924A78BD700982CF8 /* Preview Assets.xcassets */; };
563F3E7D24A78BD700982CF8 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 563F3E7B24A78BD700982CF8 /* LaunchScreen.storyboard */; };
5651F47D24A8837800727C9D /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5651F47124A8835B00727C9D /* GRDB.framework */; };
5651F47F24A884B200727C9D /* World.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F47E24A884B200727C9D /* World.swift */; };
5651F48124A8856300727C9D /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F48024A8856300727C9D /* PlayerList.swift */; };
5651F48324A885AF00727C9D /* PlayerListViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F48224A885AF00727C9D /* PlayerListViewModel.swift */; };
5651F48524A8905100727C9D /* PlayerEditor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F48424A8905100727C9D /* PlayerEditor.swift */; };
5651F48724A8909F00727C9D /* PlayerFormViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F48624A8909F00727C9D /* PlayerFormViewModel.swift */; };
5678066124A8A4E400606BC6 /* Localizable.stringsdict in Resources */ = {isa = PBXBuildFile; fileRef = 5678066324A8A4E400606BC6 /* Localizable.stringsdict */; };
5678066524A8B7DD00606BC6 /* PlayerCreationSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5678066424A8B7DD00606BC6 /* PlayerCreationSheet.swift */; };
56AAFD4724A78F9A0077EADB /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AAFD4524A78F9A0077EADB /* AppDatabase.swift */; };
56AAFD4824A78F9A0077EADB /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AAFD4624A78F9A0077EADB /* Player.swift */; };
56B1B13024A8E9A700D7FB31 /* PlayerForm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1B12F24A8E9A700D7FB31 /* PlayerForm.swift */; };
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */; };
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */; };
567C3E1A2520B6DE0011F6E9 /* GRDBCombineDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */; };
567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */; };
567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */; };
567C3E4E2520B70E0011F6E9 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 567C3E3B2520B7000011F6E9 /* GRDB.framework */; };
567C3E4F2520B70E0011F6E9 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 567C3E3B2520B7000011F6E9 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E532520B75C0011F6E9 /* Player.swift */; };
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E542520B75C0011F6E9 /* Persistence.swift */; };
567C3E5F2520B75C0011F6E9 /* PlayerListViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */; };
567C3E602520B75C0011F6E9 /* PlayerFormViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */; };
567C3E612520B75D0011F6E9 /* PlayerForm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E592520B75C0011F6E9 /* PlayerForm.swift */; };
567C3E622520B75D0011F6E9 /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5A2520B75C0011F6E9 /* PlayerList.swift */; };
567C3E632520B75D0011F6E9 /* PlayerCreationSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */; };
567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */; };
567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E652520B7880011F6E9 /* AppDatabase.swift */; };
567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E752520BB650011F6E9 /* Localizable.stringsdict */; };
567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
5651F46A24A8835B00727C9D /* PBXContainerItemProxy */ = {
56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
remoteInfo = GRDBCombineDemo;
};
567C3E342520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = DC3773F319C8CBB3004FCF85;
remoteInfo = GRDBOSX;
};
5651F46C24A8835B00727C9D /* PBXContainerItemProxy */ = {
567C3E362520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
remoteInfo = GRDBOSXTests;
};
5651F46E24A8835B00727C9D /* PBXContainerItemProxy */ = {
567C3E382520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56553C181C3E906C00522B5C;
remoteInfo = GRDBOSXCrashTests;
};
5651F47024A8835B00727C9D /* PBXContainerItemProxy */ = {
567C3E3A2520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7CA1B4D3FED00430942;
remoteInfo = GRDBiOS;
};
5651F47224A8835B00727C9D /* PBXContainerItemProxy */ = {
567C3E3C2520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
remoteInfo = GRDBiOSTests;
};
5651F47424A8835B00727C9D /* PBXContainerItemProxy */ = {
567C3E3E2520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 565490A01D5A4798005622CB;
remoteInfo = GRDBWatchOS;
};
5651F47624A8835B00727C9D /* PBXContainerItemProxy */ = {
567C3E402520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = AAA4DCFE230F1E0600C74B15;
remoteInfo = GRDBtvOS;
};
5651F47824A8835B00727C9D /* PBXContainerItemProxy */ = {
567C3E422520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = AAA4DDD4230F262000C74B15;
remoteInfo = GRDBtvOSTests;
};
5651F47A24A8836B00727C9D /* PBXContainerItemProxy */ = {
567C3E512520B71C0011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
remoteInfo = GRDBiOS;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
567C3E502520B70E0011F6E9 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
567C3E4F2520B70E0011F6E9 /* GRDB.framework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
563F3E6D24A78BD400982CF8 /* GRDBCombineDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBCombineDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
563F3E7024A78BD400982CF8 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
563F3E7224A78BD400982CF8 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
563F3E7624A78BD700982CF8 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
563F3E7924A78BD700982CF8 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = "<group>"; };
563F3E7C24A78BD700982CF8 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
563F3E7E24A78BD700982CF8 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
5651F45F24A8835B00727C9D /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
5651F47E24A884B200727C9D /* World.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = World.swift; sourceTree = "<group>"; };
5651F48024A8856300727C9D /* PlayerList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = "<group>"; };
5651F48224A885AF00727C9D /* PlayerListViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerListViewModel.swift; sourceTree = "<group>"; };
5651F48424A8905100727C9D /* PlayerEditor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerEditor.swift; sourceTree = "<group>"; };
5651F48624A8909F00727C9D /* PlayerFormViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerFormViewModel.swift; sourceTree = "<group>"; };
5678066224A8A4E400606BC6 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = en; path = en.lproj/Localizable.stringsdict; sourceTree = "<group>"; };
5678066424A8B7DD00606BC6 /* PlayerCreationSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerCreationSheet.swift; sourceTree = "<group>"; };
56AAFD4524A78F9A0077EADB /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
56AAFD4624A78F9A0077EADB /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
56B1B12F24A8E9A700D7FB31 /* PlayerForm.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerForm.swift; sourceTree = "<group>"; };
56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCombineDemoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
56026C9C25B8A7D000D1DF3F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = "<group>"; };
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = "<group>"; };
567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBCombineDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBCombineDemoApp.swift; sourceTree = "<group>"; };
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = "<group>"; };
567C3E222520B6DF0011F6E9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
567C3E292520B7000011F6E9 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
567C3E532520B75C0011F6E9 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
567C3E542520B75C0011F6E9 /* Persistence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = "<group>"; };
567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewModel.swift; sourceTree = "<group>"; };
567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerFormViewModel.swift; sourceTree = "<group>"; };
567C3E592520B75C0011F6E9 /* PlayerForm.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerForm.swift; sourceTree = "<group>"; };
567C3E5A2520B75C0011F6E9 /* PlayerList.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = "<group>"; };
567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerCreationSheet.swift; sourceTree = "<group>"; };
567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionView.swift; sourceTree = "<group>"; };
567C3E652520B7880011F6E9 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
567C3E762520BB650011F6E9 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = en; path = en.lproj/Localizable.stringsdict; sourceTree = "<group>"; };
567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
563F3E6A24A78BD400982CF8 /* Frameworks */ = {
56026C9525B8A7D000D1DF3F /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
5651F47D24A8837800727C9D /* GRDB.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
567C3E132520B6DE0011F6E9 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
567C3E4E2520B70E0011F6E9 /* GRDB.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
56248FEF24A8F3DD009C144A /* ViewModels */ = {
56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */ = {
isa = PBXGroup;
children = (
5651F48624A8909F00727C9D /* PlayerFormViewModel.swift */,
5651F48224A885AF00727C9D /* PlayerListViewModel.swift */,
56026C9C25B8A7D000D1DF3F /* Info.plist */,
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */,
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */,
);
path = ViewModels;
path = GRDBCombineDemoTests;
sourceTree = "<group>";
};
563F3E6424A78BD400982CF8 = {
56185BC125B8047D00B9C30F /* Resources */ = {
isa = PBXGroup;
children = (
5651F45F24A8835B00727C9D /* GRDB.xcodeproj */,
563F3E6F24A78BD400982CF8 /* GRDBCombineDemo */,
563F3E6E24A78BD400982CF8 /* Products */,
5651F47C24A8837800727C9D /* Frameworks */,
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */,
567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */,
567C3E752520BB650011F6E9 /* Localizable.stringsdict */,
);
path = Resources;
sourceTree = "<group>";
};
56185BC225B8048B00B9C30F /* Support */ = {
isa = PBXGroup;
children = (
567C3E222520B6DF0011F6E9 /* Info.plist */,
);
name = Support;
sourceTree = "<group>";
};
567C3E0D2520B6DE0011F6E9 = {
isa = PBXGroup;
children = (
567C3E292520B7000011F6E9 /* GRDB.xcodeproj */,
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */,
56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */,
567C3E172520B6DE0011F6E9 /* Products */,
567C3E4D2520B70E0011F6E9 /* Frameworks */,
);
sourceTree = "<group>";
};
563F3E6E24A78BD400982CF8 /* Products */ = {
567C3E172520B6DE0011F6E9 /* Products */ = {
isa = PBXGroup;
children = (
563F3E6D24A78BD400982CF8 /* GRDBCombineDemo.app */,
567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */,
56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
563F3E6F24A78BD400982CF8 /* GRDBCombineDemo */ = {
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */ = {
isa = PBXGroup;
children = (
563F3E7024A78BD400982CF8 /* AppDelegate.swift */,
563F3E7224A78BD400982CF8 /* SceneDelegate.swift */,
56AAFD4524A78F9A0077EADB /* AppDatabase.swift */,
56AAFD4624A78F9A0077EADB /* Player.swift */,
5651F47E24A884B200727C9D /* World.swift */,
56248FEF24A8F3DD009C144A /* ViewModels */,
56B1B12524A8DA1000D7FB31 /* Views */,
563F3E7824A78BD700982CF8 /* Preview Content */,
56B1B12D24A8DA3300D7FB31 /* Resources */,
56B1B12E24A8DA4F00D7FB31 /* Support */,
567C3E652520B7880011F6E9 /* AppDatabase.swift */,
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */,
567C3E542520B75C0011F6E9 /* Persistence.swift */,
567C3E532520B75C0011F6E9 /* Player.swift */,
567C3E1F2520B6DF0011F6E9 /* Preview Content */,
56185BC125B8047D00B9C30F /* Resources */,
56185BC225B8048B00B9C30F /* Support */,
567C3E552520B75C0011F6E9 /* ViewModels */,
567C3E582520B75C0011F6E9 /* Views */,
);
path = GRDBCombineDemo;
sourceTree = "<group>";
};
563F3E7824A78BD700982CF8 /* Preview Content */ = {
567C3E1F2520B6DF0011F6E9 /* Preview Content */ = {
isa = PBXGroup;
children = (
563F3E7924A78BD700982CF8 /* Preview Assets.xcassets */,
567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */,
);
path = "Preview Content";
sourceTree = "<group>";
};
5651F46024A8835B00727C9D /* Products */ = {
567C3E2A2520B7000011F6E9 /* Products */ = {
isa = PBXGroup;
children = (
5651F46B24A8835B00727C9D /* GRDB.framework */,
5651F46D24A8835B00727C9D /* GRDBOSXTests.xctest */,
5651F46F24A8835B00727C9D /* GRDBOSXCrashTests.xctest */,
5651F47124A8835B00727C9D /* GRDB.framework */,
5651F47324A8835B00727C9D /* GRDBiOSTests.xctest */,
5651F47524A8835B00727C9D /* GRDB.framework */,
5651F47724A8835B00727C9D /* GRDB.framework */,
5651F47924A8835B00727C9D /* GRDBtvOSTests.xctest */,
567C3E352520B7000011F6E9 /* GRDB.framework */,
567C3E372520B7000011F6E9 /* GRDBOSXTests.xctest */,
567C3E392520B7000011F6E9 /* GRDBOSXCrashTests.xctest */,
567C3E3B2520B7000011F6E9 /* GRDB.framework */,
567C3E3D2520B7000011F6E9 /* GRDBiOSTests.xctest */,
567C3E3F2520B7000011F6E9 /* GRDB.framework */,
567C3E412520B7000011F6E9 /* GRDB.framework */,
567C3E432520B7000011F6E9 /* GRDBtvOSTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
5651F47C24A8837800727C9D /* Frameworks */ = {
567C3E4D2520B70E0011F6E9 /* Frameworks */ = {
isa = PBXGroup;
children = (
);
name = Frameworks;
sourceTree = "<group>";
};
56B1B12524A8DA1000D7FB31 /* Views */ = {
567C3E552520B75C0011F6E9 /* ViewModels */ = {
isa = PBXGroup;
children = (
5678066424A8B7DD00606BC6 /* PlayerCreationSheet.swift */,
5651F48424A8905100727C9D /* PlayerEditor.swift */,
56B1B12F24A8E9A700D7FB31 /* PlayerForm.swift */,
5651F48024A8856300727C9D /* PlayerList.swift */,
567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */,
567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */,
);
path = ViewModels;
sourceTree = "<group>";
};
567C3E582520B75C0011F6E9 /* Views */ = {
isa = PBXGroup;
children = (
567C3E592520B75C0011F6E9 /* PlayerForm.swift */,
567C3E5A2520B75C0011F6E9 /* PlayerList.swift */,
567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */,
567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */,
);
path = Views;
sourceTree = "<group>";
};
56B1B12D24A8DA3300D7FB31 /* Resources */ = {
isa = PBXGroup;
children = (
563F3E7624A78BD700982CF8 /* Assets.xcassets */,
563F3E7B24A78BD700982CF8 /* LaunchScreen.storyboard */,
5678066324A8A4E400606BC6 /* Localizable.stringsdict */,
);
name = Resources;
sourceTree = "<group>";
};
56B1B12E24A8DA4F00D7FB31 /* Support */ = {
isa = PBXGroup;
children = (
563F3E7E24A78BD700982CF8 /* Info.plist */,
);
name = Support;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
563F3E6C24A78BD400982CF8 /* GRDBCombineDemo */ = {
56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 563F3E8124A78BD700982CF8 /* Build configuration list for PBXNativeTarget "GRDBCombineDemo" */;
buildConfigurationList = 56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoTests" */;
buildPhases = (
563F3E6924A78BD400982CF8 /* Sources */,
563F3E6A24A78BD400982CF8 /* Frameworks */,
563F3E6B24A78BD400982CF8 /* Resources */,
56026C9425B8A7D000D1DF3F /* Sources */,
56026C9525B8A7D000D1DF3F /* Frameworks */,
56026C9625B8A7D000D1DF3F /* Resources */,
);
buildRules = (
);
dependencies = (
5651F47B24A8836B00727C9D /* PBXTargetDependency */,
56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */,
);
name = GRDBCombineDemoTests;
productName = GRDBCombineDemoTests;
productReference = 56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = 567C3E252520B6DF0011F6E9 /* Build configuration list for PBXNativeTarget "GRDBCombineDemo" */;
buildPhases = (
567C3E122520B6DE0011F6E9 /* Sources */,
567C3E132520B6DE0011F6E9 /* Frameworks */,
567C3E142520B6DE0011F6E9 /* Resources */,
567C3E502520B70E0011F6E9 /* Embed Frameworks */,
);
buildRules = (
);
dependencies = (
567C3E522520B71C0011F6E9 /* PBXTargetDependency */,
);
name = GRDBCombineDemo;
productName = GRDBCombineDemo;
productReference = 563F3E6D24A78BD400982CF8 /* GRDBCombineDemo.app */;
productName = GRBCombineDemo;
productReference = 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
563F3E6524A78BD400982CF8 /* Project object */ = {
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1150;
LastUpgradeCheck = 1150;
ORGANIZATIONNAME = "Gwendal Roué";
LastSwiftUpdateCheck = 1230;
LastUpgradeCheck = 1200;
TargetAttributes = {
563F3E6C24A78BD400982CF8 = {
CreatedOnToolsVersion = 11.5;
56026C9725B8A7D000D1DF3F = {
CreatedOnToolsVersion = 12.3;
TestTargetID = 567C3E152520B6DE0011F6E9;
};
567C3E152520B6DE0011F6E9 = {
CreatedOnToolsVersion = 12.0;
};
};
};
buildConfigurationList = 563F3E6824A78BD400982CF8 /* Build configuration list for PBXProject "GRDBCombineDemo" */;
buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
@@ -271,145 +337,206 @@
en,
Base,
);
mainGroup = 563F3E6424A78BD400982CF8;
productRefGroup = 563F3E6E24A78BD400982CF8 /* Products */;
mainGroup = 567C3E0D2520B6DE0011F6E9;
productRefGroup = 567C3E172520B6DE0011F6E9 /* Products */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = 5651F46024A8835B00727C9D /* Products */;
ProjectRef = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
ProductGroup = 567C3E2A2520B7000011F6E9 /* Products */;
ProjectRef = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
},
);
projectRoot = "";
targets = (
563F3E6C24A78BD400982CF8 /* GRDBCombineDemo */,
567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */,
56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */,
);
};
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
5651F46B24A8835B00727C9D /* GRDB.framework */ = {
567C3E352520B7000011F6E9 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 5651F46A24A8835B00727C9D /* PBXContainerItemProxy */;
remoteRef = 567C3E342520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5651F46D24A8835B00727C9D /* GRDBOSXTests.xctest */ = {
567C3E372520B7000011F6E9 /* GRDBOSXTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXTests.xctest;
remoteRef = 5651F46C24A8835B00727C9D /* PBXContainerItemProxy */;
remoteRef = 567C3E362520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5651F46F24A8835B00727C9D /* GRDBOSXCrashTests.xctest */ = {
567C3E392520B7000011F6E9 /* GRDBOSXCrashTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXCrashTests.xctest;
remoteRef = 5651F46E24A8835B00727C9D /* PBXContainerItemProxy */;
remoteRef = 567C3E382520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5651F47124A8835B00727C9D /* GRDB.framework */ = {
567C3E3B2520B7000011F6E9 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 5651F47024A8835B00727C9D /* PBXContainerItemProxy */;
remoteRef = 567C3E3A2520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5651F47324A8835B00727C9D /* GRDBiOSTests.xctest */ = {
567C3E3D2520B7000011F6E9 /* GRDBiOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBiOSTests.xctest;
remoteRef = 5651F47224A8835B00727C9D /* PBXContainerItemProxy */;
remoteRef = 567C3E3C2520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5651F47524A8835B00727C9D /* GRDB.framework */ = {
567C3E3F2520B7000011F6E9 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 5651F47424A8835B00727C9D /* PBXContainerItemProxy */;
remoteRef = 567C3E3E2520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5651F47724A8835B00727C9D /* GRDB.framework */ = {
567C3E412520B7000011F6E9 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 5651F47624A8835B00727C9D /* PBXContainerItemProxy */;
remoteRef = 567C3E402520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5651F47924A8835B00727C9D /* GRDBtvOSTests.xctest */ = {
567C3E432520B7000011F6E9 /* GRDBtvOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBtvOSTests.xctest;
remoteRef = 5651F47824A8835B00727C9D /* PBXContainerItemProxy */;
remoteRef = 567C3E422520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
563F3E6B24A78BD400982CF8 /* Resources */ = {
56026C9625B8A7D000D1DF3F /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
563F3E7D24A78BD700982CF8 /* LaunchScreen.storyboard in Resources */,
5678066124A8A4E400606BC6 /* Localizable.stringsdict in Resources */,
563F3E7A24A78BD700982CF8 /* Preview Assets.xcassets in Resources */,
563F3E7724A78BD700982CF8 /* Assets.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
567C3E142520B6DE0011F6E9 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */,
567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */,
567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */,
567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
563F3E6924A78BD400982CF8 /* Sources */ = {
56026C9425B8A7D000D1DF3F /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
5651F47F24A884B200727C9D /* World.swift in Sources */,
5651F48324A885AF00727C9D /* PlayerListViewModel.swift in Sources */,
56B1B13024A8E9A700D7FB31 /* PlayerForm.swift in Sources */,
5678066524A8B7DD00606BC6 /* PlayerCreationSheet.swift in Sources */,
563F3E7124A78BD400982CF8 /* AppDelegate.swift in Sources */,
563F3E7324A78BD400982CF8 /* SceneDelegate.swift in Sources */,
5651F48724A8909F00727C9D /* PlayerFormViewModel.swift in Sources */,
5651F48124A8856300727C9D /* PlayerList.swift in Sources */,
56AAFD4724A78F9A0077EADB /* AppDatabase.swift in Sources */,
5651F48524A8905100727C9D /* PlayerEditor.swift in Sources */,
56AAFD4824A78F9A0077EADB /* Player.swift in Sources */,
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */,
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
567C3E122520B6DE0011F6E9 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */,
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */,
567C3E612520B75D0011F6E9 /* PlayerForm.swift in Sources */,
567C3E632520B75D0011F6E9 /* PlayerCreationSheet.swift in Sources */,
567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */,
567C3E622520B75D0011F6E9 /* PlayerList.swift in Sources */,
567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */,
567C3E1A2520B6DE0011F6E9 /* GRDBCombineDemoApp.swift in Sources */,
567C3E5F2520B75C0011F6E9 /* PlayerListViewModel.swift in Sources */,
567C3E602520B75C0011F6E9 /* PlayerFormViewModel.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
5651F47B24A8836B00727C9D /* PBXTargetDependency */ = {
56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */;
targetProxy = 56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */;
};
567C3E522520B71C0011F6E9 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBiOS;
targetProxy = 5651F47A24A8836B00727C9D /* PBXContainerItemProxy */;
targetProxy = 567C3E512520B71C0011F6E9 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
563F3E7B24A78BD700982CF8 /* LaunchScreen.storyboard */ = {
567C3E752520BB650011F6E9 /* Localizable.stringsdict */ = {
isa = PBXVariantGroup;
children = (
563F3E7C24A78BD700982CF8 /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
5678066324A8A4E400606BC6 /* Localizable.stringsdict */ = {
isa = PBXVariantGroup;
children = (
5678066224A8A4E400606BC6 /* en */,
567C3E762520BB650011F6E9 /* en */,
);
name = Localizable.stringsdict;
sourceTree = "<group>";
};
567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
567C3E782520BB650011F6E9 /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
563F3E7F24A78BD700982CF8 /* Debug */ = {
56026C9F25B8A7D000D1DF3F /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemoTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBCombineDemo.app/GRDBCombineDemo";
};
name = Debug;
};
56026CA025B8A7D000D1DF3F /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemoTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBCombineDemo.app/GRDBCombineDemo";
};
name = Release;
};
567C3E232520B6DF0011F6E9 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
@@ -435,6 +562,7 @@
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
@@ -459,7 +587,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.5;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@@ -469,7 +597,7 @@
};
name = Debug;
};
563F3E8024A78BD700982CF8 /* Release */ = {
567C3E242520B6DF0011F6E9 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
@@ -495,6 +623,7 @@
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
@@ -513,7 +642,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.5;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
@@ -523,15 +652,17 @@
};
name = Release;
};
563F3E8224A78BD700982CF8 /* Debug */ = {
567C3E262520B6DF0011F6E9 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_ASSET_PATHS = "\"GRDBCombineDemo/Preview Content\"";
DEVELOPMENT_TEAM = AMD8W895CT;
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -543,15 +674,17 @@
};
name = Debug;
};
563F3E8324A78BD700982CF8 /* Release */ = {
567C3E272520B6DF0011F6E9 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_ASSET_PATHS = "\"GRDBCombineDemo/Preview Content\"";
DEVELOPMENT_TEAM = AMD8W895CT;
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -566,25 +699,34 @@
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
563F3E6824A78BD400982CF8 /* Build configuration list for PBXProject "GRDBCombineDemo" */ = {
56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
563F3E7F24A78BD700982CF8 /* Debug */,
563F3E8024A78BD700982CF8 /* Release */,
56026C9F25B8A7D000D1DF3F /* Debug */,
56026CA025B8A7D000D1DF3F /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
563F3E8124A78BD700982CF8 /* Build configuration list for PBXNativeTarget "GRDBCombineDemo" */ = {
567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
563F3E8224A78BD700982CF8 /* Debug */,
563F3E8324A78BD700982CF8 /* Release */,
567C3E232520B6DF0011F6E9 /* Debug */,
567C3E242520B6DF0011F6E9 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
567C3E252520B6DF0011F6E9 /* Build configuration list for PBXNativeTarget "GRDBCombineDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
567C3E262520B6DF0011F6E9 /* Debug */,
567C3E272520B6DF0011F6E9 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 563F3E6524A78BD400982CF8 /* Project object */;
rootObject = 567C3E0E2520B6DE0011F6E9 /* Project object */;
}
@@ -2,6 +2,6 @@
<Workspace
version = "1.0">
<FileRef
location = "self:">
location = "self:/Users/groue/Documents/git/groue/GRDB.swift/Documentation/DemoApps/GRBCombineDemo/GRDBCombineDemo.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1230"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "567C3E152520B6DE0011F6E9"
BuildableName = "GRDBCombineDemo.app"
BlueprintName = "GRDBCombineDemo"
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56026C9725B8A7D000D1DF3F"
BuildableName = "GRDBCombineDemoTests.xctest"
BlueprintName = "GRDBCombineDemoTests"
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "567C3E152520B6DE0011F6E9"
BuildableName = "GRDBCombineDemo.app"
BlueprintName = "GRDBCombineDemo"
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "567C3E152520B6DE0011F6E9"
BuildableName = "GRDBCombineDemo.app"
BlueprintName = "GRDBCombineDemo"
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -5,15 +5,21 @@ import GRDB
///
/// It applies the pratices recommended at
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
final class AppDatabase {
private let dbQueue: DatabaseQueue
/// Creates an AppDatabase and make sure the database schema is ready.
init(_ dbQueue: DatabaseQueue) throws {
self.dbQueue = dbQueue
try migrator.migrate(dbQueue)
struct AppDatabase {
/// Creates an `AppDatabase`, and make sure the database schema is ready.
init(_ dbWriter: DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
}
/// Provides access to the database.
///
/// Application can use a `DatabasePool`, while SwiftUI previews and tests
/// can use a fast in-memory `DatabaseQueue`.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
private let dbWriter: DatabaseWriter
/// The DatabaseMigrator that defines the database schema.
///
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
@@ -32,9 +38,6 @@ final class AppDatabase {
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// Sort player names in a localized case insensitive fashion by default
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
.collate(.localizedCaseInsensitiveCompare)
t.column("score", .integer).notNull()
}
}
@@ -48,39 +51,36 @@ final class AppDatabase {
}
}
// MARK: - Database Access
//
// This extension defines methods that fulfill application needs, both in terms
// of writes and reads.
// MARK: - Database Access: Writes
extension AppDatabase {
// MARK: Writes
/// Save (insert or update) a player.
/// Saves (inserts or updates) a player. When the method returns, the
/// player is present in the database, and its id is not nil.
func savePlayer(_ player: inout Player) throws {
try dbQueue.write { db in
try dbWriter.write { db in
try player.save(db)
}
}
/// Delete the specified players
func deletePlayers(ids: [Int64]) throws {
try dbQueue.write { db in
try dbWriter.write { db in
_ = try Player.deleteAll(db, keys: ids)
}
}
/// Delete all players
func deleteAllPlayers() throws {
try dbQueue.write { db in
try dbWriter.write { db in
_ = try Player.deleteAll(db)
}
}
/// Refresh all players (by performing some random changes, for demo purpose).
func refreshPlayers() throws {
try dbQueue.write { db in
try dbWriter.write { db in
if try Player.fetchCount(db) == 0 {
// Insert new random players
// When database is empty, insert new random players
try createRandomPlayers(db)
} else {
// Insert a player
@@ -88,10 +88,12 @@ extension AppDatabase {
var player = Player.newRandom()
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() {
try player.updateChanges(db) {
@@ -104,7 +106,7 @@ extension AppDatabase {
/// Create random players if the database is empty.
func createRandomPlayersIfEmpty() throws {
try dbQueue.write { db in
try dbWriter.write { db in
if try Player.fetchCount(db) == 0 {
try createRandomPlayers(db)
}
@@ -118,16 +120,16 @@ extension AppDatabase {
try player.insert(db)
}
}
// MARK: Reads
}
// MARK: - Database Access: Reads
extension AppDatabase {
/// Returns a publisher that tracks changes in players ordered by name
func playersOrderedByNamePublisher() -> AnyPublisher<[Player], Error> {
ValueObservation
.tracking(Player.all().orderedByName().fetchAll)
// Use the .immediate scheduling so that views do not have to wait
// until the players are loaded.
.publisher(in: dbQueue, scheduling: .immediate)
.publisher(in: dbWriter, scheduling: .immediate)
.eraseToAnyPublisher()
}
@@ -135,29 +137,7 @@ extension AppDatabase {
func playersOrderedByScorePublisher() -> AnyPublisher<[Player], Error> {
ValueObservation
.tracking(Player.all().orderedByScore().fetchAll)
// Use the .immediate scheduling so that views do not have to wait
// until the players are loaded.
.publisher(in: dbQueue, scheduling: .immediate)
.publisher(in: dbWriter, scheduling: .immediate)
.eraseToAnyPublisher()
}
}
// MARK: - Support for Tests and Previews
#if DEBUG
extension AppDatabase {
/// Returns an empty, in-memory database, suitable for testing and previews.
static func empty() throws -> AppDatabase {
try AppDatabase(DatabaseQueue())
}
/// Returns an in-memory database populated with a few random
/// players, suitable for previews.
static func random() throws -> AppDatabase {
let database = try AppDatabase.empty()
try database.createRandomPlayersIfEmpty()
return database
}
}
#endif
@@ -1,45 +0,0 @@
import UIKit
import GRDB
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Setup database. Error handling left as an exercise for the reader.
try! setupDatabase()
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Database Setup
private func setupDatabase() throws {
// AppDelegate chooses the location of the database file.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let databaseURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
let dbQueue = try DatabaseQueue(path: databaseURL.path)
// Create the shared application database
let database = try AppDatabase(dbQueue)
// Populate the database if it is empty, for better demo purpose.
try database.createRandomPlayersIfEmpty()
// Expose it to the rest of the application
Current.database = { database }
}
}
@@ -0,0 +1,12 @@
import SwiftUI
@main
struct GRDBCombineDemoApp: App {
let appDatabase = AppDatabase.shared
var body: some Scene {
WindowGroup {
PlayerList(viewModel: PlayerListViewModel(database: appDatabase))
}
}
}
@@ -23,20 +23,12 @@
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
</dict>
</array>
</dict>
<true/>
</dict>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UILaunchScreen</key>
<dict/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
@@ -0,0 +1,58 @@
import GRDB
extension AppDatabase {
/// The database for the application
static let shared = makeShared()
private static func makeShared() -> AppDatabase {
do {
// Create a folder for storing the SQLite database, as well as
// the various temporary files created during normal database
// operations (https://sqlite.org/tempfiles.html).
let fileManager = FileManager()
let folderURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
// Connect to a database on disk
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
// Populate the database if it is empty, for better demo purpose.
try appDatabase.createRandomPlayersIfEmpty()
return appDatabase
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate.
//
// Typical reasons for an error here include:
// * The parent directory cannot be created, or disallows writing.
// * The database is not accessible, due to permissions or data protection when the device is locked.
// * The device is out of space.
// * The database could not be migrated to its latest schema version.
// Check the error message to determine what the actual problem was.
fatalError("Unresolved error \(error)")
}
}
/// Creates an empty database for SwiftUI previews
static func empty() -> AppDatabase {
// Connect to an in-memory database
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let dbQueue = DatabaseQueue()
return try! AppDatabase(dbQueue)
}
/// Creates a database full of random players for SwiftUI previews
static func random() -> AppDatabase {
let appDatabase = empty()
try! appDatabase.createRandomPlayersIfEmpty()
return appDatabase
}
}
@@ -2,8 +2,9 @@ import GRDB
/// The Player struct.
///
/// Identifiable conformance supports SwiftUI list animations
struct Player: Identifiable {
/// Identifiable conformance supports SwiftUI list animations.
/// Equatable conformance supports tests.
struct Player: Identifiable, Equatable {
/// The player id.
///
/// Int64 is the recommended type for auto-incremented database ids.
@@ -70,25 +71,35 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
extension DerivableRequest where RowDecoder == Player {
/// A request of players ordered by name
/// A request of players ordered by name.
///
/// For example:
///
/// let players = try dbQueue.read { db in
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByName().fetchAll(db)
/// }
func orderedByName() -> Self {
order(Player.Columns.name)
// Sort by name in a localized case insensitive fashion
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
/// A request of players ordered by score
/// A request of players ordered by score.
///
/// For example:
///
/// let players = try dbQueue.read { db in
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchAll(db)
/// }
/// let bestPlayer: Player? = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchOne(db)
/// }
func orderedByScore() -> Self {
order(Player.Columns.score.desc, Player.Columns.name)
// Sort by descending score, and then by name, in a
// localized case insensitive fashion
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
order(
Player.Columns.score.desc,
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
}
@@ -0,0 +1,11 @@
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -1,9 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="16097" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17156" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17125"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="System colors in document resources" minToolsVersion="11.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
@@ -19,12 +20,12 @@
<rect key="frame" x="123.5" y="334.5" width="167" height="237"/>
</imageView>
</subviews>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
<constraints>
<constraint firstItem="Sgi-te-PKu" firstAttribute="centerY" secondItem="6Tk-OE-BBY" secondAttribute="centerY" id="KT7-xd-gV4"/>
<constraint firstItem="Sgi-te-PKu" firstAttribute="centerX" secondItem="6Tk-OE-BBY" secondAttribute="centerX" id="feL-Vs-SeN"/>
</constraints>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
@@ -34,5 +35,8 @@
</scenes>
<resources>
<image name="LaunchIcon" width="167" height="237"/>
<systemColor name="systemBackgroundColor">
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</systemColor>
</resources>
</document>
@@ -1,52 +0,0 @@
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let viewModel = PlayerListViewModel(database: Current.database())
let rootView = PlayerList(viewModel: viewModel)
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: rootView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
@@ -3,7 +3,7 @@ import Foundation
/// The view model that validates and saves an edited player into the database.
///
/// It feeds `PlayerForm`, `PlayerCreationSheet` and `PlayerEditor`.
/// It feeds `PlayerForm`, `PlayerCreationSheet` and `PlayerEditionView`.
final class PlayerFormViewModel: ObservableObject {
/// A validation error that prevents the player from being saved into
/// the database.
@@ -9,11 +9,16 @@ final class PlayerListViewModel: ObservableObject {
case byName
}
struct PlayerList {
var players: [Player]
var animatedChanges: Bool
}
/// The list ordering
@Published var ordering: Ordering = .byScore
/// The players in the list
@Published var players: [Player] = []
@Published var playerList = PlayerList(players: [], animatedChanges: false)
/// The view model that edits a new player
let newPlayerViewModel: PlayerFormViewModel
@@ -24,9 +29,19 @@ final class PlayerListViewModel: ObservableObject {
init(database: AppDatabase) {
self.database = database
newPlayerViewModel = PlayerFormViewModel(database: database, player: .new())
playersCancellable = playersPublisher(in: database).sink { [weak self] players in
self?.players = players
}
playersCancellable = playersPublisher(in: database)
.scan(nil) { (previousList: PlayerList?, players: [Player]) in
if previousList == nil {
// Do not animate first view update
return PlayerList(players: players, animatedChanges: false)
} else {
return PlayerList(players: players, animatedChanges: true)
}
}
.compactMap { $0 }
.sink { [weak self] playerList in
self?.playerList = playerList
}
}
// MARK: - Players List Management
@@ -39,7 +54,7 @@ final class PlayerListViewModel: ObservableObject {
func deletePlayers(atOffsets offsets: IndexSet) {
// Eventual error presentation is left as an exercise for the reader.
let playerIDs = offsets.compactMap { players[$0].id }
let playerIDs = offsets.compactMap { playerList.players[$0].id }
try! database.deletePlayers(ids: playerIDs)
}
@@ -73,7 +88,7 @@ final class PlayerListViewModel: ObservableObject {
// MARK: - Player Edition
/// Returns a view model suitable for editing a player.
func editionViewModel(for player: Player) -> PlayerFormViewModel {
func formViewModel(for player: Player) -> PlayerFormViewModel {
PlayerFormViewModel(database: database, player: player)
}
@@ -2,7 +2,7 @@ import SwiftUI
/// The Player creation sheet
struct PlayerCreationSheet: View {
/// Manages edition of the new player
/// Manages the player form
let viewModel: PlayerFormViewModel
/// Executed when user cancels or saves the new user.
@@ -39,10 +39,9 @@ struct PlayerCreationSheet: View {
}
}
#if DEBUG
struct PlayerCreationSheet_Previews: PreviewProvider {
static var previews: some View {
let viewModel = try! PlayerFormViewModel(
let viewModel = PlayerFormViewModel(
database: .empty(),
player: .new())
@@ -51,5 +50,3 @@ struct PlayerCreationSheet_Previews: PreviewProvider {
dismissAction: { })
}
}
#endif
@@ -2,30 +2,28 @@ import SwiftUI
/// The Player edition view, designed to be the destination of
/// a NavigationLink.
struct PlayerEditor: View {
/// Manages edition of the player
struct PlayerEditionView: View {
/// Manages the player form
let viewModel: PlayerFormViewModel
var body: some View {
PlayerForm(viewModel: viewModel)
.onDisappear(perform: {
// Ignore validation errors
try? self.viewModel.savePlayer()
})
.onDisappear(perform: {
// Ignore validation errors
try? self.viewModel.savePlayer()
})
}
}
#if DEBUG
struct PlayerEditionView_Previews: PreviewProvider {
static var previews: some View {
let viewModel = try! PlayerFormViewModel(
let viewModel = PlayerFormViewModel(
database: .empty(),
player: .newRandom())
return NavigationView {
PlayerEditor(viewModel: viewModel)
PlayerEditionView(viewModel: viewModel)
.navigationBarTitle("Player Edition")
}
}
}
#endif
@@ -1,7 +1,7 @@
import SwiftUI
/// The Player edition form, embedded in both
/// `PlayerCreationSheet` and `PlayerEditor`.
/// The Player editing form, embedded in both
/// `PlayerCreationSheet` and `PlayerEditionView`.
struct PlayerForm: View {
/// Manages the player form
@ObservedObject var viewModel: PlayerFormViewModel
@@ -28,14 +28,12 @@ struct PlayerForm: View {
}
}
#if DEBUG
struct PlayerFormView_Previews: PreviewProvider {
static var previews: some View {
let viewModel = try! PlayerFormViewModel(
let viewModel = PlayerFormViewModel(
database: .empty(),
player: .newRandom())
return PlayerForm(viewModel: viewModel)
}
}
#endif
@@ -14,7 +14,7 @@ struct PlayerList: View {
playerList
toolbar
}
.navigationBarTitle(Text("\(viewModel.players.count) Players"))
.navigationBarTitle(Text("\(viewModel.playerList.players.count) Players"))
.navigationBarItems(
leading: HStack {
EditButton()
@@ -26,9 +26,10 @@ struct PlayerList: View {
private var playerList: some View {
List {
ForEach(viewModel.players) { player in
ForEach(viewModel.playerList.players) { player in
NavigationLink(destination: self.editionView(for: player)) {
PlayerRow(player: player)
.animation(nil)
}
}
.onDelete(perform: { offsets in
@@ -36,6 +37,7 @@ struct PlayerList: View {
})
}
.listStyle(PlainListStyle())
.animation(viewModel.playerList.animatedChanges ? .default : nil)
}
private var toolbar: some View {
@@ -52,7 +54,7 @@ struct PlayerList: View {
action: viewModel.stressTest,
label: { Image(systemName: "tornado").imageScale(.large) })
}
.padding()
}
@@ -80,8 +82,8 @@ struct PlayerList: View {
/// The view that edits a player in the list.
private func editionView(for player: Player) -> some View {
PlayerEditor(
viewModel: viewModel.editionViewModel(for: player))
PlayerEditionView(
viewModel: viewModel.formViewModel(for: player))
.navigationBarTitle(player.name)
}
@@ -92,7 +94,7 @@ struct PlayerList: View {
// Make sure we do not edit a previously created player.
self.viewModel.newPlayerViewModel.editNewPlayer()
self.newPlayerIsPresented = true
},
},
label: { Image(systemName: "plus").imageScale(.large) })
.sheet(
isPresented: $newPlayerIsPresented,
@@ -105,7 +107,7 @@ struct PlayerList: View {
viewModel: self.viewModel.newPlayerViewModel,
dismissAction: {
self.newPlayerIsPresented = false
})
})
}
}
@@ -121,11 +123,9 @@ struct PlayerRow: View {
}
}
#if DEBUG
struct PlayerListView_Previews: PreviewProvider {
static var previews: some View {
let viewModel = try! PlayerListViewModel(database: .random())
let viewModel = PlayerListViewModel(database: .random())
return PlayerList(viewModel: viewModel)
}
}
#endif
@@ -1,11 +0,0 @@
/// Dependency Injection based on the "How to Control the World" article:
/// https://www.pointfree.co/blog/posts/21-how-to-control-the-world
struct World {
/// The application database
var database: () -> AppDatabase
}
/// The current world.
///
/// Its setup is done by `AppDelegate`, or tests.
var Current = World(database: { fatalError("Database is uninitialized") })
@@ -0,0 +1,254 @@
import XCTest
import GRDB
@testable import GRDBCombineDemo
class AppDatabaseTests: XCTestCase {
func test_database_schema() throws {
// Given an empty database
let dbQueue = DatabaseQueue()
// When we instantiate an AppDatabase
_ = try AppDatabase(dbQueue)
// Then the player table exists, with id, name & score columns
try dbQueue.read { db in
try XCTAssert(db.tableExists("player"))
let columns = try db.columns(in: "player")
let columnNames = Set(columns.map { $0.name })
XCTAssertEqual(columnNames, ["id", "name", "score"])
}
}
func test_savePlayer_inserts() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we save a new player
var player = Player(id: nil, name: "Arthur", score: 100)
try appDatabase.savePlayer(&player)
// Then the player exists in the database
try XCTAssertTrue(dbQueue.read(player.exists))
}
func test_savePlayer_updates() throws {
// Given a players database that contains a player
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
try player.insert(db)
}
// When we modify and save the player
player.name = "Barbara"
player.score = 1000
try appDatabase.savePlayer(&player)
// Then the player has been updated in the database
let fetchedPlayer = try dbQueue.read { db in
try XCTUnwrap(Player.fetchOne(db, key: player.id))
}
XCTAssertEqual(fetchedPlayer, player)
}
func test_deletePlayers() throws {
// Given a players database that contains four players
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
var player3 = Player(id: nil, name: "Craig", score: 150)
var player4 = Player(id: nil, name: "David", score: 120)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
try player3.insert(db)
try player4.insert(db)
}
// When we delete two players
try appDatabase.deletePlayers(ids: [player1.id!, player3.id!])
// Then the deleted players no longer exist
try dbQueue.read { db in
try XCTAssertFalse(player1.exists(db))
try XCTAssertFalse(player3.exists(db))
}
// Then the database still contains two players
try XCTAssertEqual(dbQueue.read(Player.fetchCount), 2)
}
func test_deleteAllPlayers() throws {
// Given a players database that contains players
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
var player3 = Player(id: nil, name: "Craig", score: 150)
var player4 = Player(id: nil, name: "David", score: 120)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
try player3.insert(db)
try player4.insert(db)
}
// When we delete all players
try appDatabase.deleteAllPlayers()
// Then the database does not contain any player
try XCTAssertEqual(dbQueue.read(Player.fetchCount), 0)
}
func test_refreshPlayers_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we refresh players
try appDatabase.refreshPlayers()
// Then the database is not empty
try XCTAssert(dbQueue.read(Player.fetchCount) > 0)
}
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we create random players
try appDatabase.createRandomPlayersIfEmpty()
// Then the database is not empty
try XCTAssert(dbQueue.read(Player.fetchCount) > 0)
}
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
// Given a players database that contains one player
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
try player.insert(db)
}
// When we create random players
try appDatabase.createRandomPlayersIfEmpty()
// Then the database still only contains the original player
let players = try dbQueue.read(Player.fetchAll)
XCTAssertEqual(players, [player])
}
func test_playersOrderedByNamePublisher_publishes_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we observe players and wait for the first value
let exp = expectation(description: "Players")
var players: [Player]?
let cancellable = appDatabase.playersOrderedByNamePublisher().sink { completion in
if case let .failure(error) = completion {
XCTFail("Unexpected error \(error)")
}
} receiveValue: {
players = $0
exp.fulfill()
}
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
// Then the players are the two players ordered by name
XCTAssertEqual(players, [player1, player2])
}
func test_playersOrderedByNamePublisher_publishes_right_on_subscripion() throws {
// Our SwiftUI views have no "waiting" state, and must be fed with
// players without any delay in order to avoid any rendering glitch.
// This test makes sure `playersOrderedByNamePublisher` publishes right
// on subscription.
// Given a players database
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we observe players
var players: [Player]?
_ = appDatabase.playersOrderedByNamePublisher().sink { completion in
if case let .failure(error) = completion {
XCTFail("Unexpected error \(error)")
}
} receiveValue: {
players = $0
}
// Then the players are published right on subscription
XCTAssertNotNil(players)
}
func test_playersOrderedByScorePublisher_publishes_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we observe players and wait for the first value
let exp = expectation(description: "Players")
var players: [Player]?
let cancellable = appDatabase.playersOrderedByScorePublisher().sink { completion in
if case let .failure(error) = completion {
XCTFail("Unexpected error \(error)")
}
} receiveValue: {
players = $0
exp.fulfill()
}
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
// Then the players are the two players ordered by score descending
XCTAssertEqual(players, [player2, player1])
}
func test_playersOrderedByScorePublisher_publishes_right_on_subscripion() throws {
// Our SwiftUI views have no "waiting" state, and must be fed with
// players without any delay in order to avoid any rendering glitch.
// This test makes sure `playersOrderedByScorePublisher` publishes right
// on subscription.
// Given a players database
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we observe players
var players: [Player]?
_ = appDatabase.playersOrderedByScorePublisher().sink { completion in
if case let .failure(error) = completion {
XCTFail("Unexpected error \(error)")
}
} receiveValue: {
players = $0
}
// Then the players are published right on subscription
XCTAssertNotNil(players)
}
}
@@ -0,0 +1,22 @@
<?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>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
@@ -0,0 +1,108 @@
import XCTest
import GRDB
@testable import GRDBCombineDemo
class PlayerTests: XCTestCase {
// MARK: - CRUD
// Test that our Player type properly talks to GRDB.
func testInsert() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
_ = try AppDatabase(dbQueue)
// When we insert a player
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
try player.insert(db)
}
// Then the player gets a non-nil id
XCTAssertNotNil(player.id)
}
func testRoundtrip() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
_ = try AppDatabase(dbQueue)
// When we insert a player and fetch the player with the same id
var insertedPlayer = Player(id: nil, name: "Arthur", score: 100)
let fetchedPlayer: Player? = try dbQueue.write { db in
try insertedPlayer.insert(db)
return try Player.fetchOne(db, key: insertedPlayer.id)
}
// Then the fetched player is equal to the inserted player
XCTAssertEqual(insertedPlayer, fetchedPlayer)
}
// MARK: - Requests
// Test that requests defined on the Player type behave as expected.
func testOrderedByScore() throws {
// Given a players database that contains players with distinct scores
let dbQueue = DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
var player3 = Player(id: 3, name: "Craig", score: 150)
var player4 = Player(id: 4, name: "David", score: 120)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
try player3.insert(db)
try player4.insert(db)
}
// When we fetch players ordered by score
let players = try dbQueue.read(Player.all().orderedByScore().fetchAll)
// Then fetched players are ordered by score descending
XCTAssertEqual(players, [player2, player3, player4, player1])
}
func testOrderedByScoreSortsIdenticalScoresByName() throws {
// Given a players database that contains players with common scores
let dbQueue = DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
var player3 = Player(id: 3, name: "Craig", score: 200)
var player4 = Player(id: 4, name: "David", score: 200)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
try player3.insert(db)
try player4.insert(db)
}
// When we fetch players ordered by score
let players = try dbQueue.read(Player.all().orderedByScore().fetchAll)
// Then fetched players are ordered by score descending and by name
XCTAssertEqual(players, [player2, player3, player4, player1])
}
func testOrderedByName() throws {
// Given a players database that contains players with distinct names
let dbQueue = DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
var player3 = Player(id: 3, name: "Craig", score: 150)
var player4 = Player(id: 4, name: "David", score: 120)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
try player3.insert(db)
try player4.insert(db)
}
// When we fetch players ordered by name
let players = try dbQueue.read(Player.all().orderedByName().fetchAll)
// Then fetched players are ordered by name
XCTAssertEqual(players, [player1, player2, player3, player4])
}
}
@@ -5,6 +5,8 @@ Combine + SwiftUI Demo Application
**This demo application is a Combine + SwiftUI application, based on the MVVM design pattern.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md).
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
The topics covered in this demo are:
- How to setup a database in an iOS app.
@@ -15,13 +17,17 @@ The topics covered in this demo are:
**Files of interest:**
- [AppDelegate.swift](GRDBCombineDemo/AppDelegate.swift)
- [GRDBCombineDemoApp.swift](GRDBCombineDemo/GRDBCombineDemoApp.swift)
`AppDelegate` creates, on application startup, a unique instance of [DatabaseQueue](../../../README.md#database-queues) available for the whole application.
`GRDBCombineDemoApp` feeds the app views with a database.
- [AppDatabase.swift](GRDBCombineDemo/AppDatabase.swift)
`AppDatabase` grants database access for the whole application. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
- [Persistence.swift](GRDBCombineDemo/Persistence.swift)
This file instantiates various `AppDatabase` for the various projects needs: one database on disk for the application, and in-memory databases for SwiftUI previews.
- [Player.swift](GRDBCombineDemo/Player.swift)
@@ -31,6 +37,12 @@ The topics covered in this demo are:
`PlayerList` is the SwiftUI view that displays the list of players, fed by `PlayerListViewModel`.
- [PlayerForm.swift](GRDBCombineDemo/Views/PlayerForm.swift), [PlayerEditor.swift](GRDBCombineDemo/Views/PlayerEditor.swift), [PlayerCreationSheet.swift](GRDBCombineDemo/Views/PlayerCreationSheet.swift) and [PlayerFormViewModel.swift](GRDBCombineDemo/ViewModels/PlayerFormViewModel.swift).
- [PlayerForm.swift](GRDBCombineDemo/Views/PlayerForm.swift), [PlayerEditionView.swift](GRDBCombineDemo/Views/PlayerEditionView.swift), [PlayerCreationSheet.swift](GRDBCombineDemo/Views/PlayerCreationSheet.swift) and [PlayerFormViewModel.swift](GRDBCombineDemo/ViewModels/PlayerFormViewModel.swift).
`PlayerForm` is the SwiftUI view that displays a Player edition form. It is embedded in `PlayerEditor` and `PlayerCreationSheet`, two SwiftUI views that edit or create a player. All those views are fed by `PlayerFormViewModel`.
`PlayerForm` is the SwiftUI view that displays a Player editing form. It is embedded in `PlayerEditionView` and `PlayerCreationSheet`, two SwiftUI views that edit or create a player. All those views are fed by `PlayerFormViewModel`.
- [GRDBCombineDemoTests](GRDBCombineDemoTests)
- Test the database schema
- Test the `Player` record and its requests
- Test the `AppDatabase` methods that let the app access the database.
@@ -25,7 +25,7 @@
<key>NSExtensionAttributes</key>
<dict>
<key>WKAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS2.watchkitapp</string>
<string>com.github.groue.GRDBDemoiOS.watchkitapp</string>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.watchkit</string>
@@ -26,7 +26,7 @@
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>WKCompanionAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS2</string>
<string>com.github.groue.GRDBDemoiOS</string>
<key>WKWatchKitApp</key>
<true/>
</dict>
@@ -7,6 +7,9 @@
objects = {
/* Begin PBXBuildFile section */
56185BBF25B8036100B9C30F /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185BBE25B8036100B9C30F /* Persistence.swift */; };
56185BF325B80B8900B9C30F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */; };
56185C0725B80CEC00B9C30F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185C0625B80CEC00B9C30F /* PlayerTests.swift */; };
56606D202355938A00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; };
56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
56606D24235593AB00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; };
@@ -26,11 +29,17 @@
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; };
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; };
56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */; };
56FE6F1E24A90CC500711EDF /* World.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FE6F1D24A90CC500711EDF /* World.swift */; };
56FE6F2624A90CE400711EDF /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FE6F2524A90CE400711EDF /* SceneDelegate.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
56185BF525B80B8900B9C30F /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 56B036021E8D9EBE003B6DA4;
remoteInfo = GRDBDemoiOS;
};
56606D092355931F00185962 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
@@ -165,6 +174,11 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
56185BBE25B8036100B9C30F /* Persistence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = "<group>"; };
56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBDemoiOSTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = "<group>"; };
56185BF425B80B8900B9C30F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
56185C0625B80CEC00B9C30F /* PlayerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = "<group>"; };
568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoWatchOS.app; sourceTree = BUILT_PRODUCTS_DIR; };
568E5FC21E926430002582E0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Interface.storyboard; sourceTree = "<group>"; };
568E5FC41E926430002582E0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
@@ -185,11 +199,17 @@
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = "<group>"; };
56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewController.swift; sourceTree = "<group>"; };
56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
56FE6F1D24A90CC500711EDF /* World.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = World.swift; sourceTree = "<group>"; };
56FE6F2524A90CE400711EDF /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
56185BED25B80B8900B9C30F /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
568E5FC81E926430002582E0 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
@@ -209,6 +229,16 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
56185BF125B80B8900B9C30F /* GRDBDemoiOSTests */ = {
isa = PBXGroup;
children = (
56185BF425B80B8900B9C30F /* Info.plist */,
56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */,
56185C0625B80CEC00B9C30F /* PlayerTests.swift */,
);
path = GRDBDemoiOSTests;
sourceTree = "<group>";
};
56606CFD2355931F00185962 /* Products */ = {
isa = PBXGroup;
children = (
@@ -259,6 +289,7 @@
56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */,
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */,
568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */,
56185BF125B80B8900B9C30F /* GRDBDemoiOSTests */,
56B036041E8D9EBE003B6DA4 /* Products */,
56606D1F2355938A00185962 /* Frameworks */,
);
@@ -270,6 +301,7 @@
56B036031E8D9EBE003B6DA4 /* GRDBDemoiOS.app */,
568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */,
568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */,
56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */,
);
name = Products;
sourceTree = "<group>";
@@ -277,14 +309,14 @@
56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */ = {
isa = PBXGroup;
children = (
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
56FE6F2524A90CE400711EDF /* SceneDelegate.swift */,
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
56185BBE25B8036100B9C30F /* Persistence.swift */,
56B0361A1E8D9F38003B6DA4 /* Player.swift */,
56FE6F1D24A90CC500711EDF /* World.swift */,
56FE6F4F24A9114200711EDF /* ViewControllers */,
56FE6F2524A90CE400711EDF /* SceneDelegate.swift */,
56FE6F4E24A9112900711EDF /* Resources */,
56FE6F5124A9118000711EDF /* Support */,
56FE6F4F24A9114200711EDF /* ViewControllers */,
);
path = GRDBDemoiOS;
sourceTree = "<group>";
@@ -319,6 +351,24 @@
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
56185BEF25B80B8900B9C30F /* GRDBDemoiOSTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 56185BFF25B80B8900B9C30F /* Build configuration list for PBXNativeTarget "GRDBDemoiOSTests" */;
buildPhases = (
56185BEC25B80B8900B9C30F /* Sources */,
56185BED25B80B8900B9C30F /* Frameworks */,
56185BEE25B80B8900B9C30F /* Resources */,
);
buildRules = (
);
dependencies = (
56185BF625B80B8900B9C30F /* PBXTargetDependency */,
);
name = GRDBDemoiOSTests;
productName = GRDBDemoiOSTests;
productReference = 56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = 568E5FDE1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS" */;
@@ -382,10 +432,16 @@
56B035FB1E8D9EBE003B6DA4 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0830;
LastSwiftUpdateCheck = 1230;
LastUpgradeCheck = 1200;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
56185BEF25B80B8900B9C30F = {
CreatedOnToolsVersion = 12.3;
DevelopmentTeam = AMD8W895CT;
ProvisioningStyle = Automatic;
TestTargetID = 56B036021E8D9EBE003B6DA4;
};
568E5FBE1E926430002582E0 = {
CreatedOnToolsVersion = 8.3;
DevelopmentTeam = AMD8W895CT;
@@ -427,6 +483,7 @@
56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */,
568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */,
568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */,
56185BEF25B80B8900B9C30F /* GRDBDemoiOSTests */,
);
};
/* End PBXProject section */
@@ -491,6 +548,13 @@
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
56185BEE25B80B8900B9C30F /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
568E5FBD1E926430002582E0 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
@@ -521,6 +585,15 @@
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
56185BEC25B80B8900B9C30F /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
56185C0725B80CEC00B9C30F /* PlayerTests.swift in Sources */,
56185BF325B80B8900B9C30F /* AppDatabaseTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
568E5FC71E926430002582E0 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
@@ -534,10 +607,10 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
56FE6F1E24A90CC500711EDF /* World.swift in Sources */,
56FE6F2624A90CE400711EDF /* SceneDelegate.swift in Sources */,
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */,
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */,
56185BBF25B8036100B9C30F /* Persistence.swift in Sources */,
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */,
56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */,
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */,
@@ -547,6 +620,11 @@
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
56185BF625B80B8900B9C30F /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */;
targetProxy = 56185BF525B80B8900B9C30F /* PBXContainerItemProxy */;
};
56606D1E2355937900185962 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBiOS;
@@ -597,6 +675,51 @@
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
56185BF725B80B8900B9C30F /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = AMD8W895CT;
GCC_C_LANGUAGE_STANDARD = gnu11;
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOSTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemoiOS.app/GRDBDemoiOS";
};
name = Debug;
};
56185BF825B80B8900B9C30F /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = AMD8W895CT;
GCC_C_LANGUAGE_STANDARD = gnu11;
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOSTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemoiOS.app/GRDBDemoiOS";
};
name = Release;
};
568E5FDB1E926430002582E0 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
@@ -605,7 +728,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -621,7 +744,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -638,7 +761,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -655,7 +778,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -789,7 +912,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
@@ -803,7 +926,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
@@ -811,6 +934,15 @@
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
56185BFF25B80B8900B9C30F /* Build configuration list for PBXNativeTarget "GRDBDemoiOSTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
56185BF725B80B8900B9C30F /* Debug */,
56185BF825B80B8900B9C30F /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
568E5FDA1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS Extension" */ = {
isa = XCConfigurationList;
buildConfigurations = (
@@ -1,4 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
@@ -56,6 +56,16 @@
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56185BEF25B80B8900B9C30F"
BuildableName = "GRDBDemoiOSTests.xctest"
BlueprintName = "GRDBDemoiOSTests"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
@@ -68,10 +78,8 @@
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<RemoteRunnable
runnableDebuggingMode = "2"
BundleIdentifier = "com.apple.Carousel"
RemotePath = "/GRDBDemoiOS">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
@@ -79,7 +87,7 @@
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</RemoteRunnable>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -87,10 +95,8 @@
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<RemoteRunnable
runnableDebuggingMode = "2"
BundleIdentifier = "com.apple.Carousel"
RemotePath = "/GRDBDemoiOS">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
@@ -98,16 +104,7 @@
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</RemoteRunnable>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
BuildableName = "GRDBDemoWatchOS.app"
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1200"
LastUpgradeVersion = "1230"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -28,10 +28,20 @@
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56185BEF25B80B8900B9C30F"
BuildableName = "GRDBDemoiOSTests.xctest"
BlueprintName = "GRDBDemoiOSTests"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Release"
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
@@ -5,14 +5,20 @@ import GRDB
/// It applies the pratices recommended at
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
final class AppDatabase {
private let dbQueue: DatabaseQueue
/// Creates an AppDatabase and make sure the database schema is ready.
init(_ dbQueue: DatabaseQueue) throws {
self.dbQueue = dbQueue
try migrator.migrate(dbQueue)
/// Creates an `AppDatabase`, and make sure the database schema is ready.
init(_ dbWriter: DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
}
/// Provides access to the database.
///
/// Application can use a `DatabasePool`, and tests can use a fast
/// in-memory `DatabaseQueue`.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
private let dbWriter: DatabaseWriter
/// The DatabaseMigrator that defines the database schema.
///
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
@@ -31,9 +37,6 @@ final class AppDatabase {
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// Sort player names in a localized case insensitive fashion by default
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
.collate(.localizedCaseInsensitiveCompare)
t.column("score", .integer).notNull()
}
}
@@ -47,39 +50,36 @@ final class AppDatabase {
}
}
// MARK: - Database Access
//
// This extension defines methods that fulfill application needs, both in terms
// of writes and reads.
// MARK: - Database Access: Writes
extension AppDatabase {
// MARK: Writes
/// Save (insert or update) a player.
/// Saves (inserts or updates) a player. When the method returns, the
/// player is present in the database, and its id is not nil.
func savePlayer(_ player: inout Player) throws {
try dbQueue.write { db in
try dbWriter.write { db in
try player.save(db)
}
}
/// Delete the specified players
func deletePlayers(ids: [Int64]) throws {
try dbQueue.write { db in
try dbWriter.write { db in
_ = try Player.deleteAll(db, keys: ids)
}
}
/// Delete all players
func deleteAllPlayers() throws {
try dbQueue.write { db in
try dbWriter.write { db in
_ = try Player.deleteAll(db)
}
}
/// Refresh all players (by performing some random changes, for demo purpose).
func refreshPlayers() throws {
try dbQueue.write { db in
try dbWriter.write { db in
if try Player.fetchCount(db) == 0 {
// Insert new random players
// When database is empty, insert new random players
try createRandomPlayers(db)
} else {
// Insert a player
@@ -87,10 +87,12 @@ extension AppDatabase {
var player = Player.newRandom()
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() {
try player.updateChanges(db) {
@@ -103,7 +105,7 @@ extension AppDatabase {
/// Create random players if the database is empty.
func createRandomPlayersIfEmpty() throws {
try dbQueue.write { db in
try dbWriter.write { db in
if try Player.fetchCount(db) == 0 {
try createRandomPlayers(db)
}
@@ -117,33 +119,21 @@ extension AppDatabase {
try player.insert(db)
}
}
// MARK: Reads
/// Tracks changes in the number of players
func observePlayerCount(
onError: @escaping (Error) -> Void,
onChange: @escaping (Int) -> Void)
-> DatabaseCancellable
{
ValueObservation
.tracking(Player.fetchCount)
.start(
in: dbQueue,
onError: onError,
onChange: onChange)
}
}
// MARK: - Database Access: Reads
extension AppDatabase {
/// Tracks changes in players ordered by name
func observePlayersOrderedByName(
onError: @escaping (Error) -> Void,
onChange: @escaping ([Player]) -> Void)
-> DatabaseCancellable
-> DatabaseCancellable
{
ValueObservation
.tracking(Player.all().orderedByName().fetchAll)
.start(
in: dbQueue,
in: dbWriter,
onError: onError,
onChange: onChange)
}
@@ -152,24 +142,13 @@ extension AppDatabase {
func observePlayersOrderedByScore(
onError: @escaping (Error) -> Void,
onChange: @escaping ([Player]) -> Void)
-> DatabaseCancellable
-> DatabaseCancellable
{
ValueObservation
.tracking(Player.all().orderedByScore().fetchAll)
.start(
in: dbQueue,
in: dbWriter,
onError: onError,
onChange: onChange)
}
}
// MARK: - Support for Tests
#if DEBUG
extension AppDatabase {
/// Returns an empty, in-memory database, suitable for testing.
static func empty() throws -> AppDatabase {
try AppDatabase(DatabaseQueue())
}
}
#endif
@@ -1,11 +1,8 @@
import UIKit
import GRDB
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Setup database. Error handling left as an exercise for the reader.
try! setupDatabase()
return true
}
@@ -22,24 +19,4 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Database Setup
private func setupDatabase() throws {
// AppDelegate chooses the location of the database file.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let databaseURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
let dbQueue = try DatabaseQueue(path: databaseURL.path)
// Create the shared application database
let database = try AppDatabase(dbQueue)
// Populate the database if it is empty, for better demo purpose.
try database.createRandomPlayersIfEmpty()
// Expose it to the rest of the application
Current.database = { database }
}
}
@@ -0,0 +1,43 @@
import GRDB
extension AppDatabase {
/// The database for the application
static let shared = makeShared()
private static func makeShared() -> AppDatabase {
do {
// Create a folder for storing the SQLite database, as well as
// the various temporary files created during normal database
// operations (https://sqlite.org/tempfiles.html).
let fileManager = FileManager()
let folderURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
// Connect to a database on disk
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
// Populate the database if it is empty, for better demo purpose.
try appDatabase.createRandomPlayersIfEmpty()
return appDatabase
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate.
//
// Typical reasons for an error here include:
// * The parent directory cannot be created, or disallows writing.
// * The database is not accessible, due to permissions or data protection when the device is locked.
// * The device is out of space.
// * The database could not be migrated to its latest schema version.
// Check the error message to determine what the actual problem was.
fatalError("Unresolved error \(error)")
}
}
}
@@ -70,25 +70,35 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
extension DerivableRequest where RowDecoder == Player {
/// A request of players ordered by name
/// A request of players ordered by name.
///
/// For example:
///
/// let players = try dbQueue.read { db in
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByName().fetchAll(db)
/// }
func orderedByName() -> Self {
order(Player.Columns.name)
// Sort by name in a localized case insensitive fashion
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
/// A request of players ordered by score
/// A request of players ordered by score.
///
/// For example:
///
/// let players = try dbQueue.read { db in
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchAll(db)
/// }
/// let bestPlayer: Player? = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchOne(db)
/// }
func orderedByScore() -> Self {
order(Player.Columns.score.desc, Player.Columns.name)
// Sort by descending score, and then by name, in a
// localized case insensitive fashion
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
order(
Player.Columns.score.desc,
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
}
@@ -127,7 +127,7 @@ extension PlayerEditionViewController: UITextFieldDelegate {
}
player.name = nameTextField.text ?? ""
player.score = scoreTextField.text.flatMap { Int($0) } ?? 0
try! Current.database().savePlayer(&player)
try! AppDatabase.shared.savePlayer(&player)
self.player = player
}
}
@@ -9,14 +9,13 @@ class PlayerListViewController: UITableViewController {
}
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
private var dataSource: PlayerDataSource!
private var animatesPlayersChange = false // Don't animate first update
private var players: [Player] = []
private var playersCancellable: DatabaseCancellable?
private var playerCountCancellable: DatabaseCancellable?
private var playerOrdering: PlayerOrdering = .byScore {
didSet {
configureOrderingBarButtonItem()
configureTableView()
observePlayers()
}
}
@@ -24,7 +23,8 @@ class PlayerListViewController: UITableViewController {
super.viewDidLoad()
configureToolbar()
configureNavigationItem()
configureTableView()
configureDataSource()
observePlayers()
}
override func viewWillAppear(_ animated: Bool) {
@@ -48,7 +48,6 @@ class PlayerListViewController: UITableViewController {
target: nil, action: nil)
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
configureOrderingBarButtonItem()
configureTitle()
}
private func configureOrderingBarButtonItem() {
@@ -66,77 +65,65 @@ class PlayerListViewController: UITableViewController {
}
}
private func configureTitle() {
playerCountCancellable = Current.database().observePlayerCount(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] count in
guard let self = self else { return }
switch count {
case 0: self.navigationItem.title = "No Player"
case 1: self.navigationItem.title = "1 Player"
default: self.navigationItem.title = "\(count) Players"
}
})
private func configureDataSource() {
dataSource = PlayerDataSource(tableView: tableView) { (tableView, indexPath, player) in
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
if player.name.isEmpty {
cell.textLabel?.text = "(anonymous)"
} else {
cell.textLabel?.text = player.name
}
cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point"
return cell
}
dataSource.defaultRowAnimation = .fade
tableView.dataSource = dataSource
}
private func configureTableView() {
switch playerOrdering {
case .byName:
playersCancellable = Current.database().observePlayersOrderedByName(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(with: players)
})
case .byScore:
playersCancellable = Current.database().observePlayersOrderedByScore(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(with: players)
})
private func configureTitle(from players: [Player]) {
switch players.count {
case 0:
navigationItem.title = "No Player"
case 1:
navigationItem.title = "1 Player"
case let count:
navigationItem.title = "\(count) Players"
}
}
private func updateTableView(with players: [Player]) {
if animatesPlayersChange == false {
self.players = players
tableView.reloadData()
private func configureDataSource(from players: [Player]) {
var snapshot = NSDiffableDataSourceSnapshot<Int, Player>()
snapshot.appendSections([0])
snapshot.appendItems(players, toSection: 0)
if animatesPlayersChange {
dataSource.apply(snapshot, animatingDifferences: true, completion: nil)
} else {
// Future updates will be animated
animatesPlayersChange = true
return
dataSource.apply(snapshot, animatingDifferences: false, completion: nil)
}
}
private func observePlayers() {
switch playerOrdering {
case .byName:
playersCancellable = AppDatabase.shared.observePlayersOrderedByName(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.configureTitle(from: players)
self.configureDataSource(from: players)
})
case .byScore:
playersCancellable = AppDatabase.shared.observePlayersOrderedByScore(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.configureTitle(from: players)
self.configureDataSource(from: players)
})
}
// Compute difference between current and new list of players
let difference = players
.difference(from: self.players)
.inferringMoves()
// Apply those changes to the table view
tableView.performBatchUpdates({
self.players = players
for change in difference {
switch change {
case let .remove(offset, _, associatedWith):
if let associatedWith = associatedWith {
self.tableView.moveRow(
at: IndexPath(row: offset, section: 0),
to: IndexPath(row: associatedWith, section: 0))
} else {
self.tableView.deleteRows(
at: [IndexPath(row: offset, section: 0)],
with: .fade)
}
case let .insert(offset, _, associatedWith):
if associatedWith == nil {
self.tableView.insertRows(
at: [IndexPath(row: offset, section: 0)],
with: .fade)
}
}
}
}, completion: nil)
}
}
@@ -147,20 +134,18 @@ extension PlayerListViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Edit" {
guard
let controller = segue.destination as? PlayerEditionViewController,
let indexPath = tableView.indexPathForSelectedRow
else { return }
let player = players[indexPath.row]
guard let controller = segue.destination as? PlayerEditionViewController,
let indexPath = tableView.indexPathForSelectedRow,
let player = dataSource.itemIdentifier(for: indexPath)
else { return }
controller.title = player.name
controller.player = player
controller.presentation = .push
}
else if segue.identifier == "New" {
guard
let navigationController = segue.destination as? UINavigationController,
let controller = navigationController.viewControllers.first as? PlayerEditionViewController
else { return }
guard let navigationController = segue.destination as? UINavigationController,
let controller = navigationController.viewControllers.first as? PlayerEditionViewController
else { return }
setEditing(false, animated: true)
controller.title = "New Player"
controller.player = Player(id: nil, name: "", score: 0)
@@ -180,33 +165,18 @@ extension PlayerListViewController {
// MARK: - UITableViewDataSource
extension PlayerListViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
players.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
configure(cell, at: indexPath)
return cell
/// Subclass of UITableViewDiffableDataSource that supports row deletion
private class PlayerDataSource: UITableViewDiffableDataSource<Int, Player> {
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
// Delete the player
if let id = players[indexPath.row].id {
try! Current.database().deletePlayers(ids: [id])
if let player = itemIdentifier(for: indexPath), let id = player.id {
try! AppDatabase.shared.deletePlayers(ids: [id])
}
}
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
let player = players[indexPath.row]
if player.name.isEmpty {
cell.textLabel?.text = "(anonymous)"
} else {
cell.textLabel?.text = player.name
}
cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point"
}
}
@@ -225,19 +195,19 @@ extension PlayerListViewController {
@IBAction func deletePlayers() {
setEditing(false, animated: true)
try! Current.database().deleteAllPlayers()
try! AppDatabase.shared.deleteAllPlayers()
}
@IBAction func refresh() {
setEditing(false, animated: true)
try! Current.database().refreshPlayers()
try! AppDatabase.shared.refreshPlayers()
}
@IBAction func stressTest() {
setEditing(false, animated: true)
for _ in 0..<50 {
DispatchQueue.global().async {
try! Current.database().refreshPlayers()
try! AppDatabase.shared.refreshPlayers()
}
}
}
@@ -1,11 +0,0 @@
/// Dependency Injection based on the "How to Control the World" article:
/// https://www.pointfree.co/blog/posts/21-how-to-control-the-world
struct World {
/// The application database
var database: () -> AppDatabase
}
/// The current world.
///
/// Its setup is done by `AppDelegate`, or tests.
var Current = World(database: { fatalError("Database is uninitialized") })
@@ -0,0 +1,234 @@
import XCTest
import GRDB
@testable import GRDBDemoiOS
class AppDatabaseTests: XCTestCase {
func test_database_schema() throws {
// Given an empty database
let dbQueue = DatabaseQueue()
// When we instantiate an AppDatabase
_ = try AppDatabase(dbQueue)
// Then the player table exists, with id, name & score columns
try dbQueue.read { db in
try XCTAssert(db.tableExists("player"))
let columns = try db.columns(in: "player")
let columnNames = Set(columns.map { $0.name })
XCTAssertEqual(columnNames, ["id", "name", "score"])
}
}
func test_savePlayer_inserts() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we save a new player
var player = Player(id: nil, name: "Arthur", score: 100)
try appDatabase.savePlayer(&player)
// Then the player exists in the database
try XCTAssertTrue(dbQueue.read(player.exists))
}
func test_savePlayer_updates() throws {
// Given a players database that contains a player
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
try player.insert(db)
}
// When we modify and save the player
player.name = "Barbara"
player.score = 1000
try appDatabase.savePlayer(&player)
// Then the player has been updated in the database
let fetchedPlayer = try dbQueue.read { db in
try XCTUnwrap(Player.fetchOne(db, key: player.id))
}
XCTAssertEqual(fetchedPlayer, player)
}
func test_deletePlayers() throws {
// Given a players database that contains four players
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
var player3 = Player(id: nil, name: "Craig", score: 150)
var player4 = Player(id: nil, name: "David", score: 120)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
try player3.insert(db)
try player4.insert(db)
}
// When we delete two players
try appDatabase.deletePlayers(ids: [player1.id!, player3.id!])
// Then the deleted players no longer exist
try dbQueue.read { db in
try XCTAssertFalse(player1.exists(db))
try XCTAssertFalse(player3.exists(db))
}
// Then the database still contains two players
try XCTAssertEqual(dbQueue.read(Player.fetchCount), 2)
}
func test_deleteAllPlayers() throws {
// Given a players database that contains players
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
var player3 = Player(id: nil, name: "Craig", score: 150)
var player4 = Player(id: nil, name: "David", score: 120)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
try player3.insert(db)
try player4.insert(db)
}
// When we delete all players
try appDatabase.deleteAllPlayers()
// Then the database does not contain any player
try XCTAssertEqual(dbQueue.read(Player.fetchCount), 0)
}
func test_refreshPlayers_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we refresh players
try appDatabase.refreshPlayers()
// Then the database is not empty
try XCTAssert(dbQueue.read(Player.fetchCount) > 0)
}
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we create random players
try appDatabase.createRandomPlayersIfEmpty()
// Then the database is not empty
try XCTAssert(dbQueue.read(Player.fetchCount) > 0)
}
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
// Given a players database that contains one player
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
try player.insert(db)
}
// When we create random players
try appDatabase.createRandomPlayersIfEmpty()
// Then the database still only contains the original player
let players = try dbQueue.read(Player.fetchAll)
XCTAssertEqual(players, [player])
}
func test_observePlayerCount() throws {
// Given a players database that contains one player
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
try player.insert(db)
}
// When we observe the player count and wait for the first value
let exp = expectation(description: "Player count")
var count: Int?
let cancellable = appDatabase.observePlayerCount(
onError: { error in
XCTFail("Unexpected error \(error)")
},
onChange: {
count = $0
exp.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
// Then that first value is one
XCTAssertEqual(count, 1)
}
func test_observePlayersOrderedByName() throws {
// Given a players database that contains two players
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we observe players and wait for the first value
let exp = expectation(description: "Players")
var players: [Player]?
let cancellable = appDatabase.observePlayersOrderedByName(
onError: { error in
XCTFail("Unexpected error \(error)")
},
onChange: {
players = $0
exp.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
// Then the players are the two players ordered by name
XCTAssertEqual(players, [player1, player2])
}
func test_observePlayersOrderedByScore() throws {
// Given a players database that contains two players
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we observe players and wait for the first value
let exp = expectation(description: "Players")
var players: [Player]?
let cancellable = appDatabase.observePlayersOrderedByScore(
onError: { error in
XCTFail("Unexpected error \(error)")
},
onChange: {
players = $0
exp.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
// Then the players are the two players ordered by score descending
XCTAssertEqual(players, [player2, player1])
}
}
@@ -0,0 +1,22 @@
<?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>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
@@ -0,0 +1,108 @@
import XCTest
import GRDB
@testable import GRDBDemoiOS
class PlayerTests: XCTestCase {
// MARK: - CRUD
// Test that our Player type properly talks to GRDB.
func testInsert() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
_ = try AppDatabase(dbQueue)
// When we insert a player
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
try player.insert(db)
}
// Then the player gets a non-nil id
XCTAssertNotNil(player.id)
}
func testRoundtrip() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
_ = try AppDatabase(dbQueue)
// When we insert a player and fetch the player with the same id
var insertedPlayer = Player(id: nil, name: "Arthur", score: 100)
let fetchedPlayer: Player? = try dbQueue.write { db in
try insertedPlayer.insert(db)
return try Player.fetchOne(db, key: insertedPlayer.id)
}
// Then the fetched player is equal to the inserted player
XCTAssertEqual(insertedPlayer, fetchedPlayer)
}
// MARK: - Requests
// Test that requests defined on the Player type behave as expected.
func testOrderedByScore() throws {
// Given a players database that contains players with distinct scores
let dbQueue = DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
var player3 = Player(id: 3, name: "Craig", score: 150)
var player4 = Player(id: 4, name: "David", score: 120)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
try player3.insert(db)
try player4.insert(db)
}
// When we fetch players ordered by score
let players = try dbQueue.read(Player.all().orderedByScore().fetchAll)
// Then fetched players are ordered by score descending
XCTAssertEqual(players, [player2, player3, player4, player1])
}
func testOrderedByScoreSortsIdenticalScoresByName() throws {
// Given a players database that contains players with common scores
let dbQueue = DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
var player3 = Player(id: 3, name: "Craig", score: 200)
var player4 = Player(id: 4, name: "David", score: 200)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
try player3.insert(db)
try player4.insert(db)
}
// When we fetch players ordered by score
let players = try dbQueue.read(Player.all().orderedByScore().fetchAll)
// Then fetched players are ordered by score descending and by name
XCTAssertEqual(players, [player2, player3, player4, player1])
}
func testOrderedByName() throws {
// Given a players database that contains players with distinct names
let dbQueue = DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
var player3 = Player(id: 3, name: "Craig", score: 150)
var player4 = Player(id: 4, name: "David", score: 120)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
try player3.insert(db)
try player4.insert(db)
}
// When we fetch players ordered by name
let players = try dbQueue.read(Player.all().orderedByName().fetchAll)
// Then fetched players are ordered by name
XCTAssertEqual(players, [player1, player2, player3, player4])
}
}
+13 -5
View File
@@ -5,6 +5,8 @@ UIKit Demo Application
**This demo application is a storyboard-based UIKit application, based on the MVC design pattern.** For a demo application that uses Combine and SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md).
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
The topics covered in this demo are:
- How to setup a database in an iOS app.
@@ -14,13 +16,13 @@ The topics covered in this demo are:
**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` grants database access for the whole application. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
- [Persistence.swift](GRDBDemoiOS/Persistence.swift)
This file defines the `AppDatabase` instance used by the application.
- [Player.swift](GRDBDemoiOS/Player.swift)
@@ -33,3 +35,9 @@ The topics covered in this demo are:
- [PlayerEditionViewController.swift](GRDBDemoiOS/ViewControllers/PlayerEditionViewController.swift)
`PlayerEditionViewController` can create or edit a player, and save it in the database.
- [GRDBDemoiOSTests](GRDBDemoiOSTests)
- Test the database schema
- Test the `Player` record and its requests
- Test the `AppDatabase` methods that let the app access the database.
+5 -1
View File
@@ -66,7 +66,11 @@ Once you have a custom tokenizer type that adopts [FTS5CustomTokenizer](#fts5cus
```swift
class MyTokenizer : FTS5CustomTokenizer { ... }
dbQueue.add(tokenizer: MyTokenizer.self) // or dbPool.add
var config = Configuration()
config.prepareDatabase { db in
db.add(tokenizer: MyTokenizer.self)
}
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
```
**Create [full-text tables](../../../#create-fts5-virtual-tables) that use the custom tokenizer:**
+2 -2
View File
@@ -280,7 +280,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.8/Structs/StatementArguments.html):
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.3/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.8/Structs/StatementArguments.html):
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.3/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
+52 -16
View File
@@ -5,6 +5,7 @@ Migrating From GRDB 4 to GRDB 5
- [Preparing the Migration to GRDB 5](#preparing-the-migration-to-grdb-5)
- [New requirements](#new-requirements)
- [Database Configuration](#database-configuration)
- [ValueObservation](#valueobservation)
- [Combine Integration](#combine-integration)
- [Other Changes](#other-changes)
@@ -31,6 +32,35 @@ GRDB requirements have been bumped:
- watchOS 2.0+ (unchanged)
## Database Configuration
The way to configure a database relies much more on the `Configuration.prepareDatabase(_:)` method:
```swift
// BEFORE: GRDB 4
var config = Configuration()
config.trace = { ... } // Tracing SQL statements
config.prepareDatabase = { db in // prepareDatabase was a property
... // Custom setup
}
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
dbQueue.add(function: ...) // Custom SQL function
dbQueue.add(collation: ...) // Custom collation
dbQueue.add(tokenizer: ...) // Custom FTS5 tokenizer
// NEW: GRDB 5
var config = Configuration()
config.prepareDatabase { db in // prepareDatabase is now a method
db.trace { ... }
db.add(function: ...)
db.add(collation: ...)
db.add(tokenizer: ...)
...
}
let dbQueue = try DatabaseQueue(dbPath, configuration: config)
```
## ValueObservation
[ValueObservation] is the database observation tool that tracks changes in database values. It has quite changed in GRDB 5.
@@ -63,19 +93,6 @@ let observation = ValueObservation.tracking { db in
let observation = ValueObservation.tracking(Player.fetchAll)
```
If the tracked value is computed from several database requests that are not always the same, make sure you use the `trackingVaryingRegion` method, as below. See [Observing a Varying Database Region] for more information.
```swift
// An observation which does not always execute the same requests:
let observation = ValueObservation.trackingVaryingRegion { db -> Int in
let preference = try Preference.fetchOne(db) ?? .default
switch preference.selection {
case .food: return try Food.fetchCount(db)
case .beverage: return try Beverage.fetchCount(db)
}
}
```
Several methods that build observations were removed:
```swift
@@ -337,7 +354,7 @@ let publisher = observation
// NEW: GRDB 5
var config = Configuration()
config.prepareDatabase = { db in
config.prepareDatabase { db in
db.trace { print($0) }
}
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
@@ -457,15 +474,34 @@ let publisher = observation
11. `FetchedRecordsController` was removed from GRDB 5. The [Database Observation] chapter describes the other ways to observe the database.
12. Defining custom `RowAdapter` types is no longer supported.
12. Defining custom `RowAdapter` types is no longer supported. A new [RenameColumnAdapter](../README.md#renamecolumnadapter) adapter makes it possible to process column names.
13. Many types and methods that support the query builder used to be publicly exposed and flagged as experimental. They are now private, or renamed with an underscore prefix, which means they are not for public use.
14. Explicit boolean tests `expression == true` and `expression == false` generate different SQL:
```swift
// GRDB 4: SELECT * FROM player WHERE isActive
// GRDB 5: SELECT * FROM player WHERE isActive = 1
Player.filter(Column("isActive") == true)
// GRDB 4: SELECT * FROM player WHERE NOT isActive
// GRDB 5: SELECT * FROM player WHERE isActive = 0
Player.filter(Column("isActive") == false)
// GRDB 4 & 5: SELECT * FROM player WHERE isActive
Player.filter(Column("isActive"))
// GRDB 4 & 5: SELECT * FROM player WHERE NOT isActive
Player.filter(!Column("isActive"))
```
This change is innocuous for database boolean values that are `0`, `1`, or `NULL`. However, it is a breaking change for all other database values.
[ValueObservation]: ../README.md#valueobservation
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[Observing a Varying Database Region]: ../README.md#observing-a-varying-database-region
[removeDuplicates]: ../README.md#valueobservationremoveduplicates
[Custom SQL functions]: ../README.md#custom-sql-functions
[Batch updates]: ../README.md#update-requests
+1 -1
View File
@@ -68,7 +68,7 @@ try dbQueue.read { db in
}
```
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.8/Structs/DatabaseMigrator.html) for more migrator methods.
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.3/Structs/DatabaseMigrator.html) for more migrator methods.
## The `eraseDatabaseOnSchemaChange` Option
@@ -11,7 +11,7 @@ import GRDB
//: Open a database connection
var configuration = Configuration()
configuration.prepareDatabase = { db in
configuration.prepareDatabase { db in
db.trace { print("SQL> \($0)") }
}
let dbQueue = DatabaseQueue(configuration: configuration)
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='macos'>
<playground version='5.0' target-platform='macos' buildActiveScheme='true'>
<timeline fileName='timeline.xctimeline'/>
</playground>
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='macos' display-mode='rendered'>
<playground version='5.0' target-platform='macos' display-mode='rendered' buildActiveScheme='true'>
<timeline fileName='timeline.xctimeline'/>
</playground>
@@ -3,7 +3,7 @@
import GRDB
var configuration = Configuration()
configuration.prepareDatabase = { db in
configuration.prepareDatabase { db in
db.trace { print("SQL> \($0)") }
}
let dbQueue = DatabaseQueue(configuration: configuration)
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='macos'>
<playground version='5.0' target-platform='macos' buildActiveScheme='true'>
<timeline fileName='timeline.xctimeline'/>
</playground>
@@ -19,7 +19,7 @@ import CoreLocation
// Open an in-memory database that logs all SQL statements
var configuration = Configuration()
configuration.prepareDatabase = { db in
configuration.prepareDatabase { db in
db.trace { print("SQL> \($0)") }
}
let dbQueue = DatabaseQueue(configuration: configuration)
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='osx' display-mode='raw'>
<playground version='5.0' target-platform='osx' display-mode='raw' buildActiveScheme='true'>
<timeline fileName='timeline.xctimeline'/>
</playground>
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='osx' display-mode='rendered'>
<playground version='5.0' target-platform='osx' display-mode='rendered' buildActiveScheme='true'>
<timeline fileName='timeline.xctimeline'/>
</playground>
+1 -1
View File
@@ -11,7 +11,7 @@ To release a new GRDB version:
- Archive GRDBDemoiOS
- Check for performance regression with GRDBOSXPerformanceTests
- On https://github.com/groue/sqlcipher.git upgrade, update SQLCipher version in README.md
- On https://github.com/swiftlyfalling/SQLiteLib upgrade, update SQLite version in README.md and Documentation/CustomSQLiteBuilds.md
- On https://github.com/swiftlyfalling/SQLiteLib upgrade, update SQLite version in Documentation/CustomSQLiteBuilds.md
- Update GRDB version number and release date in:
- Makefile
- CHANGELOG.md
+19 -1
View File
@@ -417,9 +417,16 @@ This chapter lists all kinds of supported interpolations.
```swift
// SELECT * FROM player ORDER BY name DESC
"SELECT * FROM player WHERE id IN \(Column("name").desc)"
"SELECT * FROM player ORDER BY \(Column("name").desc)"
```
- Database Collations:
```swift
"SELECT * FROM player ORDER BY email COLLATING \(.nocase)"
"SELECT * FROM player ORDER BY email COLLATING \(.localizedCompare)"
```
- Subqueries:
```swift
@@ -432,6 +439,16 @@ This chapter lists all kinds of supported interpolations.
"SELECT * FROM player WHERE score = (\(subquery))"
```
- Definition and table name of [common table Expressions]:
```swift
// WITH name AS (SELECT 'O''Brien') SELECT * FROM name
let cte = CommonTableExpression<Void>(
named: "name",
literal: "SELECT \("O'Brien")")
"WITH \(definitionFor: cte) SELECT * FROM \(cte)"
```
- SQLLiteral:
```swift
@@ -472,3 +489,4 @@ This chapter lists all kinds of supported interpolations.
[query interface requests]: ../README.md#requests
[SE-0228 Fix ExpressibleByStringInterpolation]: https://github.com/apple/swift-evolution/blob/master/proposals/0228-fix-expressiblebystringinterpolation.md
[columns selected by the record]: ../README.md#columns-selected-by-a-request
[common table Expressions]: CommonTableExpressions.md
+4 -4
View File
@@ -50,7 +50,7 @@ Since several processes may open the database at the same time, protect the crea
private func openDatabase(at databaseURL: URL) throws -> DatabasePool {
var configuration = Configuration()
configuration.prepareDatabase = { db in
configuration.prepareDatabase { db in
// Activate the persistent WAL mode so that
// readonly processes can access the database.
//
@@ -179,7 +179,7 @@ See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for
```swift
var configuration = Configuration()
configuration.prepareDatabase = { (db: Database) in
configuration.prepareDatabase { (db: Database) in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA cipher_plaintext_header_size = 32")
}
@@ -188,7 +188,7 @@ See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for
This will avoid https://github.com/sqlcipher/sqlcipher/issues/255.
2. [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features) In each process that wants to write in the database:
2. [**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features) In each process that wants to write in the database:
Set the `observesSuspensionNotifications` configuration flag:
@@ -236,7 +236,7 @@ See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for
}
```
Suspended databases greatly reduce the odds of `0xDEAD10CC` exception are greatly reduced. If you see one in your crash logs, please open an issue!
Suspended databases greatly reduce the odds of `0xDEAD10CC` exception occurring. If you see one in your crash logs, please open an issue!
In exchange, you will get `SQLITE_INTERRUPT` (9) or `SQLITE_ABORT` (4) errors, with messages "Database is suspended", "Transaction was aborted", or "interrupted", for any attempt at writing in the database when it is suspended.
+956
View File
@@ -0,0 +1,956 @@
Tutorial: Building a Database Access Layer
==========================================
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png" width="50%">
**This tutorial builds and explains a database access layer for a UIKit or SwiftUI application**. See the [demo applications] for sample code.
The target audience has basic database knowledge, and knows what tables and columns are. The tutorial visits high-level GRDB features: record types, query interface, database observation. Raw SQL is also provided, so that you can choose your favorite way to use SQLite.
The setup of Xcode projects, view controllers, or SwiftUI is not discussed. Refer to the demo apps for sample code.
When you want an explanation about some particular recommendation or piece of code, expand the design notes marked with an ℹ️.
As you can see in the [screenshot], the demo application displays the list of players stored in the database. The application user can sort players by name or by score. She can add, edit, and delete players. The list of players can be "refreshed". For demo purpose, refreshing players performs random modifications to the players. The tornado icon exercices multi-threading robustness by spawning many concurrent refreshes.
Let's start!
- [The Database Service]
- [The Shared Application Database]
- [The Database Schema]
- [The Player Struct]
- [Saving Players]
- [Deleting Players]
- [Fetching Players]
- [Refreshing Players]
- [Sorting Players]
- [Observing Players]
- [The Initial Application State]
- [Testing the Database]
## The Database Service
The database service (or database manager, or persistence layer) is a class named `AppDatabase` that grants access to the SQLite database of players. It fetches the list of players, inserts new players, etc.
`AppDatabase` accesses the database through a GRDB [database connection]. In the application, the service uses a `DatabasePool` connection that leverages the advantages of the SQLite [WAL mode]. Tests use a service that connects to an in-memory database, with `DatabaseQueue`, so that they can run as fast as possible. SwiftUI previews also run with in-memory databases.
Database pools and queues share a common protocol: `DatabaseWriter`. This is what the `AppDatabase` service needs, in order to support both:
```swift
// File: AppDatabase.swift
import GRDB
final class AppDatabase {
/// Creates an `AppDatabase`.
init(_ dbWriter: DatabaseWriter) throws {
self.dbWriter = dbWriter
}
/// Provides access to the database.
private let dbWriter: DatabaseWriter
}
```
<details>
<summary>ℹ️ Design Notes</summary>
> :point_right: The `dbWriter` property is private: this allows `AppDatabase` to restrict the operations that can be performed on the database.
>
> :point_right: The initializer is not private: we can freely create `AppDatabase` instances, for the application, and for tests.
>
> :point_right: The initializer is declared with the `throws` qualifier, because it will be extended, below in this guide, in order to prepare the database for application use.
</details>
> ✅ At this stage, we have an `AppDatabase` class which encapsulates access to the database. It supports both WAL databases, and in-memory databases, so that it can feed the application, tests, and SwiftUI previews.
## The Shared Application Database
Our app uses a single database file, so we want a "shared" database: `AppDatabase.shared`.
The shared `AppDatabase` instance opens a file named "db.sqlite" stored in a "database" folder. The database is created if the file does not already exist:
```swift
// File: Persistence.swift
import GRDB
extension AppDatabase {
/// The database for the application
static let shared = makeShared()
private static func makeShared() -> AppDatabase {
do {
// Create a folder for storing the SQLite database
let fileManager = FileManager()
let folderURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
// Connect to a database on disk
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
return appDatabase
} catch {
fatalError("Unresolved error \(error)")
}
}
}
```
The [Combine + SwiftUI Demo Application] defines more instances of `AppDatabase`, such as en empty players database suitable for some SwiftUI previews:
```swift
// File: Persistence.swift
extension AppDatabase {
/// Creates an empty database for SwiftUI previews
static func empty() -> AppDatabase {
// Connect to an in-memory database
let dbQueue = DatabaseQueue()
return try! AppDatabase(dbQueue)
}
}
```
<details>
<summary>ℹ️ Design Notes</summary>
> :point_right: Some applications will prefer to manage the shared `AppDatabase` instance differently, for example with some dependency injection technique. In this case, you will not define `AppDatabase.shared`.
>
> Just make sure that there exists a single instance of `DatabaseQueue` or `DatabasePool` for any given database file. This is because multiple instances would compete for database access, and sometimes throw errors. Get inspiration from `AppDatabase.makeShared()`, above, in order to create the single instance of database service used by the application.
>
> :point_right: The database is stored in its own directory, so that you can easily:
>
> - Set up [data protection].
> - Remove the database as well as its companion [temporary files](https://sqlite.org/tempfiles.html) from disk in a single stroke.
>
> :point_right: `AppDatabase.shared` is created from a `DatabasePool` in order to profit from the SQLite [WAL mode].
>
> :point_right: Any error which prevents the application from opening the database has the application crash. You will have to adapt this sample code if you intend to build an app that is able to run without a working database. For example, you could modify `AppDatabase` so that it feeds from a `Result<DatabaseWriter, Error>` instead of a plain `DatabaseWriter` - but your mileage may vary. This sample code has the error bubble up in crash reports, which is arguably better than displaying a blank screen without any error reporting.
</details>
> ✅ At this stage, we have an `AppDatabase.shared` object which vends an empty database. We'll add methods and properties to `AppDatabase`, as we discover the needs of our application.
## The Database Schema
Now that we have an empty database, let's define its schema: the database table(s) that will store our application data. A good database schema will have SQLite manage the database integrity for you, and make sure it is impossible to store invalid data in the database: this is an important step!
Our database has one table, `player`, where each row contains the attributes of a player: a unique identifier (aka *primary key*), a name, and a score. The identifier makes it possible to instruct the database to perform operations on a specific player. We'll make sure all players have a name and a score (we'll prevent *NULL* values from entering those columns).
In order to define the schema and create the `player` table, it is recommended to use [migrations]. All applications around us evolve as time passes, and ship several versions: it is likely our app will do the same. The database schema evolves as well, as we add features and fix bugs in our app. That's exactly what migrations are for: they represent the building steps of our database schema, as our app goes through its versions.
The migrations are defined in the `AppDatabase.migrator` property, in which we register the *initial migration*:
```swift
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
migrator.registerMigration("initial") { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("score", .integer).notNull()
}
}
// Migrations for future application versions will be inserted here:
// migrator.registerMigration(...) { db in
// ...
// }
return migrator
}
```
<details>
<summary>Raw SQL version</summary>
> Some readers like to write SQL. Please be welcome:
>
> ```swift
> private var migrator: DatabaseMigrator {
> var migrator = DatabaseMigrator()
>
> migrator.registerMigration("initial") { db in
> try db.execute(sql: """
> CREATE TABLE player (
> id INTEGER PRIMARY KEY AUTOINCREMENT,
> name TEXT NOT NULL,
> score INTEGER NOT NULL
> )
> """)
> }
>
> return migrator
> }
> ```
</details>
The migrations are now defined, but they are not applied yet. Let's modify the `AppDatabase` initializer, and *migrate* the database. It means that unapplied migrations are run. In the end, we are sure that the database schema is exactly what we want it to be:
```swift
/// Creates an `AppDatabase` from a database connection,
/// and make sure the database schema is ready.
init(_ dbWriter: DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
}
```
<details>
<summary>ℹ️ Design Notes</summary>
> :point_right: GRDB is a library that fosters robust database schemas, defined right at the SQLite level, because you can't build a safer haven for your precious users' data. There is no such thing as "automatic schema definition" or "automatic migrations" based on annotated Swift models. See [Trust SQLite More Than Yourself] for a longer explanation of this policy.
>
> :point_right: The database table for players is named `player`, because GRDB recommends that table names are English, singular, and camel-cased (`player`, `country`, `postalAddress`, etc.) Such names will help you using [Associations] when you need them. Database table names that follow another naming convention are totally OK, but you will have to perform extra configuration.
>
> :point_right: The primary key for players is an auto-incremented column named `id`. It also could have been a UUID column named `uuid`. GRDB generally accepts all primary keys, even if they are not named `id`, even if they span several columns, without any extra setup. Yet `id` is a frequent convention.
>
> :point_right: The `id` column is [autoincremented](https://sqlite.org/autoinc.html), in order to avoid id reuse. Reused ids can trip up [database observation] tools: a deletion followed by an insertion with the same id could be interpreted as an update, with unintended consequences.
</details>
> ✅ At this stage, we have an `AppDatabase.shared` object which vends a database that contains a `player` table.
## The Player Struct
The application will insert, edit, display, and delete players. Let's *model* a player with a dedicated type:
```swift
// File: Player.swift
/// A Player
struct Player {
var id: Int64?
var name: String
var score: Int
}
```
With its `name` and `score` properties, it can feed our application screens. With its `id` property, it can talk to `AppDatabase`, whenever we need to perform operations of a particular player (such as saving changes performed on a player).
The type of `id` is `Int64?`, because it matches the `id` column in the `player` table (SQLite integer primary keys are 64-bit integers, even on 32-bit platforms). When the id is nil, the player is not yet saved in the database. When the id is not nil, it is the identifier of a player in the database.
The `name` and `score` properties are regular `String` and `Int`. They are not optional because the `player` table was created with "not null" constraints on those database columns: we do not want to insert nil names, and we are sure we won't fetch nil names either.
> ✅ Now we have a `Player` type that fits the columns of the `player` database table, and is able to deal with all application needs. This is what GRDB calls a [record type]. At this stage, `Player` has no database power yet.
## Saving Players
The user application inserts player by tapping the "+" button on the top left of the [screen], which displays a form. The user fills the name and score fields, and hits the "Done" button.
The same form screen is pushed when the user taps a player in the list. The app then updates the player when the user hits the back button.
The `AppDatabase` service supports both these use cases by providing a `savePlayer(_:)` method.
We can write it with raw SQL:
<details>
<summary>Raw SQL version</summary>
> ```swift
> // File: AppDatabase.swift
>
> extension AppDatabase {
> /// Saves (inserts or updates) a player. When the method returns, the
> /// player is present in the database, and its id is not nil.
> func savePlayer(_ player: inout Player) throws {
> try dbWriter.write { db in
> try save(db, player: &player)
> }
> }
>
> /// Saves (inserts or updates) a player. When the method returns, the
> /// player is present in the database, and its id is not nil.
> private func save(_ db: Database, player: inout Player) throws {
> if let id = player.id {
> // Player has an id: update
> try db.execute(literal: """
> UPDATE player
> SET name = \(player.name),
> score = \(player.score)
> WHERE id = \(id)
> """)
>
> if db.changesCount == 0 {
> // Player was not updated. This means that is was not
> // present in the database. So let's insert it with its id.
> try db.execute(literal: """
> INSERT INTO player (id, name, score)
> VALUES (\(player.id), \(player.name), \(player.score))
> """)
> }
> } else {
> // Player has no id: insert
> try db.execute(literal: """
> INSERT INTO player (name, score)
> VALUES (\(player.name), \(player.score))
> """)
> player.id = db.lastInsertedRowID
> }
> }
> }
> ```
>
> The `savePlayer(_:)` method calls a private helper method `save(_:player:)`. This helper method will be reused later in the tutorial.
>
> Note that the helper method uses the `execute(literal:)` method, which avoids [SQL injection], thanks to [SQL Interpolation].
</details>
SQL is just fine, but we can also make `Player` a [persistable record], so that you do not have to write the SQL queries that perform common persistence operations.
In our specific case, the `Player` struct adopts the `MutablePersistableRecord` protocol, because the `player` database table has an autoincremented id:
- "Persistable": players can be inserted, updated and deleted.
- "Mutable": a player is modified (mutated) upon insertion, because its `id` property is set from the autoincremented SQLite id.
Conformance to `MutablePersistableRecord` is easy for types that adopt the standard [Encodable] protocol:
```swift
// File: Player.swift
// Give Player database powers
extension Player: Encodable, MutablePersistableRecord {
/// Updates a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
```
In this tutorial, the name of the database table matches the name of the type, and so do columns and properties: we do not have to configure anything.
<details>
<summary>Avoiding Encodable</summary>
The `Encodable` protocol is handy, but you may prefer not to use it. In this case, you have to fulfill the `MutablePersistableRecord` requirements:
```swift
// File: Player.swift
// Give Player database powers
extension Player: MutablePersistableRecord {
/// Defines the values persisted in the database
func encode(to container: inout PersistenceContainer) {
container["id"] = id
container["name"] = name
container["score"] = score
}
/// Updates a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
```
</details>
Thanks to persistable records, we now support both inserts and updates:
```swift
// File: AppDatabase.swift
extension AppDatabase {
/// Saves (inserts or updates) a player. When the method returns, the
/// player is present in the database, and its id is not nil.
func savePlayer(_ player: inout Player) throws {
try dbWriter.write { db in
try player.save(db)
}
}
}
```
Usage:
```swift
// Inserts a player
var player = Player(id: nil, name: "Arthur", score: 0)
try AppDatabase.shared.savePlayer(player)
print("Player id is \(player.id)") // Prints "Player id is 1"
// Updates a player
player.score = 1000
try AppDatabase.shared.savePlayer(player)
```
> ✅ At this stage, we can save players in the database.
## Deleting Players
The application can delete players:
- The "Trash" icon at the bottom left of the [screen] deletes all players.
- The "Edit" button at the top left of the screen lets the user delete individual players.
- The player list supports the swipe to delete gesture.
The `AppDatabase` service supports these use cases with two new methods:
```swift
// File: AppDatabase.swift
extension AppDatabase {
/// Delete the specified players
func deletePlayers(ids: [Int64]) throws {
try dbWriter.write { db in
_ = try Player.deleteAll(db, keys: ids)
}
}
/// Delete all players
func deleteAllPlayers() throws {
try dbWriter.write { db in
_ = try Player.deleteAll(db)
}
}
}
```
Both `deleteAll(_:)` and `deleteAll(_:keys:)` methods are available for all persistable records.
<details>
<summary>Raw SQL version</summary>
> If you do not want to make `Player` a persistable record, you can fallback to raw SQL:
>
> ```swift
> // File: AppDatabase.swift
>
> extension AppDatabase {
> /// Delete the specified players
> func deletePlayers(ids: [Int64]) throws {
> try dbWriter.write { db in
> try db.execute(literal: """
> DELETE FROM player WHERE id IN \(ids)
> """)
> }
> }
>
> /// Delete all players
> func deleteAllPlayers() throws {
> try dbWriter.write { db in
> try db.execute(sql: "DELETE FROM player")
> }
> }
> }
> ```
>
> The `deletePlayers(ids:)` method above uses [SQL Interpolation] so that you can embed an array of ids right inside your SQL query (`WHERE id IN \(ids)`). The "really raw" SQL version below is a little more involved:
>
> ```swift
> func deletePlayers(ids: [Int64]) throws {
> try dbWriter.write { db in
> if ids.isEmpty {
> // Avoid SQL syntax error
> return
> }
> // DELETE FROM player WHERE id IN (?, ?, ...)
> // ~~~~~~~~~
> // as many question marks as there are ids
> let placeholders = databaseQuestionMarks(count: ids.count)
> let query = "DELETE FROM player WHERE id IN (\(placeholders))"
> try db.execute(sql: query, arguments: StatementArguments(ids))
> }
> }
> ```
>
> All the techniques we have seen avoid [SQL injection].
</details>
> ✅ At this stage, we can delete all or individual players from the database.
## Fetching Players
GRDB record types also provide fetching methods, when they adopt the [FetchableRecord] protocol.
This protocol is "free" when `Player` adopts the [Decodable] protocol:
```swift
// File: Player.swift
extension Player: Decodable, FetchableRecord { }
```
<details>
<summary>Avoiding Decodable</summary>
The `Decodable` protocol is handy, but you may prefer not to use it. In this case, you have to fulfill the [FetchableRecord] requirement:
```swift
// File: Player.swift
extension Player: FetchableRecord {
/// Creates a player from a database row
init(row: Row) {
id = row["id"]
name = row["name"]
score = row["score"]
}
}
```
</details>
> ✅ At this stage, we can turn raw database rows into players.
## Refreshing Players
The refresh button at the bottom center of the [screen] applies random transformations to the player database. The `AppDatabase` service supports this use cases by providing a `refreshPlayers()` method.
```swift
// File: AppDatabase.swift
extension AppDatabase {
/// Refresh all players (by performing some random changes, for demo purpose).
func refreshPlayers() throws {
try dbWriter.write { db in
if try Player.fetchCount(db) == 0 {
// When database is empty, insert new random players
try createRandomPlayers(db)
} else {
// Insert a player
if Bool.random() {
var player = Player.newRandom()
try player.save(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() {
try player.updateChanges(db) {
$0.score = Player.randomScore()
}
}
}
}
}
private func createRandomPlayers(_ db: Database) throws {
for _ in 0..<8 {
var player = Player.newRandom()
try player.save(db)
}
}
}
```
The `AppDatabase.refreshPlayers()` method calls a private helper method `createRandomPlayers(_:)`. This helper method will be reused later in the tutorial.
Refreshing players needs some support from the `Player` record type, so that we can build random players:
```swift
// File: Player.swift
extension Player {
private static let names = ["Arthur", "Anita", ...]
/// Creates a new player with random name and random score
static func newRandom() -> Player {
Player(id: nil, name: randomName(), score: randomScore())
}
/// Returns a random name
static func randomName() -> String {
names.randomElement()!
}
/// Returns a random score
static func randomScore() -> Int {
10 * Int.random(in: 0...100)
}
}
```
<details>
<summary>Raw SQL version</summary>
> Let's write `AppDatabase.refreshPlayers()` without any support from SQL generation provided by record protocols:
>
> ```swift
> // File: AppDatabase.swift
>
> extension AppDatabase {
> /// Refresh all players (by performing some random changes, for demo purpose).
> func refreshPlayers() throws {
> try dbWriter.write { db in
> if try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player") == 0 {
> // When database is empty, insert new random players
> try createRandomPlayers(db)
> } else {
> // Insert a player
> if Bool.random() {
> var player = Player.newRandom()
> try save(db, player: &player)
> }
>
> // Delete a random player
> if Bool.random() {
> try db.execute(sql: """
> DELETE FROM player
> ORDER BY RANDOM()
> LIMIT 1
> """)
> }
>
> // Update some players
> let ids = try Int64.fetchAll(db, sql: "SELECT id FROM player")
> for id in ids where Bool.random() {
> try db.execute(literal: """
> UPDATE player
> SET score = \(Player.randomScore())
> WHERE id = \(id)
> """)
> }
> }
> }
> }
>
> private func createRandomPlayers(_ db: Database) throws {
> for _ in 0..<8 {
> var player = Player.newRandom()
> try save(db, player: &player)
> }
> }
> }
> ```
>
> The `save(_:player:)` method was defined, with raw SQL, in [Saving Players].
</details>
<details>
<summary>ℹ️ Design Notes</summary>
> The role of the `AppDatabase` service is to provide a set of [ACID] transformations, that fully control the state of the database. Either a player is saved, either it is not. Players are refreshed, or they are not. If our application would synchronize its local database with some remote server, we would want players to be fully synchronized, or not at all. Intermediate states such as partially saved, deleted, refreshed, or synchronized players must be avoided, in order to make the application robust. After all, errors happen, and even hard crashes. Thanks to the ACID guarantees provided by SQLite, errors and crashes are unable to threaten important database invariants.
>
> **The added value of the `AppDatabase` service is to provide one method per database transformation needed by the app.** All those methods perform **a single GRDB write**, in order to profit from all ACID guarantees of SQLite transactions. Refreshing players is one of those transformations. Saving a player is another, which supports the user interface for editing of creating players.
>
> :bulb: **Tip**: when two distinct service methods want to reuse a piece of code, we extract it in a helper method such as `createRandomPlayers(_:)` above. Unlike service methods, helper methods access the database through their `Database` argument, not through the `dbWriter` property.
</details>
> ✅ At this stage, we can modify players in a controlled and robust way.
## Sorting Players
The application [screen] displays a list of players. The user can choose the order of players by tapping the button at the top right of the screen. The app supports two orderings: by descending score, and by ascending name.
In this chapter, we will not describe how the applications keeps its screen synchronized with the content of the database. This will be the topic of [Observing Players].
Here we will extend the `Player` record type so that it provides the **database requests** needed by the application.
<details>
<summary>ℹ️ Design Notes</summary>
> With GRDB, record types are responsible of their table: they know how data is stored in the database. This is why `Player` is better suited to know what sorting players by name, or by score, means.
>
> On the other side, `Player` does not perform database fetches on its own. Actual database fetches are performed by the application, depending on the user actions, by invoking methods on `AppDatabase.shared`.
>
> `Player` *defines* database requests, and `AppDatabase` *executes* those requests.
</details>
We made `Player` a full-fledged record type in the previous chapters. Record types can profit from the [query interface], a Swift way to build database requests.
In order to build requests that sort by score or by name, we need to define columns. When the `Player` type is [Codable], we can profit from its `CodingKeys` so that the compiler makes sure we do not make any typo:
```swift
// File: Player.swift
extension Player {
// Player columns are defined from CodingKeys
fileprivate enum Columns {
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
}
}
```
<details>
<summary>ℹ️ Design Notes</summary>
> `Player.Columns` is declared `fileprivate`. The goal is to prevent other application files from messing with the intimate relationship between the `Player` record type and the `player` database table.
>
> Some apps eventually need to relax the visibility of those columns. Until they really have to, though, `fileprivate` is the recommended default for columns.
</details>
<details>
<summary>Avoiding Codable</summary>
The `Codable` protocol is handy, but you may prefer not to use it. In this case, define columns as a String enum:
```swift
// File: Player.swift
extension Player {
// Player columns
fileprivate enum Columns: String, ColumnExpression {
case name
case score
}
}
```
</details>
Following advice from the [Good Practices for Designing Record Types], we can now define player requests in an extension of the `DerivableRequest` protocol:
```swift
// File: Player.swift
/// Define some player requests used by the application.
extension DerivableRequest where RowDecoder == Player {
/// A request of players ordered by name.
///
/// For example:
///
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByName().fetchAll(db)
/// }
func orderedByName() -> Self {
// Sort by name in a localized case insensitive fashion
order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
/// A request of players ordered by score.
///
/// For example:
///
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchAll(db)
/// }
/// let bestPlayer: Player? = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchOne(db)
/// }
func orderedByScore() -> Self {
// Sort by descending score, and then by name, in a
// localized case insensitive fashion
order(
Player.Columns.score.desc,
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
}
```
Names are sorted according to the `localizedCaseInsensitiveCompare` collation. See [String Comparison](../README.md#string-comparison) for more information.
Writing an "extension of the `DerivableRequest` protocol" may sound intimidating. Well, don't be shy, and look at the sample code above: it contains inline documentation which describes the usage of those requests. Is it more clear now? `DerivableRequest` makes it possible to extend the query interface with custom requests, and also to hide some database implementation details inside a dedicated record type.
If you know the [Active Record](https://guides.rubyonrails.org/active_record_querying.html) Ruby library, you may be reminded of [scopes](https://guides.rubyonrails.org/active_record_querying.html#scopes):
```ruby
# player.rb
class Player < ApplicationRecord
scope :ordered_by_name, -> { order(name: :asc) }
end
```
<details>
<summary>Raw SQL version</summary>
> You can build SQL requests with `SQLRequest`, which profits from [SQL Interpolation]. If you have the `Player` type conform to [FetchableRecord], those requests will be able to fetch. Otherwise, we'll have to fetch raw database rows and we will have more work to do. But those requests can still be defined:
>
> ```swift
> // File: Player.swift
>
> /// Define some player requests used by the application.
> extension Player {
> /// A request of players ordered by name.
> ///
> /// For example:
> ///
> /// let players: [Player] = try dbWriter.read { db in
> /// try Player.orderedByName().fetchAll(db)
> /// }
> static func orderedByName() -> SQLRequest<Player> {
> // Sort by name in a localized case insensitive fashion
> """
> SELECT * FROM player
> ORDER BY name COLLATING \(.localizedCaseInsensitiveCompare)
> """
> }
>
> /// A request of players ordered by score.
> ///
> /// For example:
> ///
> /// let players: [Player] = try dbWriter.read { db in
> /// try Player.orderedByScore().fetchAll(db)
> /// }
> static func orderedByScore() -> SQLRequest<Player> {
> // Sort by descending score, and then by name, in a
> // localized case insensitive fashion
> """
> SELECT * FROM player
> ORDER BY score DESC,
> name COLLATING \(.localizedCaseInsensitiveCompare)
> """
> }
> }
> ```
>
> Compared to query interface requests, raw SQL requests lose two benefits:
>
> - SQL requests are not composable together. You can not reuse them. For example:
>
> ```swift
> // A request from a future version of our app.
> // Request composition is only possible for query interface requests.
> let request = Player.all()
> .filter(team: .red)
> .including(all: Player.awards)
> .orderedByName()
> ```
>
> - SQL requests do not auto-optimize when you are only interested in the first row:
>
> ```swift
> // No automatic appending of `LIMIT 1`, as query interface requests do.
> let bestPlayer: Player? = try dbWriter.read { db in
> try Player.orderedByScore().fetchOne(db)
> }
> ```
</details>
> ✅ At this stage, we have defined the database requests that can feed the list of players in the application.
## Observing Players
Some elements that are visible in the application [screen] do not depend on the database: action buttons, and the selected ordering. Those are transient information that live in a UIKit controller, or a SwiftUI view.
The database content on screen is:
- The number of players (in the navigation title).
- The list of all players.
Those two elements are not independent. We want them to be always consistent: if there are twelve players in the list, the title must be "12 Players".
In the previous [Sorting Players] chapter, we built database requests for players, one sorted by name, one sorted by score. Now is time to fetch those players from those requests.
More precisely, we will **observe** the requests of players. This will make it much easier to display an always-accurate list of players in the app. We will not have to remember to update the list whenever the player database is updated.
> ✅ At this stage, we can feed UIViewControllers and SwiftUI with an always fresh list of players.
## The Initial Application State
Let's perform a little polishing step, so that the first time the application is launched, it is already populated with a few players. We write a demo application, and a demo is nicer when the user can play right away.
To this end, we create a new `AppDatabase.createRandomPlayersIfEmpty()` method. It reuses the `createRandomPlayers(_:)` helper method defined in the [Refreshing Players] chapter:
```swift
// File: AppDatabase.swift
extension AppDatabase {
/// Create random players if the database is empty.
func createRandomPlayersIfEmpty() throws {
try dbWriter.write { db in
if try Player.fetchCount(db) == 0 {
try createRandomPlayers(db)
}
}
}
}
```
And we modify `AppDatabase.makeShared()` so that the application never boots with an empty database:
```swift
// File: Persistence.swift
import GRDB
extension AppDatabase {
/// The database for the application
static let shared = makeShared()
private static func makeShared() -> AppDatabase {
do {
// Create a folder for storing the SQLite database
let fileManager = FileManager()
let folderURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
// Connect to a database on disk
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
// Populate the database if it is empty, for better demo purpose.
try appDatabase.createRandomPlayersIfEmpty()
return appDatabase
} catch {
fatalError("Unresolved error \(error)")
}
}
}
```
<details>
<summary>ℹ️ Design Notes</summary>
> We do not call `createRandomPlayersIfEmpty()` from the `AppDatabase` initializer, or from its migrator, because we also need to create empty databases (for tests, or some SwiftUI previews). The correct place is indeed `makeShared()`, the method that creates the database for the application itself.
</details>
> ✅ At this stage, we have a polished Database Access Layer that makes sure the demo app looks good.
## Testing the Database
[The Database Service]: #the-database-service
[The Shared Application Database]: #the-shared-application-database
[The Database Schema]: #the-database-schema
[The Player Struct]: #the-player-struct
[Saving Players]: #saving-players
[Deleting Players]: #deleting-players
[Fetching Players]: #fetching-players
[Refreshing Players]: #refreshing-players
[Sorting Players]: #sorting-players
[Observing Players]: #observing-players
[The Initial Application State]: #the-initial-application-state
[Testing the Database]: #testing-the-database
[demo applications]: DemoApps
[UIKit demo application]: DemoApps/GRDBDemoiOS/README.md
[Combine + SwiftUI Demo Application]: DemoApps/GRDBCombineDemo/README.md
[database connection]: https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
[DatabaseQueue]: ../README.md#database-queues
[DatabasePool]: ../README.md#database-pools
[migrations]: Migrations.md
[Codable]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[Encodable]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[Decodable]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[record type]: ../README.md#records
[persistable record]: ../README.md#persistablerecord-protocol
[FetchableRecord]: ../README.md#fetchablerecord-protocol
[WAL mode]: https://sqlite.org/wal.html
[data protection]: ../README.md#data-protection
[Associations]: AssociationsBasics.md
[Sharing a database]: SharingADatabase.md
[database observation]: ../README.md#database-changes-observation
[SQL Interpolation]: SQLInterpolation.md
[SQL injection]: ../README.md#avoiding-sql-injection
[screenshot]: https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png
[screen]: https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png
[ACID]: https://en.wikipedia.org/wiki/ACID
[query interface]: ../README.md#the-query-interface
[Good Practices for Designing Record Types]: GoodPracticesForDesigningRecordTypes.md
[Trust SQLite More Than Yourself]: GoodPracticesForDesigningRecordTypes.md#trust-sqlite-more-than-yourself
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '5.0.0-beta.8'
s.version = '5.3.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+38 -120
View File
@@ -7,6 +7,13 @@
objects = {
/* Begin PBXBuildFile section */
56012B552573EED000B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; };
56012B562573EED100B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; };
56012B572573EED100B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; };
56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
56012BA8257404E000B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
56012BB1257404E100B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
56012BB2257404E200B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; };
560432A1228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; };
560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
@@ -52,6 +59,10 @@
560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; };
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; };
560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; };
5611620825757583007AAF99 /* JoinAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5611620725757583007AAF99 /* JoinAssociation.swift */; };
5611620925757583007AAF99 /* JoinAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5611620725757583007AAF99 /* JoinAssociation.swift */; };
5611620A25757583007AAF99 /* JoinAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5611620725757583007AAF99 /* JoinAssociation.swift */; };
5611620B25757583007AAF99 /* JoinAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5611620725757583007AAF99 /* JoinAssociation.swift */; };
5613ED3521A95A5C00DC7A68 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* Map.swift */; };
5613ED3621A95A5C00DC7A68 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* Map.swift */; };
5613ED3721A95A5C00DC7A68 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* Map.swift */; };
@@ -810,6 +821,10 @@
56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
56D8B3FF257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; };
56D8B400257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; };
56D8B401257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; };
56D8B402257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; };
56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; };
56D91AA32205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; };
56D91AA42205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; };
@@ -856,66 +871,18 @@
56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; };
56F0B9921B6001C600A2F135 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; };
56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; };
56F34F9924AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */; };
56F34F9A24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */; };
56F34F9B24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */; };
56F34F9C24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */; };
56F34FA424B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */; };
56F34FA524B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */; };
56F34FA624B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */; };
56F34FA724B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */; };
56F34FBA24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; };
56F34FBB24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; };
56F34FBC24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; };
56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
56F34FC324B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
56F34FC424B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
56F34FC924B0DD6A007513FC /* SQLSelectableVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */; };
56F34FCA24B0DD6A007513FC /* SQLSelectableVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */; };
56F34FCB24B0DD6B007513FC /* SQLSelectableVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */; };
56F34FCC24B0DD6B007513FC /* SQLSelectableVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */; };
56F34FD124B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */; };
56F34FD224B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */; };
56F34FD324B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */; };
56F34FD424B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */; };
56F34FD624B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */; };
56F34FD724B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */; };
56F34FD824B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */; };
56F34FD924B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */; };
56F34FE124B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */; };
56F34FE224B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */; };
56F34FE324B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */; };
56F34FE424B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */; };
56F34FE924B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */; };
56F34FEA24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */; };
56F34FEB24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */; };
56F34FEC24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */; };
56F34FF424B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */; };
56F34FF524B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */; };
56F34FF624B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */; };
56F34FF724B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */; };
56F34FFF24B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */; };
56F3500024B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */; };
56F3500124B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */; };
56F3500224B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */; };
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56F5ABD91D814330001F60CB /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
56F5ABDA1D814330001F60CB /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; };
56F5ABDC1D814330001F60CB /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; };
56F5ABDD1D814330001F60CB /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
56F896AA24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */; };
56F896AB24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */; };
56F896AC24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */; };
56F896AD24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */; };
56F896B624B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */; };
56F896B724B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */; };
56F896B824B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */; };
56F896B924B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */; };
56F896BB24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */; };
56F896BC24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */; };
56F896BD24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */; };
56F896BE24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */; };
56FBFED92210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
@@ -1279,6 +1246,8 @@
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
56012B542573EED000B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = "<group>"; };
56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = "<group>"; };
56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = "<group>"; };
560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = "<group>"; };
56057C4E2291B16900A7CB10 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = "<group>"; };
@@ -1304,6 +1273,7 @@
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = "<group>"; };
560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = "<group>"; };
560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = "<group>"; };
5611620725757583007AAF99 /* JoinAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinAssociation.swift; sourceTree = "<group>"; };
5613ED3421A95A5C00DC7A68 /* Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = "<group>"; };
5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = "<group>"; };
5615B25A222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLDerivationTests.swift; sourceTree = "<group>"; };
@@ -1607,6 +1577,7 @@
56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = "<group>"; };
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = "<group>"; };
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRowValue.swift; sourceTree = "<group>"; };
56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
56D91AA82205F2F000770D8D /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = "<group>"; };
56D91AAF2205F8AC00770D8D /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = "<group>"; };
@@ -1629,21 +1600,9 @@
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = "<group>"; };
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionVisitor.swift; sourceTree = "<group>"; };
56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionGenerator.swift; sourceTree = "<group>"; };
56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionIsConstantTests.swift; sourceTree = "<group>"; };
56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = "<group>"; };
56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelectableVisitor.swift; sourceTree = "<group>"; };
56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelectableResultColumnGenerator.swift; sourceTree = "<group>"; };
56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectableCountGenerator.swift; sourceTree = "<group>"; };
56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLOrderingTermVisitor.swift; sourceTree = "<group>"; };
56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrderingGenerator.swift; sourceTree = "<group>"; };
56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollectionVisitor.swift; sourceTree = "<group>"; };
56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollectionGenerator.swift; sourceTree = "<group>"; };
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchRequestVisitor.swift; sourceTree = "<group>"; };
56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestGenerator.swift; sourceTree = "<group>"; };
56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLPreparedRequestGenerator.swift; sourceTree = "<group>"; };
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = "<group>"; };
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
@@ -1902,6 +1861,7 @@
isa = PBXGroup;
children = (
56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */,
56012B542573EED000B4925B /* CommonTableExpressionTests.swift */,
56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */,
56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */,
56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */,
@@ -2060,6 +2020,7 @@
56959628222C462D002CB7C9 /* HasManyThroughAssociation.swift */,
5653EB0220944C7C00F46237 /* HasOneAssociation.swift */,
56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */,
5611620725757583007AAF99 /* JoinAssociation.swift */,
);
path = Association;
sourceTree = "<group>";
@@ -2076,15 +2037,8 @@
5656A8162295AFD6001FF3FF /* SQLGeneration */ = {
isa = PBXGroup;
children = (
56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */,
56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */,
5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */,
56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */,
56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */,
568D13182207213E00674B58 /* SQLQueryGenerator.swift */,
56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */,
56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */,
56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */,
);
path = SQLGeneration;
sourceTree = "<group>";
@@ -2097,21 +2051,18 @@
5656A81D2295B12F001FF3FF /* SQLAssociation.swift */,
5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */,
566475991D97D8A000FF74B8 /* SQLCollection.swift */,
56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */,
56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */,
56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */,
56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */,
56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */,
5653EAF920944C7B00F46237 /* SQLForeignKeyRequest.swift */,
566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */,
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */,
56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */,
56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */,
56D91AAF2205F8AC00770D8D /* SQLQuery.swift */,
56D91AA12205E03700770D8D /* SQLRelation.swift */,
56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */,
56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */,
566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */,
56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */,
566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */,
);
path = SQL;
@@ -2121,6 +2072,7 @@
isa = PBXGroup;
children = (
5653EAF720944BC900F46237 /* Association */,
56012B742574048B00B4925B /* CommonTableExpression.swift */,
56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */,
5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */,
5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */,
@@ -2352,7 +2304,6 @@
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */,
56A238761B9C75030082EB20 /* Row.swift */,
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
@@ -2919,12 +2870,10 @@
files = (
5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
56F34FCB24B0DD6B007513FC /* SQLSelectableVisitor.swift in Sources */,
56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
565490CE1D5AE252005622CB /* NSNull.swift in Sources */,
5656A8202295B12F001FF3FF /* SQLAssociation.swift in Sources */,
565490E41D5AE252005622CB /* TableRecord.swift in Sources */,
56F3500124B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */,
564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
565490CF1D5AE252005622CB /* NSNumber.swift in Sources */,
566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */,
@@ -2947,7 +2896,6 @@
56172950223533F40006E219 /* EncodableRecord.swift in Sources */,
56AE64142229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
5613ED3721A95A5C00DC7A68 /* Map.swift in Sources */,
56F34FD324B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */,
5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */,
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */,
56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
@@ -2964,8 +2912,8 @@
565490D91D5AE252005622CB /* Migration.swift in Sources */,
56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
5698AD271DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
56F896BD24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */,
C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */,
56012BB1257404E100B4925B /* CommonTableExpression.swift in Sources */,
566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
565490D51D5AE252005622CB /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */,
@@ -2973,6 +2921,7 @@
5698AC3D1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
563EF45D2163309F007DAACD /* Inflections.swift in Sources */,
569D6DE0220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
5611620A25757583007AAF99 /* JoinAssociation.swift in Sources */,
567ECE512222E431009245CA /* GRDB-5.0.swift in Sources */,
565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */,
566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
@@ -2993,14 +2942,12 @@
565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */,
563B8FAE24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */,
565490CA1D5AE252005622CB /* DatabaseDateComponents.swift in Sources */,
56F896AC24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */,
565490D01D5AE252005622CB /* NSString.swift in Sources */,
565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */,
565490B71D5AE236005622CB /* Database.swift in Sources */,
5674A6E81F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
56E9FACD221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
5653EB2320944C7C00F46237 /* HasOneAssociation.swift in Sources */,
56F34F9B24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */,
565490C01D5AE236005622CB /* DatabaseWriter.swift in Sources */,
565490C41D5AE236005622CB /* SchedulingWatchdog.swift in Sources */,
566B91311FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */,
@@ -3020,12 +2967,10 @@
56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */,
56F5ABD91D814330001F60CB /* Data.swift in Sources */,
565490D41D5AE252005622CB /* (null) in Sources */,
56F34FA624B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */,
566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
565490B61D5AE236005622CB /* Configuration.swift in Sources */,
565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */,
56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
56F896B824B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */,
569BBA50229170FA00478429 /* Inflections+English.swift in Sources */,
563B8FB724A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
@@ -3044,18 +2989,15 @@
565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */,
565490B81D5AE236005622CB /* DatabaseError.swift in Sources */,
56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */,
56D8B401257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */,
5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
56A2FA3C24424F4800E97D23 /* Export.swift in Sources */,
565490BC1D5AE236005622CB /* DatabaseSchemaCache.swift in Sources */,
563EF42F2161180D007DAACD /* AssociationAggregate.swift in Sources */,
565490BA1D5AE236005622CB /* DatabaseQueue.swift in Sources */,
56F34FEB24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */,
56781B0D243F86E600650A83 /* Refinable.swift in Sources */,
565490CD1D5AE252005622CB /* Date.swift in Sources */,
56F34FD824B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */,
56F34FE324B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */,
56F34FF624B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */,
5653EB0820944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */,
565490BE1D5AE236005622CB /* DatabaseValue.swift in Sources */,
);
@@ -3085,8 +3027,6 @@
5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */,
563EF42E2161180D007DAACD /* AssociationAggregate.swift in Sources */,
56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
56F34FEA24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */,
56F34FD724B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */,
563B8FC624A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
5656A8B12295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
@@ -3095,13 +3035,13 @@
5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */,
566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
56012BA8257404E000B4925B /* CommonTableExpression.swift in Sources */,
5653EB0A20944C7C00F46237 /* Association.swift in Sources */,
56A2387E1B9C75030082EB20 /* Database.swift in Sources */,
56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
5605F15A1C672E4000235C62 /* CGFloat.swift in Sources */,
56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */,
5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
56F896AB24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */,
5605F1641C672E4000235C62 /* Date.swift in Sources */,
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */,
@@ -3117,7 +3057,6 @@
5664759D1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
568D13202207213E00674B58 /* SQLQueryGenerator.swift in Sources */,
5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
56F34FE224B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */,
563EF416215F87EB007DAACD /* OrderedDictionary.swift in Sources */,
563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */,
5698AD1B1DAAD17D0056AF8C /* FTS5Tokenizer.swift in Sources */,
@@ -3125,7 +3064,6 @@
56B964B41DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
563B8FB624A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
56F34FD224B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */,
566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
56CEB54F1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
@@ -3134,7 +3072,6 @@
56A8C2331D1914540096E9D4 /* UUID.swift in Sources */,
560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
566475BD1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */,
56F3500024B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */,
56A238A51B9C753B0082EB20 /* Record.swift in Sources */,
5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
@@ -3149,7 +3086,6 @@
5657AB121D10899D006283EF /* URL.swift in Sources */,
5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
5659F48B1EA8D94E004A4992 /* Utils.swift in Sources */,
56F34FA524B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */,
56A2387C1B9C75030082EB20 /* Configuration.swift in Sources */,
56DAA2DE1DE9C827006E10C8 /* Cursor.swift in Sources */,
560A37A51C8F625000949E71 /* DatabasePool.swift in Sources */,
@@ -3158,14 +3094,10 @@
56A2388C1B9C75030082EB20 /* Statement.swift in Sources */,
5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
56D91AB12205F8AC00770D8D /* SQLQuery.swift in Sources */,
56F896BC24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */,
56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */,
56F896B724B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */,
5690C3431D23E82A00E59934 /* Data.swift in Sources */,
5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
5674A6E91F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
56F34FF524B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */,
56F34F9A24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */,
566B91161FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
56A238881B9C75030082EB20 /* Row.swift in Sources */,
@@ -3181,6 +3113,7 @@
569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
563B06AC217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
5611620925757583007AAF99 /* JoinAssociation.swift in Sources */,
56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */,
566BE71F2342542F00A8254B /* LockedBox.swift in Sources */,
5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
@@ -3189,6 +3122,7 @@
5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */,
566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
56D8B400257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */,
5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
56FBFED92210731A00945324 /* SQLRequest.swift in Sources */,
5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
@@ -3216,7 +3150,6 @@
56D91AA32205E03700770D8D /* SQLRelation.swift in Sources */,
564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */,
564CE59E21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
56F34FCA24B0DD6A007513FC /* SQLSelectableVisitor.swift in Sources */,
56B964A01DA51B4C0002DA19 /* FTS5.swift in Sources */,
5674A6F01F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
);
@@ -3286,6 +3219,7 @@
5698AC4D1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */,
56419C6E24A519A3004967E1 /* DatabaseWriterWritePublisherTests.swift in Sources */,
56057C632291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */,
56012B562573EED100B4925B /* CommonTableExpressionTests.swift in Sources */,
56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */,
5656A80022946B34001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */,
5615B261222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */,
@@ -3511,6 +3445,7 @@
56D496881D81316E008276D7 /* DatabaseValueConversionTests.swift in Sources */,
56419C6924A519A2004967E1 /* DatabaseWriterWritePublisherTests.swift in Sources */,
56057C622291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */,
56012B552573EED000B4925B /* CommonTableExpressionTests.swift in Sources */,
56D496BA1D813482008276D7 /* DatabaseQueueSchemaCacheTests.swift in Sources */,
56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */,
5656A7FF22946B34001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */,
@@ -3679,8 +3614,6 @@
AAA4DC77230F1E0600C74B15 /* FetchRequest.swift in Sources */,
AAA4DC78230F1E0600C74B15 /* AssociationAggregate.swift in Sources */,
AAA4DC79230F1E0600C74B15 /* SchedulingWatchdog.swift in Sources */,
56F34FEC24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */,
56F34FD924B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */,
563B8FC824A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
AAA4DC7A230F1E0600C74B15 /* QueryInterfaceRequest.swift in Sources */,
AAA4DC7B230F1E0600C74B15 /* TableRecord+QueryInterfaceRequest.swift in Sources */,
@@ -3689,13 +3622,13 @@
AAA4DC7E230F1E0600C74B15 /* SQLCollatedExpression.swift in Sources */,
AAA4DC7F230F1E0600C74B15 /* SQLOperators.swift in Sources */,
AAA4DC80230F1E0600C74B15 /* FTS5CustomTokenizer.swift in Sources */,
56012BB2257404E200B4925B /* CommonTableExpression.swift in Sources */,
AAA4DC81230F1E0600C74B15 /* Association.swift in Sources */,
AAA4DC82230F1E0600C74B15 /* Database.swift in Sources */,
AAA4DC83230F1E0600C74B15 /* FTS3.swift in Sources */,
AAA4DC84230F1E0600C74B15 /* CGFloat.swift in Sources */,
AAA4DC85230F1E0600C74B15 /* Column.swift in Sources */,
AAA4DC86230F1E0600C74B15 /* QueryInterfaceRequest+Association.swift in Sources */,
56F896AD24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */,
AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */,
AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */,
AAA4DC8A230F1E0600C74B15 /* ValueObserver.swift in Sources */,
@@ -3711,7 +3644,6 @@
AAA4DC93230F1E0600C74B15 /* SQLCollection.swift in Sources */,
AAA4DC94230F1E0600C74B15 /* SQLQueryGenerator.swift in Sources */,
AAA4DC95230F1E0600C74B15 /* RowAdapter.swift in Sources */,
56F34FE424B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */,
AAA4DC96230F1E0600C74B15 /* OrderedDictionary.swift in Sources */,
AAA4DC97230F1E0600C74B15 /* DatabaseWriter.swift in Sources */,
AAA4DC98230F1E0600C74B15 /* FTS5Tokenizer.swift in Sources */,
@@ -3719,7 +3651,6 @@
AAA4DC9A230F1E0600C74B15 /* FTS5TokenizerDescriptor.swift in Sources */,
563B8FB824A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
AAA4DC9B230F1E0600C74B15 /* SerializedDatabase.swift in Sources */,
56F34FD424B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */,
AAA4DC9C230F1E0600C74B15 /* DatabaseSnapshot.swift in Sources */,
AAA4DC9D230F1E0600C74B15 /* SQLExpressible.swift in Sources */,
AAA4DC9E230F1E0600C74B15 /* DatabaseMigrator.swift in Sources */,
@@ -3728,7 +3659,6 @@
AAA4DCA1230F1E0600C74B15 /* UUID.swift in Sources */,
AAA4DCA2230F1E0600C74B15 /* DatabaseValueConvertible.swift in Sources */,
AAA4DCA3230F1E0600C74B15 /* SQLSpecificExpressible+QueryInterface.swift in Sources */,
56F3500224B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */,
AAA4DCA4230F1E0600C74B15 /* Record.swift in Sources */,
AAA4DCA5230F1E0600C74B15 /* FTS3TokenizerDescriptor.swift in Sources */,
AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */,
@@ -3743,7 +3673,6 @@
AAA4DCAD230F1E0600C74B15 /* URL.swift in Sources */,
AAA4DCAE230F1E0600C74B15 /* RequestProtocols.swift in Sources */,
AAA4DCAF230F1E0600C74B15 /* Utils.swift in Sources */,
56F34FA724B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */,
AAA4DCB0230F1E0600C74B15 /* Configuration.swift in Sources */,
AAA4DCB1230F1E0600C74B15 /* Cursor.swift in Sources */,
AAA4DCB2230F1E0600C74B15 /* DatabasePool.swift in Sources */,
@@ -3752,14 +3681,10 @@
AAA4DCB5230F1E0600C74B15 /* Statement.swift in Sources */,
AAA4DCB6230F1E0600C74B15 /* ReadWriteBox.swift in Sources */,
AAA4DCB7230F1E0600C74B15 /* SQLQuery.swift in Sources */,
56F896BE24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */,
AAA4DCB8230F1E0600C74B15 /* Migration.swift in Sources */,
56F896B924B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */,
AAA4DCB9230F1E0600C74B15 /* Data.swift in Sources */,
AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */,
AAA4DCBB230F1E0600C74B15 /* DatabaseValueConvertible+Decodable.swift in Sources */,
56F34FF724B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */,
56F34F9C24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */,
AAA4DCBC230F1E0600C74B15 /* DatabaseCollation.swift in Sources */,
AAA4DCBD230F1E0600C74B15 /* SQLExpression+QueryInterface.swift in Sources */,
AAA4DCBE230F1E0600C74B15 /* Row.swift in Sources */,
@@ -3775,6 +3700,7 @@
AAA4DCCB230F1E0600C74B15 /* DatabaseRegion.swift in Sources */,
AAA4DCCC230F1E0600C74B15 /* DatabaseQueue.swift in Sources */,
AAA4DCCD230F1E0600C74B15 /* ValueObservation.swift in Sources */,
5611620B25757583007AAF99 /* JoinAssociation.swift in Sources */,
AAA4DCCE230F1E0600C74B15 /* DatabasePromise.swift in Sources */,
566BE7212342542F00A8254B /* LockedBox.swift in Sources */,
AAA4DCCF230F1E0600C74B15 /* VirtualTableModule.swift in Sources */,
@@ -3783,6 +3709,7 @@
AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */,
AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */,
AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */,
56D8B402257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */,
AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */,
AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */,
AAA4DCD7230F1E0600C74B15 /* DatabaseValueConversion.swift in Sources */,
@@ -3810,7 +3737,6 @@
AAA4DCEF230F1E0600C74B15 /* SQLRelation.swift in Sources */,
AAA4DCF0230F1E0600C74B15 /* DatabaseFunction.swift in Sources */,
AAA4DCF1230F1E0600C74B15 /* RemoveDuplicates.swift in Sources */,
56F34FCC24B0DD6B007513FC /* SQLSelectableVisitor.swift in Sources */,
AAA4DCF2230F1E0600C74B15 /* FTS5.swift in Sources */,
AAA4DCF3230F1E0600C74B15 /* DatabaseValueConvertible+Encodable.swift in Sources */,
);
@@ -3880,6 +3806,7 @@
AAA4DD3E230F262000C74B15 /* FTS3RecordTests.swift in Sources */,
56419C7324A519A4004967E1 /* DatabaseWriterWritePublisherTests.swift in Sources */,
AAA4DD3F230F262000C74B15 /* AssociationHasManyThroughRowScopeTests.swift in Sources */,
56012B572573EED100B4925B /* CommonTableExpressionTests.swift in Sources */,
AAA4DD41230F262000C74B15 /* RecordInitializersTests.swift in Sources */,
AAA4DD42230F262000C74B15 /* ValueObservationQueryInterfaceRequestTests.swift in Sources */,
AAA4DD43230F262000C74B15 /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */,
@@ -4048,8 +3975,6 @@
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */,
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
56F34FE924B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */,
56F34FD624B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */,
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
@@ -4058,13 +3983,13 @@
563EF44A2161F179007DAACD /* Inflections.swift in Sources */,
566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */,
563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
56F896AA24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */,
56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */,
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */,
@@ -4080,7 +4005,6 @@
5605F1591C672E4000235C62 /* CGFloat.swift in Sources */,
5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
5605F1631C672E4000235C62 /* Date.swift in Sources */,
56F34FE124B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */,
5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */,
566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
@@ -4088,7 +4012,6 @@
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */,
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */,
56F34FD124B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */,
564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
5659F4981EA8D989004A4992 /* Pool.swift in Sources */,
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */,
@@ -4097,7 +4020,6 @@
5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
56F34FFF24B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */,
563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */,
569BBA4E229170F800478429 /* Inflections+English.swift in Sources */,
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */,
@@ -4112,7 +4034,6 @@
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */,
56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
56F34FA424B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */,
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
56CEB55A1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */,
56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */,
@@ -4121,14 +4042,10 @@
5653EB0920944C7C00F46237 /* Association.swift in Sources */,
56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */,
5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
56F896BB24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */,
56A238A41B9C753B0082EB20 /* Record.swift in Sources */,
56F896B624B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */,
56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */,
5657AB0F1D10899D006283EF /* URL.swift in Sources */,
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */,
56F34FF424B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */,
56F34F9924AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */,
56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */,
5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */,
@@ -4144,6 +4061,7 @@
56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */,
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
5611620825757583007AAF99 /* JoinAssociation.swift in Sources */,
5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */,
569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */,
@@ -4152,6 +4070,7 @@
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */,
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */,
56D8B3FF257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */,
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */,
5605F1651C672E4000235C62 /* NSNull.swift in Sources */,
56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
@@ -4179,7 +4098,6 @@
5644DE6D20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
5657AAB91D107001006283EF /* NSData.swift in Sources */,
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
56F34FC924B0DD6A007513FC /* SQLSelectableVisitor.swift in Sources */,
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
56B9649D1DA51B4C0002DA19 /* FTS5.swift in Sources */,
);
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1200"
LastUpgradeVersion = "1230"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1200"
LastUpgradeVersion = "1230"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1200"
LastUpgradeVersion = "1230"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1200"
LastUpgradeVersion = "1230"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+17 -4
View File
@@ -103,16 +103,23 @@ public struct Configuration {
// MARK: - Managing SQLite Connections
/// A function that is run when an SQLite connection is opened, before the
/// connection is made available for database access methods.
private var setups: [(Database) throws -> Void] = []
/// The function argument is run when an SQLite connection is opened,
/// before the connection is made available for database access methods.
///
/// For example:
///
/// var config = Configuration()
/// config.prepareDatabase = { db in
/// config.prepareDatabase { db in
/// try db.execute(sql: "PRAGMA kdf_iter = 10000")
/// }
public var prepareDatabase: ((Database) throws -> Void)?
///
/// This method can be called several times. The setup functions are run in
/// the same order.
public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) {
setups.append(setup)
}
// MARK: - Transactions
@@ -207,6 +214,12 @@ public struct Configuration {
return threadingMode.SQLiteOpenFlags | readWriteFlags
}
func setUp(_ db: Database) throws {
for f in setups {
try f(db)
}
}
func identifier(defaultLabel: String, purpose: String? = nil) -> String {
(self.label ?? defaultLabel) + (purpose.map { "." + $0 } ?? "")
}
+23 -9
View File
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
// MARK: - Array, Sequence, Set extensions
// MARK: - Array, Sequence, Dictionary, Set extensions
extension Array {
/// Creates an array containing the elements of a cursor.
@@ -25,13 +25,27 @@ extension Array {
}
}
extension Dictionary {
/// Creates a new dictionary whose keys are the groupings returned by the
/// given closure and whose values are arrays of the elements that returned
/// each key.
public init<C: Cursor>(grouping values: C, by keyForValue: (C.Element) throws -> Key)
throws where Value == [C.Element]
{
self.init()
while let value = try values.next() {
try self[keyForValue(value), default: []].append(value)
}
}
}
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>>
-> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>>
{
AnyCursor(self).flatMap(transform)
}
@@ -145,7 +159,7 @@ extension Cursor {
/// Returns a cursor over the concatenated non-nil results of mapping
/// transform over this cursor.
public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?)
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
{
map(transform).filter { $0 != nil }.map { $0! }
}
@@ -249,8 +263,8 @@ extension Cursor {
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult>(_ transform: @escaping (Element) throws -> SegmentOfResult)
-> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>>
where SegmentOfResult: Sequence
-> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>>
where SegmentOfResult: Sequence
{
flatMap { try AnyCursor(transform($0)) }
}
@@ -258,8 +272,8 @@ extension Cursor {
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult>(_ transform: @escaping (Element) throws -> SegmentOfResult)
-> FlattenCursor<MapCursor<Self, SegmentOfResult>>
where SegmentOfResult: Cursor
-> FlattenCursor<MapCursor<Self, SegmentOfResult>>
where SegmentOfResult: Cursor
{
map(transform).joined()
}
@@ -353,7 +367,7 @@ extension Cursor {
public func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult: (Result, Element) throws -> Result)
throws -> Result
throws -> Result
{
var accumulator = initialResult
while let element = try next() {
@@ -367,7 +381,7 @@ extension Cursor {
public func reduce<Result>(
into initialResult: Result,
_ updateAccumulatingResult: (inout Result, Element) throws -> Void)
throws -> Result
throws -> Result
{
var accumulator = initialResult
while let element = try next() {
+105 -37
View File
@@ -18,6 +18,16 @@ extension Database {
publicStatementCache.clear()
}
/// Clears the database schema cache if the database schema has changed
/// since this method was last called.
func clearSchemaCacheIfNeeded() throws {
let schemaVersion = try Int32.fetchOne(internalCachedSelectStatement(sql: "PRAGMA schema_version"))
if _lastSchemaVersion != schemaVersion {
_lastSchemaVersion = schemaVersion
clearSchemaCache()
}
}
/// Returns whether a table exists.
public func tableExists(_ name: String) throws -> Bool {
try exists(type: .table, name: name)
@@ -25,26 +35,44 @@ extension Database {
/// Returns whether a table is an internal SQLite table.
///
/// Those are tables whose name begins with "sqlite_".
/// Those are tables whose name begins with `sqlite_` and `pragma_`.
///
/// For more information, see https://www.sqlite.org/fileformat2.html
public func isSQLiteInternalTable(_ tableName: String) -> Bool {
public static 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_")
tableName.starts(with: "sqlite_") || tableName.starts(with: "pragma_")
}
/// Returns whether a table is an internal SQLite table.
///
/// Those are tables whose name begins with `sqlite_` and `pragma_`.
///
/// For more information, see https://www.sqlite.org/fileformat2.html
@available(*, deprecated, message: "Use Database.isSQLiteInternalTable(_:) static method instead.")
public func isSQLiteInternalTable(_ tableName: String) -> Bool {
Self.isSQLiteInternalTable(tableName)
}
/// Returns whether a table is an internal GRDB table.
///
/// Those are tables whose name begins with "grdb_".
public func isGRDBInternalTable(_ tableName: String) -> Bool {
public static func isGRDBInternalTable(_ tableName: String) -> Bool {
tableName.starts(with: "grdb_")
}
/// Returns whether a table is an internal GRDB table.
///
/// Those are tables whose name begins with "grdb_".
@available(*, deprecated, message: "Use Database.isGRDBInternalTable(_:) static method instead.")
public func isGRDBInternalTable(_ tableName: String) -> Bool {
Self.isGRDBInternalTable(tableName)
}
/// Returns whether a view exists.
public func viewExists(_ name: String) throws -> Bool {
try exists(type: .view, name: name)
@@ -168,35 +196,49 @@ extension Database {
return false
}
}
/// The indexes on table named `tableName`; returns the empty array if the
/// table does not exist.
/// The indexes on table named `tableName`.
///
/// Note: SQLite does not define any index for INTEGER PRIMARY KEY columns:
/// this method does not return any index that represents this primary key.
/// Only indexes on columns are returned. Indexes on expressions are
/// not returned.
///
/// SQLite does not define any index for INTEGER PRIMARY KEY columns: this
/// method does not return any index that represents the primary key.
///
/// If you want to know if a set of columns uniquely identify a row, prefer
/// table(_:hasUniqueKey:) instead.
/// `table(_:hasUniqueKey:)` instead.
public func indexes(on tableName: String) throws -> [IndexInfo] {
if let indexes = schemaCache.indexes(on: tableName) {
return indexes
}
let indexes = try Row
// [seq:0 name:"index" unique:0 origin:"c" partial:0]
.fetchAll(self, sql: "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))")
.map { row -> IndexInfo in
// [seq:0 name:"index" unique:0 origin:"c" partial:0]
.compactMap { row -> IndexInfo? in
let indexName: String = row[1]
let unique: Bool = row[2]
let columns = try Row
let indexInfoRows = try Row
// [seqno:0 cid:2 name:"column"]
.fetchAll(self, sql: "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 }
// Sort by rank
.sorted(by: { ($0[0] as Int) < ($1[0] as Int) })
var columns: [String] = []
for indexInfoRow in indexInfoRows {
guard let column = indexInfoRow[2] as String? else {
// https://sqlite.org/pragma.html#pragma_index_info
// > The name of the column being indexed is NULL if the
// > column is the rowid or an expression.
//
// IndexInfo does not support expressing such index.
// Maybe in a future GRDB version?
return nil
}
columns.append(column)
}
return IndexInfo(name: indexName, columns: columns, unique: unique)
}
}
if indexes.isEmpty {
// PRAGMA index_list doesn't throw any error when table does
@@ -215,8 +257,8 @@ extension Database {
public func table<T: Sequence>(
_ tableName: String,
hasUniqueKey columns: T)
throws -> Bool
where T.Iterator.Element == String
throws -> Bool
where T.Iterator.Element == String
{
try columnsForUniqueKey(Array(columns), in: tableName) != nil
}
@@ -244,9 +286,8 @@ extension Database {
.mapping
.append((origin: origin, destination: destination, seq: seq))
} else {
rawForeignKeys.append((
destinationTable: table,
mapping: [(origin: origin, destination: destination, seq: seq)]))
let mapping = [(origin: origin, destination: destination, seq: seq)]
rawForeignKeys.append((destinationTable: table, mapping: mapping))
previousId = id
}
}
@@ -322,27 +363,54 @@ extension Database {
// > column in the primary key for columns that are part of the primary
// > key.
//
// CREATE TABLE players (
// sqlite> CREATE TABLE players (
// id INTEGER PRIMARY KEY,
// firstName TEXT,
// lastName TEXT)
//
// PRAGMA table_info("players")
// lastName TEXT);
//
// sqlite> PRAGMA table_info("players");
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
if sqlite3_libversion_number() < 3008005 {
// Work around a bug in SQLite where PRAGMA table_info would
// return a result even after the table was deleted.
if try !tableExists(tableName) {
throw DatabaseError(message: "no such table: \(tableName)")
//
//
// PRAGMA table_info does not expose hidden and generated columns. For
// that, we need PRAGMA table_xinfo, introduced in SQLite 3.26.0:
// https://sqlite.org/releaselog/3_26_0.html
//
// > PRAGMA schema.table_xinfo(table-name);
//
// > This pragma returns one row for each column in the named table,
// > including hidden columns in virtual tables. The output is the same
// > as for PRAGMA table_info except that hidden columns are shown
// > rather than being omitted.
//
// sqlite> PRAGMA table_xinfo("players");
// cid | name | type | notnull | dflt_value | pk | hidden
// 0 | id | INTEGER | 0 | NULL | 1 | 0
// 1 | firstName | TEXT | 0 | NULL | 0 | 0
// 2 | lastName | TEXT | 0 | NULL | 0 | 0
let columnInfoQuery: String
if sqlite3_libversion_number() < 3026000 {
if sqlite3_libversion_number() < 3008005 {
// Work around a bug in SQLite where PRAGMA table_info would
// return a result even after the table was deleted.
if try !tableExists(tableName) {
throw DatabaseError(message: "no such table: \(tableName)")
}
}
columnInfoQuery = "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))"
} else {
// For our purposes, we look for generated columns, not hidden
// columns. The "hidden" column magic numbers come from the SQLite
// source code. The values 2 and 3 refer to virtual and stored
// generated columns, respectively. Search for COLFLAG_VIRTUAL in
// https://www.sqlite.org/cgi/src/file?name=src/pragma.c&ci=fca8dc8b578f215a
columnInfoQuery = "SELECT * FROM pragma_table_xinfo('\(tableName)') WHERE hidden IN (0,2,3)"
}
let columns = try ColumnInfo
.fetchAll(self, sql: "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
.fetchAll(self, sql: columnInfoQuery)
.sorted(by: { $0.cid < $1.cid })
if columns.isEmpty {
throw DatabaseError(message: "no such table: \(tableName)")
@@ -358,8 +426,8 @@ extension Database {
func columnsForUniqueKey<T: Sequence>(
_ columns: T,
in tableName: String)
throws -> [String]?
where T.Iterator.Element == String
throws -> [String]?
where T.Iterator.Element == String
{
let lowercasedColumns = Set(columns.map { $0.lowercased() })
if lowercasedColumns.isEmpty {
+75 -90
View File
@@ -125,6 +125,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// MARK: - Internal properties
// Caches
var _lastSchemaVersion: Int32? // Support for clearSchemaCacheIfNeeded()
var schemaCache: DatabaseSchemaCache // internal so that it can be tested
lazy var internalStatementCache = StatementCache(database: self)
lazy var publicStatementCache = StatementCache(database: self)
@@ -210,7 +211,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// MARK: - Database Setup
/// This method must be called after database initialization
func setup() throws {
func setUp() throws {
setupBusyMode()
setupDoubleQuotedStringLiterals()
try setupForeignKeys()
@@ -225,7 +226,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
#endif
// Last step before we can start accessing the database.
try configuration.prepareDatabase?(self)
try configuration.setUp(self)
try validateFormat()
configuration.SQLiteConnectionDidOpen?()
@@ -267,7 +268,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
let callback = db.busyCallback!
return callback(Int(numberOfTries)) ? 1 : 0
},
},
dbPointer)
}
}
@@ -310,7 +311,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
return SQLITE_OK
}
return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4)
},
},
dbPointer)
}
@@ -354,7 +355,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// This method must be called before database deallocation
func close() {
SchedulingWatchdog.preconditionValidQueue(self)
assert(!isClosed)
if isClosed {
return
}
configuration.SQLiteConnectionWillClose?(sqliteConnection)
internalStatementCache.clear()
@@ -398,7 +402,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
public var maximumStatementArgumentCount: Int {
Int(sqlite3_limit(sqliteConnection, SQLITE_LIMIT_VARIABLE_NUMBER, -1))
}
// MARK: - Functions
/// Add or redefine an SQL function.
@@ -442,7 +446,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
{ (collationPointer, length1, buffer1, length2, buffer2) -> Int32 in
let collation = Unmanaged<DatabaseCollation>.fromOpaque(collationPointer!).takeUnretainedValue()
return Int32(collation.function(length1, buffer1, length2, buffer2).rawValue)
}, nil)
}, nil)
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
@@ -487,18 +491,17 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// MARK: - Snapshots
/// Returns a snapshot that must be freed with `grdb_snapshot_free`.
///
#if SQLITE_ENABLE_SNAPSHOT
/// Returns a snapshot that must be freed with `sqlite3_snapshot_free`.
///
/// See https://www.sqlite.org/c3ref/snapshot.html
func takeVersionSnapshot() throws -> UnsafeMutablePointer<sqlite3_snapshot> {
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
let code = withUnsafeMutablePointer(to: &snapshot) {
grdb_snapshot_get(sqliteConnection, "main", $0)
sqlite3_snapshot_get(sqliteConnection, "main", $0)
}
guard code == SQLITE_OK else {
// Don't grab `lastErrorMessage`, because grdb_snapshot_get may be a
// shim that does not call the missing sqlite3_snapshot_get.
throw DatabaseError(resultCode: code)
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
if let snapshot = snapshot {
return snapshot
@@ -510,12 +513,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
func wasChanged(since initialSnapshot: UnsafeMutablePointer<sqlite3_snapshot>) throws -> Bool {
let secondSnapshot = try takeVersionSnapshot()
defer {
grdb_snapshot_free(secondSnapshot)
sqlite3_snapshot_free(secondSnapshot)
}
let cmp = grdb_snapshot_cmp(initialSnapshot, secondSnapshot)
let cmp = sqlite3_snapshot_cmp(initialSnapshot, secondSnapshot)
assert(cmp <= 0, "Unexpected snapshot ordering")
return cmp < 0
}
#endif
// MARK: - Authorizer
@@ -558,7 +562,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// // Trace all SQL statements executed by the database
/// var configuration = Configuration()
/// configuration.prepareDatabase = { db in
/// configuration.prepareDatabase { db in
/// db.trace(options: .statement) { event in
/// print("SQL: \(event)")
/// }
@@ -644,18 +648,20 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
switch mask {
case SQLITE_TRACE_STMT:
if let sqliteStatement = p, let unexpandedSQL = x {
let statement = TraceEvent.Statement(impl: .trace_v2(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
sqlite3_expanded_sql: sqlite3_expanded_sql))
let statement = TraceEvent.Statement(
impl: .trace_v2(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
sqlite3_expanded_sql: sqlite3_expanded_sql))
trace(TraceEvent.statement(statement))
}
case SQLITE_TRACE_PROFILE:
if let sqliteStatement = p, let durationP = x?.assumingMemoryBound(to: Int64.self) {
let statement = TraceEvent.Statement(impl: .trace_v2(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: nil,
sqlite3_expanded_sql: sqlite3_expanded_sql))
let statement = TraceEvent.Statement(
impl: .trace_v2(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: nil,
sqlite3_expanded_sql: sqlite3_expanded_sql))
let duration = TimeInterval(durationP.pointee) / 1.0e9
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
@@ -688,7 +694,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// in the log file
@discardableResult
public func checkpoint(_ kind: Database.CheckpointMode = .passive, on dbName: String? = "main") throws
-> (walFrameCount: Int, checkpointedFrameCount: Int)
-> (walFrameCount: Int, checkpointedFrameCount: Int)
{
SchedulingWatchdog.preconditionValidQueue(self)
var walFrameCount: CInt = -1
@@ -810,9 +816,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
return
}
if
let updateStatement = statement as? UpdateStatement,
updateStatement.releasesDatabaseLock
if let updateStatement = statement as? UpdateStatement,
updateStatement.releasesDatabaseLock
{
// Accept statements that release locks:
// - COMMIT
@@ -859,7 +864,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
func checkForAbortedTransaction(
sql: @autoclosure () -> String? = nil,
arguments: @autoclosure () -> StatementArguments? = nil)
throws
throws
{
if isInsideTransactionBlock && !isInsideTransaction {
throw DatabaseError(
@@ -1072,55 +1077,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
assert(isInsideTransaction)
}
/// Begins a database transaction and take a snapshot of the last committed
/// database state.
func beginSnapshotTransaction() 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(sql: "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
@@ -1209,13 +1165,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
return .commit
}
},
},
finally: {
// Restore foreign keys if needed
if foreignKeysEnabled {
try execute(sql: "PRAGMA foreign_keys = ON")
}
})
})
#else
try DatabaseQueue().backup(to: self)
#endif
@@ -1227,7 +1183,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
to dbDest: Database,
afterBackupInit: (() -> Void)? = nil,
afterBackupStep: (() -> Void)? = nil)
throws
throws
{
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", sqliteConnection, "main") else {
throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
@@ -1274,15 +1230,34 @@ extension Database {
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
///
/// Call this method from Configuration.prepareDatabase, as in the example below:
/// Call this method from `Configuration.prepareDatabase`,
/// as in the example below:
///
/// var config = Configuration()
/// config.prepareDatabase = { db in
/// config.prepareDatabase { db in
/// try db.usePassphrase("secret")
/// }
public func usePassphrase(_ passphrase: String) throws {
let data = passphrase.data(using: .utf8)!
let code = data.withUnsafeBytes {
guard var data = passphrase.data(using: .utf8) else {
throw DatabaseError(message: "invalid passphrase")
}
defer {
data.resetBytes(in: 0..<data.count)
}
try usePassphrase(data)
}
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
///
/// Call this method from `Configuration.prepareDatabase`,
/// as in the example below:
///
/// var config = Configuration()
/// config.prepareDatabase { db in
/// try db.usePassphrase(passphraseData)
/// }
public func usePassphrase(_ passphrase: Data) throws {
let code = passphrase.withUnsafeBytes {
sqlite3_key(sqliteConnection, $0.baseAddress, Int32($0.count))
}
guard code == SQLITE_OK else {
@@ -1292,6 +1267,17 @@ extension Database {
/// Changes the passphrase used by an SQLCipher encrypted database.
public func changePassphrase(_ passphrase: String) throws {
guard var data = passphrase.data(using: .utf8) else {
throw DatabaseError(message: "invalid passphrase")
}
defer {
data.resetBytes(in: 0..<data.count)
}
try changePassphrase(data)
}
/// Changes the passphrase used by an SQLCipher encrypted database.
public func changePassphrase(_ passphrase: Data) throws {
// FIXME: sqlite3_rekey is discouraged.
//
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
@@ -1302,8 +1288,7 @@ extension Database {
// > schema of the original db into the new one:
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
// swiftlint:disable:previous line_length
let data = passphrase.data(using: .utf8)!
let code = data.withUnsafeBytes {
let code = passphrase.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count))
}
guard code == SQLITE_OK else {
@@ -1525,9 +1510,9 @@ extension Database {
enum Impl {
case trace_v1(String)
case trace_v2(
sqliteStatement: SQLiteStatement,
unexpandedSQL: UnsafePointer<CChar>?,
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
sqliteStatement: SQLiteStatement,
unexpandedSQL: UnsafePointer<CChar>?,
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
}
let impl: Impl
+6 -7
View File
@@ -356,7 +356,6 @@ extension DatabaseError {
}
extension DatabaseError {
// TODO: test
/// Returns true if the error has code `SQLITE_ABORT` or `SQLITE_INTERRUPT`.
///
/// Such an error can be thrown when a database has been interrupted, or
@@ -379,15 +378,15 @@ extension DatabaseError {
/// :nodoc:
public var description: String {
var description = "SQLite error \(resultCode.rawValue)"
if let sql = sql {
description += " with statement `\(sql)`"
}
if let arguments = arguments, !arguments.isEmpty {
description += " arguments \(arguments)"
}
if let message = message {
description += ": \(message)"
}
if let sql = sql {
description += " - while executing `\(sql)`"
}
if let arguments = arguments, !arguments.isEmpty {
description += " with arguments \(arguments)"
}
return description
}
}
+3 -3
View File
@@ -75,8 +75,8 @@ public final class DatabaseFunction: Hashable {
///
/// let dbQueue = DatabaseQueue()
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
/// dbQueue.add(function: fn)
/// try dbQueue.write { db in
/// db.add(function: fn)
/// try db.execute(sql: "CREATE TABLE test(i)")
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
@@ -126,7 +126,7 @@ public final class DatabaseFunction: Hashable {
{ definitionP in
// Release the function definition
Unmanaged<AnyObject>.fromOpaque(definitionP!).release()
})
})
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
@@ -364,8 +364,8 @@ extension DatabaseFunction {
///
/// let dbQueue = DatabaseQueue()
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
/// dbQueue.add(function: fn)
/// try dbQueue.write { db in
/// db.add(function: fn)
/// try db.execute(sql: "CREATE TABLE test(i)")
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
+145 -141
View File
@@ -8,9 +8,6 @@ import UIKit
public final class DatabasePool: DatabaseWriter {
private let writer: SerializedDatabase
private var readerPool: Pool<SerializedDatabase>!
private var functions = Set<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
private var tokenizerRegistrations: [(Database) -> Void] = []
@LockedBox var databaseSnapshotCount = 0
@@ -50,51 +47,22 @@ public final class DatabasePool: DatabaseWriter {
purpose: "writer")
// Readers
var readerConfiguration = configuration
readerConfiguration.readonly = true
// Readers use deferred transactions by default.
// Other transaction kinds are forbidden by SQLite in read-only connections.
readerConfiguration.defaultTransactionKind = .deferred
var readerConfiguration = DatabasePool.readerConfiguration(configuration)
// Readers can't allow dangling transactions because there's no
// guarantee that one can get the same reader later in order to close
// an opened transaction.
readerConfiguration.allowsUnsafeTransactions = false
// https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode
// > But there are some obscure cases where a query against a WAL-mode
// > database can return SQLITE_BUSY, so applications should be prepared
// > for that happenstance.
// >
// > - If another database connection has the database mode open in
// > exclusive locking mode [...]
// > - When the last connection to a particular database is closing,
// > that connection will acquire an exclusive lock for a short time
// > while it cleans up the WAL and shared-memory files [...]
// > - If the last connection to a database crashed, then the first new
// > connection to open the database will start a recovery process. An
// > exclusive lock is held during recovery. [...]
//
// The whole point of WAL readers is to avoid SQLITE_BUSY, so let's
// setup a busy handler for pool readers, in order to workaround those
// "obscure cases" that may happen when the database is shared between
// multiple processes.
if readerConfiguration.readonlyBusyMode == nil {
readerConfiguration.readonlyBusyMode = .timeout(10)
}
var readerCount = 0
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
readerCount += 1 // protected by pool (TODO: document this protection behavior)
let reader = try SerializedDatabase(
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
return try SerializedDatabase(
path: path,
configuration: readerConfiguration,
schemaCache: DatabaseSchemaCache(),
defaultLabel: "GRDB.DatabasePool",
purpose: "reader.\(readerCount)")
reader.sync { self.setupDatabase($0) }
return reader
})
// Activate WAL Mode unless readonly
@@ -147,16 +115,40 @@ public final class DatabasePool: DatabaseWriter {
readerPool = nil
}
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)
/// Returns a Configuration suitable for readonly connections on a
/// WAL database.
static func readerConfiguration(_ configuration: Configuration) -> Configuration {
var configuration = configuration
configuration.readonly = true
// Readers use deferred transactions by default.
// Other transaction kinds are forbidden by SQLite in read-only connections.
configuration.defaultTransactionKind = .deferred
// https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode
// > But there are some obscure cases where a query against a WAL-mode
// > database can return SQLITE_BUSY, so applications should be prepared
// > for that happenstance.
// >
// > - If another database connection has the database mode open in
// > exclusive locking mode [...]
// > - When the last connection to a particular database is closing,
// > that connection will acquire an exclusive lock for a short time
// > while it cleans up the WAL and shared-memory files [...]
// > - If the last connection to a database crashed, then the first new
// > connection to open the database will start a recovery process. An
// > exclusive lock is held during recovery. [...]
//
// The whole point of WAL readers is to avoid SQLITE_BUSY, so let's
// setup a busy handler for pool readers, in order to workaround those
// "obscure cases" that may happen when the database is shared between
// multiple processes.
if configuration.readonlyBusyMode == nil {
configuration.readonlyBusyMode = .timeout(10)
}
return configuration
}
/// Blocks the current thread until all database connections have
@@ -322,8 +314,7 @@ 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.clearSchemaCache()
try db.clearSchemaCacheIfNeeded()
result = try block(db)
return .commit
}
@@ -369,9 +360,7 @@ extension DatabasePool: DatabaseReader {
do {
// The block isolation comes from the DEFERRED transaction.
try db.beginTransaction(.deferred)
// Reset the schema cache before running user code in snapshot isolation
db.clearSchemaCache()
try db.clearSchemaCacheIfNeeded()
block(.success(db))
} catch {
block(.failure(error))
@@ -380,7 +369,7 @@ extension DatabasePool: DatabaseReader {
} catch {
block(.failure(error))
}
}
}
}
/// :nodoc:
@@ -416,9 +405,7 @@ extension DatabasePool: DatabaseReader {
do {
// The block isolation comes from the DEFERRED transaction.
try db.beginTransaction(.deferred)
// Reset the schema cache before running user code in snapshot isolation
db.clearSchemaCache()
try db.clearSchemaCacheIfNeeded()
block(.success(db))
} catch {
block(.failure(error))
@@ -427,7 +414,7 @@ extension DatabasePool: DatabaseReader {
} catch {
block(.failure(error))
}
}
}
}
/// Synchronously executes a read-only block in a protected dispatch queue,
@@ -460,8 +447,7 @@ extension DatabasePool: DatabaseReader {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
return try readerPool.get { reader in
try reader.sync { db in
// Reset the schema cache
db.clearSchemaCache()
try db.clearSchemaCacheIfNeeded()
return try block(db)
}
}
@@ -500,8 +486,7 @@ extension DatabasePool: DatabaseReader {
} else {
return try readerPool.get { reader in
try reader.sync { db in
// Reset the schema cache
db.clearSchemaCache()
try db.clearSchemaCacheIfNeeded()
return try block(db)
}
}
@@ -592,19 +577,64 @@ extension DatabasePool: DatabaseReader {
releaseReader()
}
do {
try db.beginSnapshotTransaction()
// 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 from the reader
// SELECT ...
// UPDATE ... (2)
// Here the change (2) is not visible from the reader
//
// 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 ... (1)
// Here the change (1) is not visible from the reader
//
// Since any select goes, use `PRAGMA schema_version`.
try db.beginTransaction(.deferred)
try db.clearSchemaCacheIfNeeded()
} catch {
isolationSemaphore.signal()
block(.failure(error))
return
}
// Release the writer queue
// Now that we have an isolated snapshot of the last commit, we
// can release the writer queue.
isolationSemaphore.signal()
// Reset the schema cache before running user code in snapshot isolation
db.clearSchemaCache()
block(.success(db))
}
} catch {
@@ -718,7 +748,7 @@ extension DatabasePool: DatabaseReader {
public func writeInTransaction(
_ kind: Database.TransactionKind? = nil,
_ updates: (Database) throws -> Database.TransactionCompletion)
throws
throws
{
try writer.sync { db in
try db.inTransaction(kind) {
@@ -756,53 +786,6 @@ extension DatabasePool: DatabaseReader {
writer.weakAsync(updates)
}
// 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, sql: "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(sql: "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: - Database Observation
/// :nodoc:
@@ -810,7 +793,7 @@ extension DatabasePool: DatabaseReader {
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
-> DatabaseCancellable
-> DatabaseCancellable
{
if configuration.readonly {
return _addReadOnly(
@@ -840,7 +823,7 @@ extension DatabasePool: DatabaseReader {
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
-> ValueObserver<Reducer> // For testability
-> ValueObserver<Reducer> // For testability
{
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead")
@@ -891,6 +874,7 @@ extension DatabasePool: DatabaseReader {
//
// 3. Install the transaction observer.
#if SQLITE_ENABLE_SNAPSHOT
if scheduler.immediateInitialValue() {
do {
let initialSnapshot = try makeSnapshot()
@@ -919,12 +903,38 @@ extension DatabasePool: DatabaseReader {
} catch {
observer.notifyErrorAndComplete(error)
}
}
}
#else
if scheduler.immediateInitialValue() {
do {
let initialValue = try read(observer.fetchInitialValue)
onChange(initialValue)
addObserver(observer: observer)
} catch {
observer.complete()
observation.events.didFail?(error)
}
} else {
_weakAsyncRead { [weak self] dbResult in
guard let self = self, let dbResult = dbResult else { return }
if observer.isCompleted { return }
do {
let initialValue = try observer.fetchInitialValue(dbResult.get())
observer.notifyChange(initialValue)
self.addObserver(observer: observer)
} catch {
observer.notifyErrorAndComplete(error)
}
}
}
#endif
return observer
}
#if SQLITE_ENABLE_SNAPSHOT
// Support for _addConcurrent(observation:)
private func add<Reducer: ValueReducer>(
observer: ValueObserver<Reducer>,
@@ -941,20 +951,11 @@ extension DatabasePool: DatabaseReader {
// database versions. It prevents database checkpointing,
// and keeps versions (`sqlite3_snapshot`) valid
// and comparable.
let fetchNeeded: Bool = withExtendedLifetime(initialSnapshot) {
// Version is nil if SQLite is not compiled with
// SQLITE_ENABLE_SNAPSHOT, or if the DatabaseSnaphot
// could not grab its version. In this case, we don't
// care, and just fetch a fresh value.
let fetchNeeded: Bool = try withExtendedLifetime(initialSnapshot) {
guard let initialVersion = initialSnapshot.version else {
return true
}
do {
return try db.wasChanged(since: initialVersion)
} catch {
// ignore: we'll just re-fetch
return true
}
return try db.wasChanged(since: initialVersion)
}
if fetchNeeded {
@@ -973,20 +974,25 @@ extension DatabasePool: DatabaseReader {
}
}
}
// 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)
#else
// Support for _addConcurrent(observation:)
private func addObserver<Reducer: ValueReducer>(observer: ValueObserver<Reducer>) {
_weakAsyncWriteWithoutTransaction { db in
guard let db = db else { return }
if observer.isCompleted { return }
do {
observer.events.databaseDidChange?()
if let value = try observer.fetchValue(db) {
observer.notifyChange(value)
}
// Now we can start observation
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
observer.notifyErrorAndComplete(error)
}
}
tokenizerRegistrations.append(registerTokenizer)
forEachConnection(registerTokenizer)
}
#endif
}
@@ -1063,12 +1069,10 @@ extension DatabasePool {
}
}
let snapshot = try DatabaseSnapshot(
return try DatabaseSnapshot(
path: path,
configuration: writer.configuration,
defaultLabel: "GRDB.DatabasePool",
purpose: "snapshot.\($databaseSnapshotCount.increment())")
snapshot.read { setupDatabase($0) }
return snapshot
}
}
+2 -45
View File
@@ -349,7 +349,7 @@ extension DatabaseQueue {
public func inTransaction(
_ kind: Database.TransactionKind? = nil,
_ updates: (Database) throws -> Database.TransactionCompletion)
throws
throws
{
try writer.sync { db in
try db.inTransaction(kind) {
@@ -427,49 +427,6 @@ extension DatabaseQueue {
writer.weakAsync(updates)
}
// 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
/// }
/// dbQueue.add(function: fn)
/// try dbQueue.read { db in
/// try Int.fetchOne(db, sql: "SELECT succ(1)") // 2
/// }
public func add(function: DatabaseFunction) {
writer.sync { $0.add(function: function) }
}
/// Remove an SQL function.
public func remove(function: DatabaseFunction) {
writer.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)
/// }
/// dbQueue.add(collation: collation)
/// try dbQueue.write { db in
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
/// }
public func add(collation: DatabaseCollation) {
writer.sync { $0.add(collation: collation) }
}
/// Remove a collation.
public func remove(collation: DatabaseCollation) {
writer.sync { $0.remove(collation: collation) }
}
// MARK: - Database Observation
/// :nodoc:
@@ -477,7 +434,7 @@ extension DatabaseQueue {
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
-> DatabaseCancellable
-> DatabaseCancellable
{
if configuration.readonly {
return _addReadOnly(
Loaded 100 of 299 files, more files were not shown because too many files have changed in this diff. Show more