Compare commits

..
Author SHA1 Message Date
Gwendal Roué a88067a815 Merge branch 'GRDB5' into dev/hasMany-first 2020-04-25 13:31:58 +02:00
Gwendal Roué df4d5b8603 Back to basics, round 2: keep all children of firstOnly relations 2020-04-19 17:44:50 +02:00
Gwendal Roué a7b8a73dba Cleanup
After failed experiment:

SELECT ...
FROM parent
JOIN (SELECT * FROM child LIMIT 1) child ON child.parentId = child.id

The problem is that the join condition can't go inside the subquery, because SQLite complains about unknown table "parent". And when the join condition is outside the subquery, the LIMIT clause has been applied too early.

So we're still stuck with:

SELECT ...
FROM parent
JOIN child ON child.id = (SELECT id FROM child WHERE child.parentId = child.id LIMIT 1)

For some reason SQLite accepts the reference to the parent table in this case.
2020-04-19 14:14:13 +02:00
Gwendal Roué 278c18adfc Cleanup 2020-04-18 20:21:14 +02:00
Gwendal Roué cbd494e3b9 Documentation 2020-04-18 20:19:47 +02:00
Gwendal Roué c73fb0dd9b Back to basics 2020-04-18 20:14:27 +02:00
Gwendal Roué c966eb3ecf Cleanup 2020-04-18 19:09:02 +02:00
Gwendal Roué 217b0a3f3e More failing HasManyThrough.first tests 2020-04-18 17:52:50 +02:00
Gwendal Roué e604a10860 TODO 2020-04-18 17:06:29 +02:00
Gwendal Roué ac4f4c6611 Improve HasMany.first tests 2020-04-18 17:06:29 +02:00
Gwendal Roué 162da80e4f Attempt at expressing some todos 2020-04-18 17:06:29 +02:00
Gwendal Roué 315496928b More failing HasManyThrough.first 2020-04-18 17:06:29 +02:00
Gwendal Roué d82cbb6853 Improve HasManyThrough.first tests 2020-04-18 17:06:29 +02:00
Gwendal Roué 5fed231856 Simplify SQLAssociationCondition.filteringExpression 2020-04-18 17:06:29 +02:00
Gwendal Roué 45dfe7d7f1 More HasManyThrough.first tests 2020-04-18 17:06:29 +02:00
Gwendal Roué c7d1cca023 Ease testing SQL by ignoring white space 2020-04-18 17:06:29 +02:00
Gwendal Roué 615f4159d6 Rename firstInMany to firstOnly 2020-04-18 17:06:29 +02:00
Gwendal Roué 8057572357 Move firstInMany flag in SQLRelation 2020-04-18 17:06:29 +02:00
Gwendal Roué da63037948 Fix documentation 2020-04-18 17:06:29 +02:00
Gwendal Roué 2d3dafad7d Document first and last properties, set their association key 2020-04-18 17:06:29 +02:00
Gwendal Roué 7ed967b502 Cleanup SQLAssociationCardinality and SQLAssociationStep 2020-04-18 17:06:29 +02:00
Gwendal Roué f545789205 Avoid using the rowid column when we can use the regular primary key 2020-04-18 17:06:23 +02:00
Gwendal Roué 79373d5b74 Cleanup some old tests 2020-04-18 16:40:22 +02:00
Gwendal Roué f97088d63a Failing tests for HasManyThrough.first 2020-04-18 16:40:22 +02:00
Gwendal Roué 860faf19f7 HasManyThrough.first and last 2020-04-18 16:40:22 +02:00
Gwendal Roué 0f54779386 Isolate tests for hasMany.first 2020-04-18 16:40:22 +02:00
Gwendal Roué 6f125bd3d7 SQLAssociation.associationForFirst() 2020-04-18 16:40:22 +02:00
Gwendal Roué 4483f037a4 Cleanup 2020-04-18 16:40:22 +02:00
Gwendal Roué 20296652dd More test for hasMany.first including nested associations 2020-04-18 16:40:22 +02:00
Gwendal Roué d80922954a Let hasMany.first include nested associations 2020-04-18 16:40:22 +02:00
Gwendal Roué d67814ef61 Make sure hasMany.first doesn't lose information 2020-04-18 16:40:22 +02:00
Gwendal Roué fb550d30a0 HasManyAssociation.first and last 2020-04-18 16:40:22 +02:00
418 changed files with 16172 additions and 30970 deletions

No files matched your search

+1 -2
View File
@@ -2,9 +2,7 @@ included:
- GRDB
disabled_rules:
- comment_spacing
- cyclomatic_complexity
- duplicate_enum_cases
- file_length
- force_cast
- force_try
@@ -26,6 +24,7 @@ disabled_rules:
opt_in_rules:
- anyobject_protocol
- array_init
- attributes
- closure_spacing
- collection_alignment
- contains_over_filter_count
+108 -61
View File
@@ -28,134 +28,181 @@ jobs:
include:
###########################################
## Test GRDB Xcode 12.2
## Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.3"
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 5.1, macOS)
script: make test_framework_GRDBOSX_maxSwift
- name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.2"
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 4.2, macOS)
script: make test_framework_GRDBOSX_minSwift
- name: "Test GRDB Xcode 12.2 - GRDBWatchOS"
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=GRDBWatchOS (watchOS)
script: make test_framework_GRDBWatchOS
- name: "Test GRDB Xcode 12.2 - GRDBiOS iOS maxTarget"
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 12.2 - GRDBiOS iOS minTarget"
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_minSwift
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
- name: "Test GRDB Xcode 12.2 - GRDBtvOS maxTarget"
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 5.1, tvOS <MAX>)
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 12 - GRDBtvOS minTarget"
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
script: make test_framework_GRDBtvOS_maxTarget_minSwift
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 5.1, tvOS <MIN>)
script: make test_framework_GRDBtvOS_minTarget
- name: "Test GRDB Xcode 12.2 - SPM"
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=GRDB [SPM] (macOS)
script: make test_SPM
###########################################
## Test GRDBCustom Xcode 12.2
## Test GRDBCustom Xcode 11.4
- name: "Test GRDBCustom Xcode 12.2 - GRDBOSX"
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 5.1, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
- name: "Test GRDBCustom Xcode 12.2 - GRDBiOS maxTarget"
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
- name: "Test GRDBCustom Xcode 12.2 - GRDBiOS minTarget"
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test SQLCipher Xcode 12.2
## Test SQLCipher Xcode 11.4
- name: "Test SQLCipher Xcode 12.2 - SQLCipher 3"
- stage: Test SQLCipher Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=SQLCipher 3
script: make test_framework_SQLCipher3
- name: "Test SQLCipher Xcode 12.2 - SQLCipher 4"
- stage: Test SQLCipher Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=SQLCipher 4
script: make test_framework_SQLCipher4
###########################################
## Test Installation Xcode 12.2
## Test Installation Xcode 11.4
# Manual Install
- name: "Test Installation Xcode 12.2 - Manual Install"
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=Manual Install
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 Lint
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=CocoaPods Lint
script: make test_CocoaPodsLint_GRDB
# CocoaPods Install GRDB
- name: "Test Installation Xcode 12.2 - CocoaPods Framework"
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=CocoaPods GRDB (framework)
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- name: "Test Installation Xcode 12.2 - CocoaPods Static"
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=CocoaPods GRDB (static)
script: make test_install_GRDB_CocoaPods_static
# SPM Install
- name: "Test Installation Xcode 12.2 - SPM Package"
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=SPM Package
script: make test_install_SPM_Package
# SPM Install
- name: "Test Installation Xcode 12.2 - SPM Package in Xcode Project"
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=SPM Package in Xcode Project
script: make test_install_SPM_Project
# Custom SQLite Install
- name: "Test Installation Xcode 12.2 - Custom SQLite"
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
osx_image: xcode11.4
env:
- TID=Custom SQLite
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
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 11.4 - GRDBiOS iOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_framework_GRDBiOS_minTarget
-30
View File
@@ -4,36 +4,6 @@ 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
---
https://twitter.com/_maxheld/status/1266509824994553860
> I tried out GRDB since I saw you mention it a few days ago and absolutely love it. It’s so nice and testing the database logic is so much nicer than CoreData
---
https://twitter.com/stephencelis/status/1263518304980918274
> GRDB.swift is great! (I say this as the person that started SQLite.swift long ago.) And @groue’s very helpful and friendly.
---
https://twitter.com/peres/status/1262682199482142720
> GRDB in already in my top3 when it comes to documentation. Clearly and pragmatically explained.
---
https://twitter.com/layoutsubviews/status/1249940744929816582
> Mixing SQLite / GRDB with Combine is my whole world right now, and it is delightful.
+16 -281
View File
@@ -5,13 +5,16 @@ 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.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)
- `5.0.x` Development - [GRDB5 Branch](#grdb5-branch)
#### 4.x Releases
@@ -69,279 +72,18 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- [0.110.0](#01100), ...
## 5.3.0
<!--
## Next Release
-->
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
Released July 19, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.7...v5.0.0-beta.8)
- **New**: [#811](https://github.com/groue/GRDB.swift/pull/811): Introduce RenameColumnAdapter
## 5.0.0-beta.7
Released July 14, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.6...v5.0.0-beta.7)
- **New**: [#802](https://github.com/groue/GRDB.swift/pull/802) by [@GetToSet](https://github.com/GetToSet): Add tokenchars support for ascii tokenizer in FTS5
- **New**: `fetchSet` has joined `fetchCursor`, `fetchAll` and `fetchOne` in the group of universal fetching methods.
- **Breaking Change**: [#803](https://github.com/groue/GRDB.swift/pull/803): Remove FetchedRecordsController
- **Breaking Change**: Removed `TableRecord.primaryKey` and `selectPrimaryKey(as:)` introduced in 5.0.0-beta.5
- **Breaking Change**: 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.
- **Breaking Change**: Defining custom `FetchRequest` types is no longer supported.
- **Breaking Change**: Defining custom `RowAdapter` types is no longer supported.
- **Fixed**: Fix rare occurences of an `SQLITE_BUSY` error when opening a DatabaseSnapshot.
- **Fixed**: Work around an SQLite bug which prevents rollbacking a transaction with `sqlite3_commit_hook`.
- The [How do I filter records and only keep those that are NOT associated to another record?](README.md#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) FAQ has been updated.
## 5.0.0-beta.6
Released June 29, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.5...v5.0.0-beta.6)
- **New**: [#798](https://github.com/groue/GRDB.swift/pull/798): Debugging operators for ValueObservation
- **New**: [#800](https://github.com/groue/GRDB.swift/pull/800): Xcode 12 support
- **New**: [#801](https://github.com/groue/GRDB.swift/pull/801): Combine support
- **New**: Faster decoding of Date and DateComponents
## GRDB5 Branch
### Documentation Diff
- The [ValueObservation Operators](README.md#valueobservation-operators) chapter was extended with a description of the two new debugging operators `handleEvents` and `print`.
- A new [GRDB ❤️ Combine](Documentation/Combine.md) guide describes the various Combine publishers that read, write, and observe the database.
- [GRDBCombineDemo](Documentation/DemoApps/GRDBCombineDemo/README.md) is a new Combine + SwiftUI demo application.
## 5.0.0-beta.5
Released June 15, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.4...v5.0.0-beta.5)
- **Breaking Change** [#795](https://github.com/groue/GRDB.swift/pull/795): Enhanced support for WAL Checkpoints
- **New**: `Database.maximumStatementArgumentCount` returns the maximum number of arguments accepted by an SQLite statement.
- **New**: Optimize DatabasePool handling of ValueObservation when SQLite is compiled with the SQLITE_ENABLE_SNAPSHOT option. We are now able to avoid fetching the observed value when we can prove that the database wasn't changed between the initial fetch and the beginning of transaction tracking. This optimization avoids duplicate notifications.
- **New**: The query interface now exposes the primary key through `TableRecord.primaryKey`, as well as the `selectPrimaryKey(as:)` method.
### Documentation Diff
- The [Demo Application](Documentation/DemoApps/GRDBDemoiOS) was updated for better conformance with the [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) Guide.
- A new [FAQ: Associations](README.md#faq-associations) addresses three frequent questions:
- [How do I filter records and only keep those that are associated to another record?](README.md#how-do-i-filter-records-and-only-keep-those-that-are-associated-to-another-record)
- [How do I filter records and only keep those that are NOT associated to another record?](README.md#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record)
- [How do I select only one column of an associated record?](README.md#how-do-i-select-only-one-column-of-an-associated-record)
- The guide for [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) now recommends enabling the `SQLITE_ENABLE_SNAPSHOT` option.
## 5.0.0-beta.4
Released June 6, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.3...v5.0.0-beta.4)
### Documentation Diff
- [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) was updated for RxGRDB and GRDBCombine 1.0 beta 2, which haved change their way to configure how ValueObservation schedules fresh database values.
- The [SQL Functions](README.md#sql-functions) chapter was updated for the new `julianDay` and `dateTime` functions.
### New
- [#794](https://github.com/groue/GRDB.swift/pull/794): Name of Database Connections
- Add the `julianDay` and `dateTime` functions
## 5.0.0-beta.3
Released June 1, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.2...v5.0.0-beta.3)
### Documentation Diff
- Updated FAQ: [How do I print a request as SQL?](README.md#how-do-i-print-a-request-as-sql)
- New FAQ: [How do I monitor the duration of database statements execution?](README.md#how-do-i-monitor-the-duration-of-database-statements-execution)
### Fixed
- [#784](https://github.com/groue/GRDB.swift/pull/784): Fix observation of eager-loaded to-many associations
### Breaking Changes
- [#790](https://github.com/groue/GRDB.swift/pull/790): Bump required iOS version to 10.0
- [#791](https://github.com/groue/GRDB.swift/pull/791): Extend tracing of statement execution
## 5.0.0-beta.2
Released May 11, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta...v5.0.0-beta.2)
### Documentation Diff
- [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) describes the sunsetting of custom `FetchRequest` types.
- The [Sharing a Database](Documentation/SharingADatabase.md) guide has an updated recommendation for opening writer connections to a shared database.
### New
- [#772](https://github.com/groue/GRDB.swift/pull/772): Update the Database Sharing Guide with mention of the persistent WAL mode
- [#775](https://github.com/groue/GRDB.swift/pull/775): DatabaseMigrator can check if it has been superseded
### Breaking Changes
- [#774](https://github.com/groue/GRDB.swift/pull/774): All requests are usable as SQL expressions and collections
### Fixed
- [#773](https://github.com/groue/GRDB.swift/pull/773): Allow subqueries to refer to outer tables
## 5.0.0-beta
Released May 2, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v4.14.0...v5.0.0-beta)
GRDB 5 is a release focused on **Swift 5.2**, and **removing technical debt**.
There are breaking changes, though as few as possible. They open the door for future library improvements. And they have GRDB, [GRDBCombine](http://github.com/groue/GRDBCombine), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) offer a common behavior.
New features include support for SQL subqueries, and a simplified handling of database errors. The most demanding users will also find it easier to switch between the system SQLite, SQLCipher, and custom SQLite builds.
<details>
<summary>A glimpse on the new features</summary>
All requests can now be used as subqueries:
```swift
// Define a request with the query interface or raw SQL
let maximumScore = Player.select(max(Column("score")))
let maximumScore: SQLRequest<Int> = "SELECT MAX(score) FROM player"
// Use the request as a subquery in the query interface
let request = Player.filter(Column("score") == maximumScore)
let bestPlayers = try request.fetchAll(db)
// Use the request as a subquery in SQL requests
let request: SQLRequest<Player> = "SELECT * FROM player WHERE score = (\(maximumScore))"
let bestPlayers = try request.fetchAll(db)
```
Catch specific SQLite error codes in a simplified fashion:
```swift
do {
try ...
} catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY {
// foreign key constraint error
} catch DatabaseError.SQLITE_CONSTRAINT {
// any other constraint error
} catch {
// any other database error
}
```
Reuse the same code for system SQLite, SQLCipher, and custom SQLite builds:
```swift
// Supported in all GRDB flavors
import GRDB
let sqliteVersion = String(cString: sqlite3_libversion())
```
</details>
### Documentation Diff
- **[Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)**: how to upgrade your apps, and deal with breaking changes.
- [ValueObservation](README.md#valueobservation): this chapter describes the new ValueObservation behaviors.
- [DatabaseError](README.md#databaseerror): learn how to catch and match DatabaseError on their codes, in a fashion similar to `CocoaError`.
- [Batch Updates](README.md#update-requests): this chapter is updated for the new `set(to:)` method.
- [SQL Operators](README.md#sql-operators): introduces support for SQL and query interface subqueries.
- [How do I print a request as SQL?](README.md#how-do-i-print-a-request-as-sql) This FAQ was updated for GRDB 5.
- [SQL Interpolation](Documentation/SQLInterpolation.md): this guide now describes how to embed subqueries and record columns in your SQL literals.
- [Joined Queries Support](README.md#joined-queries-support): describes the GRDB 5 way of dealing with complex and hand-crafted SQL queries.
- [Raw SQLite Pointers](README.md#raw-sqlite-pointers) and [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md): `import GRDB` now provides access to the full [C SQLite API](https://www.sqlite.org/capi3ref.html), and custom SQLite builds.
- The [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) Guide helps migrating your apps and turn your attention where it needs to focus during the upgrade.
- The [ValueObservation](README.md#valueobservation) chapter has been fully rewritten and describes the new ValueObservation behaviors.
- The [DatabaseError](README.md#databaseerror) chapter demonstrates the new way to catch and match DatabaseError on their codes, in a fashion similar to CocoaError et al.
- The [Batch Updates](README.md#update-requests) chapter has been updated for the new `set(to:)` method.
### New
@@ -366,13 +108,6 @@ let sqliteVersion = String(cString: sqlite3_libversion())
- [#747](https://github.com/groue/GRDB.swift/pull/747): Rename GRDBCustomSQLite to GRDB
- [#750](https://github.com/groue/GRDB.swift/pull/750): Batch updates do not need any operator
- [#752](https://github.com/groue/GRDB.swift/pull/752): Remove ValueObservation.combine
- [#770](https://github.com/groue/GRDB.swift/pull/770): Subqueries
### Fixed
- [#601](https://github.com/groue/GRDB.swift/pull/601): ValueObservation won't start until concurrent write transaction has ended
- [#697](https://github.com/groue/GRDB.swift/pull/697): `SQLInterpolation` could not work with `QueryInterfaceRequest`
- [#743](https://github.com/groue/GRDB.swift/pull/743): Rename GRDBCustomSQLite to GRDB for compatibility with dependents?
## 4.14.0
+11
View File
@@ -82,6 +82,7 @@ The ideas, in alphabetical order:
- [JSON]
- [Linux]
- [More SQL Generation]
- [Reactive Database Observation]
- [SQL Console in the Debugger]
- [SQLCipher in a Shared App Container]
- [Typed Expressions]
@@ -246,6 +247,15 @@ There are several SQLite features that GRDB could natively support:
See [issue #575](https://github.com/groue/GRDB.swift/issues/575) for more information and guidance about the implementation of extra table alterations.
### Reactive Database Observation
:baby: Starter Task
We already have the [GRDBCombine](http://github.com/groue/GRDBCombine) and [RxGRDB] companion libraries.
More choices of reactive engines would help more developers enjoy GRDB.
### SQL Console in the Debugger
:question: Unknown Difficulty :hammer: Tooling
@@ -309,6 +319,7 @@ Features that blur this focus are non-goals:
[JSON]: #json
[Linux]: #linux
[More SQL Generation]: #more-sql-generation
[Reactive Database Observation]: #reactive-database-observation
[Records: Splitting Database Encoding from Ability to Write in the Database]: #records-splitting-database-encoding-from-ability-to-write-in-the-database
[Non-Goals]: #non-goals
[Report Bugs]: #report-bugs
+247 -1
View File
@@ -1,4 +1,250 @@
Sharing a Database in an App Group Container
============================================
This guide [has moved](SharingADatabase.md).
On iOS, you can share database files between multiple processes by storing them in an [App Group Container](https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati).
A shared database is accessed from several SQLite connections, from several processes. This creates challenges at various levels:
1. **Database setup** may be attempted by multiple processes, concurrently.
2. **SQLite** may throw `SQLITE_BUSY` errors, code 5, "database is locked".
3. **iOS** may kill your application with a `0xDEAD10CC` exception.
4. **GRDB** database observation misses changes performed by external processes.
We'll address all of those challenges below.
- [Use a Database Pool]
- [How to limit the `SQLITE_BUSY` error]
- [How to limit the `0xDEAD10CC` exception]
- [How to perform cross-process database observation]
## Use a Database Pool
In order to access a shared database, use a [Database Pool]. It opens the database in the [WAL mode](https://www.sqlite.org/wal.html), which helps sharing a database.
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
- In a process that can create and write in the database, use this sample code:
```swift
/// Returns an initialized database pool at the shared location databaseURL
func openSharedDatabase(at databaseURL: URL) throws -> DatabasePool {
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var dbPool: DatabasePool?
var dbError: Error?
coordinator.coordinate(writingItemAt: databaseURL, options: .forMerging, error: &coordinatorError, byAccessor: { url in
do {
dbPool = try openDatabase(at: url)
} catch {
dbError = error
}
})
if let error = dbError ?? coordinatorError {
throw error
}
return dbPool!
}
private func openDatabase(at databaseURL: URL) throws -> DatabasePool {
let dbPool = try DatabasePool(path: databaseURL.path)
// Perform here other database setups, such as defining
// the database schema with a DatabaseMigrator.
try migrator.migrate(dbPool)
return dbPool
}
```
- In a process that only reads in the database, use this sample code:
```swift
/// Returns an initialized database pool at the shared location databaseURL,
/// or nil if the database is not created yet, or does not have the required
/// schema version.
func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var dbPool: DatabasePool?
var dbError: Error?
coordinator.coordinate(readingItemAt: databaseURL, options: .withoutChanges, error: &coordinatorError, byAccessor: { url in
do {
dbPool = try openReadOnlyDatabase(at: url)
} catch {
dbError = error
}
})
if let error = dbError ?? coordinatorError {
throw error
}
return dbPool
}
private func openReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
do {
var configuration = Configuration()
configuration.readonly = true
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
// Check here if the database schema is correct, for example
// with a DatabaseMigrator.
if try dbPool.read(migrator.hasCompletedMigrations) {
return dbPool
} else {
return nil
}
} catch {
if FileManager.default.fileExists(atPath: databaseURL.path) {
throw error
} else {
return nil
}
}
}
```
## How to limit the `SQLITE_BUSY` error
> The SQLITE_BUSY result code indicates that the database file could not be written (or in some cases read) because of concurrent activity by some other database connection, usually a database connection in a separate process.
See https://www.sqlite.org/rescode.html#busy for more information about this error.
If several processes want to write in the database, configure the database pool of each process that wants to write:
```swift
var configuration = Configuration()
configuration.busyMode = .timeout(/* a TimeInterval */)
configuration.defaultTransactionKind = .immediate
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
With such a setup, you may still get `SQLITE_BUSY` (5, "database is locked") errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout.
```swift
do {
try dbPool.write { db in ... }
} catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY {
// Another process won't let you write. Deal with it.
}
```
> :bulb: **Tip**: In order to be nice to other processes, measure the duration of your longest writes, and attempt at optimizing the ones that last for too long.
## How to limit the `0xDEAD10CC` exception
> The exception code 0xDEAD10CC indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension.
See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for more information about this exception.
1. If you use SQLCipher, use SQLCipher 4+, and call the `cipher_plaintext_header_size` pragma from your database preparation function:
```swift
var configuration = Configuration()
configuration.prepareDatabase = { (db: Database) in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA cipher_plaintext_header_size = 32")
}
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
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:
Set the `observesSuspensionNotifications` configuration flag:
```swift
var configuration = Configuration()
configuration.suspendsOnBackgroundTimeExpiration = true
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
Post `Database.suspendNotification` when the application is about to be [suspended](https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle). You can for example post this notification from `UIApplicationDelegate.applicationDidEnterBackground(_:)`, or in the expiration handler of a [background task](https://forums.developer.apple.com/thread/85066).
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationDidEnterBackground(_ application: UIApplication) {
// Suspend databases
NotificationCenter.default.post(name: Database.suspendNotification, object: self)
}
}
```
Post `Database.resumeNotification` from `UIApplicationDelegate.applicationWillEnterForeground(_:)` (or `SceneDelegate.sceneWillEnterForeground(_:)` for scene-based applications):
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationWillEnterForeground(_ application: UIApplication) {
// Resume databases
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
}
}
```
If the application uses the background modes supported by iOS, post `Database.resumeNotification` method from each and every background mode callback that may use the database. For example, if your application supports background fetches:
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// Resume databases
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
// Proceed with background fetch
...
}
}
```
Suspended databases greatly reduce the odds of `0xDEAD10CC` exception are greatly reduced. 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.
You can catch those errors:
```swift
do {
try dbPool.write { db in ... }
} catch let error as DatabaseError where error.isInterruptionError {
// Oops, the database is suspended.
// Maybe try again after database is resumed?
}
```
## How to perform cross-process database observation
GRDB [Database Observation] features, as well as [GRDBCombine] and [RxGRDB], are not able to notify database changes performed by other processes.
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
You can trigger those notifications automatically with [DatabaseRegionObservation]:
```swift
// Notify all changes made to the "player" and "team" database tables
let observation = DatabaseRegionObservation(tracking: Player.all(), Team.all())
let observer = try observation.start(in: dbPool) { (db: Database) in
// Notify other processes
}
// Notify all changes made to the database
let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase)
let observer = try observation.start(in: dbPool) { (db: Database) in
// Notify other processes
}
```
[Use a Database Pool]: #use-a-database-pool
[How to limit the `SQLITE_BUSY` error]: #how-to-limit-the-sqlite_busy-error
[How to limit the `0xDEAD10CC` exception]: #how-to-limit-the-0xdead10cc-exception
[How to perform cross-process database observation]: #how-to-perform-cross-process-database-observation
[Database Pool]: ../README.md#database-pools
[Database Observation]: ../README.md#database-changes-observation
[GRDBCombine]: http://github.com/groue/GRDBCombine
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
+23 -39
View File
@@ -11,7 +11,6 @@ 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]
@@ -40,14 +39,7 @@ GRDB Associations
- [Aggregate Operations]
- [Isolation of Multiple Aggregates]
- [DerivableRequest Protocol]
**[FAQ]**
- [How do I filter records and only keep those that are associated to another record?](../README.md#how-do-i-filter-records-and-only-keep-those-that-are-associated-to-another-record)
- [How do I filter records and only keep those that are NOT associated to another record?](../README.md#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record)
- [How do I select only one column of an associated record?](../README.md#how-do-i-select-only-one-column-of-an-associated-record)
**[Known Issues]**
- [Known Issues]
## Associations Benefits
@@ -117,7 +109,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 *much more efficient*:
As for loading all pairs of books and authors, it is not only easier, but also *far much efficient*:
```swift
struct BookInfo: FetchableRecord, Decodable {
@@ -192,21 +184,18 @@ Generally speaking, associations use the [TableRecord], [FetchableRecord], and [
The Types of Associations
=========================
GRDB handles several types of associations:
GRDB handles five types of associations:
- **BelongsTo**
- **HasMany**
- **HasOne**
- **HasManyThrough**
- **HasOneThrough**
- **Associations to common table expressions**
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.
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.
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]
@@ -697,7 +686,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, because the database schema defines a foreign key between the book and author database tables (see [Convention for the BelongsTo Association]).
In the example below, the `book.authorId` column is automatically used to link a book to its author:
![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/master/Documentation/Images/Associations2/BelongsToSchema.svg)
@@ -711,9 +700,7 @@ struct Author: TableRecord {
}
```
> :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.
But this requires the database schema to define a foreign key between the book and author database tables (see [Convention for the BelongsTo Association]).
Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another.
@@ -1843,7 +1830,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
}
// SELECT author.*,
// COUNT(DISTINCT book.id) AS bookCount,
// COUNT(DISTINCT book.rowid) AS bookCount,
// MAX(book.year) AS maxBookYear,
// FROM author
// LEFT JOIN book ON book.authorId = author.id
@@ -1936,7 +1923,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
FROM author
LEFT JOIN book ON book.authorId = author.id
GROUP BY author.id
HAVING COUNT(DISTINCT book.id) = 0
HAVING COUNT(DISTINCT book.rowid) = 0
```
</details>
@@ -1955,7 +1942,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
FROM author
LEFT JOIN book ON book.authorId = author.id
GROUP BY author.id
HAVING COUNT(DISTINCT book.id) > 0
HAVING COUNT(DISTINCT book.rowid) > 0
```
</details>
@@ -1974,7 +1961,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
FROM author
LEFT JOIN book ON book.authorId = author.id
GROUP BY author.id
HAVING COUNT(DISTINCT book.id) >= 2
HAVING COUNT(DISTINCT book.rowid) >= 2
```
</details>
@@ -2012,7 +1999,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
FROM author
LEFT JOIN book ON book.authorId = author.id AND book.kind = 'novel'
GROUP BY author.id
HAVING COUNT(DISTINCT book.id) > 0
HAVING COUNT(DISTINCT book.rowid) > 0
```
</details>
@@ -2033,7 +2020,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
LEFT JOIN book ON book.authorId = author.id
LEFT JOIN painting ON painting.authorId = author.id
GROUP BY author.id
HAVING COUNT(DISTINCT book.id) > COUNT(DISTINCT painting.id)
HAVING COUNT(DISTINCT book.rowid) > COUNT(DISTINCT painting.rowid)
```
</details>
@@ -2053,7 +2040,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
LEFT JOIN book ON book.authorId = author.id
LEFT JOIN painting ON painting.authorId = author.id
GROUP BY author.id
HAVING ((COUNT(DISTINCT book.id) = 0) AND (COUNT(DISTINCT painting.id) > 0))
HAVING ((COUNT(DISTINCT book.rowid) = 0) AND (COUNT(DISTINCT painting.rowid) > 0))
```
</details>
@@ -2078,7 +2065,7 @@ Aggregates can be modified and combined with Swift operators:
LEFT JOIN book ON book.authorId = author.id
LEFT JOIN painting ON painting.authorId = author.id
GROUP BY author.id
HAVING ((COUNT(DISTINCT book.id) = 0) AND (COUNT(DISTINCT painting.id) = 0))
HAVING ((COUNT(DISTINCT book.rowid) = 0) AND (COUNT(DISTINCT painting.rowid) = 0))
```
</details>
@@ -2114,8 +2101,8 @@ Aggregates can be modified and combined with Swift operators:
```sql
SELECT author.*,
(COUNT(DISTINCT book.id) +
COUNT(DISTINCT painting.id)) AS workCount
(COUNT(DISTINCT book.rowid) +
COUNT(DISTINCT painting.rowid)) AS workCount
FROM author
LEFT JOIN book ON book.authorId = author.id
LEFT JOIN painting ON painting.authorId = author.id
@@ -2196,7 +2183,7 @@ In this other example, the `Author.books` and `Author.paintings` have the distin
```sql
SELECT author.*,
(COUNT(DISTINCT book.id) + COUNT(DISTINCT painting.id)) AS workCount
(COUNT(DISTINCT book.rowid) + COUNT(DISTINCT painting.rowid)) AS workCount
FROM author
LEFT JOIN book ON book.authorId = author.id
LEFT JOIN painting ON painting.authorId = author.id
@@ -2231,8 +2218,8 @@ But in the following example, we use the same association `Author.books` twice,
```sql
SELECT author.*,
COUNT(DISTINCT book1.id) AS novelCount,
COUNT(DISTINCT book2.id) AS theatrePlayCount
COUNT(DISTINCT book1.rowid) AS novelCount,
COUNT(DISTINCT book2.rowid) AS theatrePlayCount
FROM author
LEFT JOIN book book1 ON book1.authorId = author.id AND book1.kind = 'novel'
LEFT JOIN book book2 ON book2.authorId = author.id AND book2.kind = 'theatrePlay'
@@ -2271,8 +2258,8 @@ But in the following example, we use the same association `Author.books` twice,
```sql
SELECT author.*,
COUNT(DISTINCT book.id) AS novelCount,
COUNT(DISTINCT book.id) AS theatrePlayCount
COUNT(DISTINCT book.rowid) AS novelCount,
COUNT(DISTINCT book.rowid) AS theatrePlayCount
FROM author
LEFT JOIN book ON book.authorId = author.id
AND (book.kind = 'novel' AND book.kind = 'theatrePlay')
@@ -2379,7 +2366,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.
---
@@ -2435,7 +2422,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Ordered Associations]: #ordered-associations
[The Types of Associations]: #the-types-of-associations
[FetchableRecord]: ../README.md#fetchablerecord-protocols
[migration]: Migrations.md
[migration]: ../README.md#migrations
[Record]: ../README.md#records
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
[Associations and the Database Schema]: #associations-and-the-database-schema
@@ -2481,6 +2468,3 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[persistence methods]: ../README.md#persistence-methods
[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
-328
View File
@@ -1,328 +0,0 @@
GRDB ❤️ Combine
===============
**On systems supporting the Combine framework, GRDB offers the ability to publish database values and events using Combine's publishers.**
- [Usage]
- [Demo Application]
- [Asynchronous Database Access]
- [Database Observation]
## Usage
To connect to the database, please refer to [Database Connections].
<details>
<summary><strong>Asynchronously read from the database</strong></summary>
This publisher reads a single value and delivers it.
```swift
// DatabasePublishers.Read<[Player]>
let players = dbQueue.readPublisher { db in
try Player.fetchAll(db)
}
```
</details>
<details>
<summary><strong>Asynchronously write in the database</strong></summary>
This publisher updates the database and delivers a single value.
```swift
// DatabasePublishers.Write<Void>
let write = dbQueue.writePublisher { db in
try Player(...).insert(db)
}
// DatabasePublishers.Write<Int>
let newPlayerCount = dbQueue.writePublisher { db -> Int in
try Player(...).insert(db)
return try Player.fetchCount(db)
}
```
</details>
<details>
<summary><strong>Observe changes in database values</strong></summary>
This publisher delivers fresh values whenever the database changes:
```swift
// A publisher with output [Player] and failure Error
let publisher = ValueObservation
.tracking { db in try Player.fetchAll(db) }
.publisher(in: dbQueue)
// A publisher with output Int? and failure Error
let publisher = ValueObservation
.tracking { db in try Int.fetchOne(db, sql: "SELECT MAX(score) FROM player") }
.publisher(in: dbQueue)
```
</details>
<details>
<summary><strong>Observe database transactions</strong></summary>
This publisher delivers database connections whenever a database transaction has impacted an observed region:
```swift
// A publisher with output Database and failure Error
let publisher = DatabaseRegionObservation
.tracking(Player.all())
.publisher(in: dbQueue)
let cancellable = publisher.sink(
receiveCompletion: { completion in ... },
receiveValue: { (db: Database) in
print("Exclusive write access to the database after players have been impacted")
})
// A publisher with output Database and failure Error
let publisher = DatabaseRegionObservation
.tracking(SQLRequest<Int>(sql: "SELECT MAX(score) FROM player"))
.publisher(in: dbQueue)
let cancellable = publisher.sink(
receiveCompletion: { completion in ... },
receiveValue: { (db: Database) in
print("Exclusive write access to the database after maximum score has been impacted")
})
```
</details>
# Asynchronous Database Access
GRDB provide publishers that perform asynchronous database accesses.
- [`readPublisher(receiveOn:value:)`]
- [`writePublisher(receiveOn:updates:)`]
- [`writePublisher(receiveOn:updates:thenRead:)`]
#### `DatabaseReader.readPublisher(receiveOn:value:)`
This methods returns a publisher that completes after database values have been asynchronously fetched.
```swift
// DatabasePublishers.Read<[Player]>
let players = dbQueue.readPublisher { db in
try Player.fetchAll(db)
}
```
Any attempt at modifying the database completes subscriptions with an error.
When you use a [database queue] or a [database snapshot], the read has to wait for any eventual concurrent database access performed by this queue or snapshot to complete.
When you use a [database pool], reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured].
This publisher can be subscribed from any thread. A new database access starts on every subscription.
The fetched value is published on the main queue, unless you provide a specific scheduler to the `receiveOn` argument.
#### `DatabaseWriter.writePublisher(receiveOn:updates:)`
This method returns a publisher that completes after database updates have been successfully executed inside a database transaction.
```swift
// DatabasePublishers.Write<Void>
let write = dbQueue.writePublisher { db in
try Player(...).insert(db)
}
// DatabasePublishers.Write<Int>
let newPlayerCount = dbQueue.writePublisher { db -> Int in
try Player(...).insert(db)
return try Player.fetchCount(db)
}
```
This publisher can be subscribed from any thread. A new database access starts on every subscription.
It completes on the main queue, unless you provide a specific [scheduler] to the `receiveOn` argument.
When you use a [database pool], and your app executes some database updates followed by some slow fetches, you may profit from optimized scheduling with [`writePublisher(receiveOn:updates:thenRead:)`]. See below.
#### `DatabaseWriter.writePublisher(receiveOn:updates:thenRead:)`
This method returns a publisher that completes after database updates have been successfully executed inside a database transaction, and values have been subsequently fetched:
```swift
// DatabasePublishers.Write<Int>
let newPlayerCount = dbQueue.writePublisher(
updates: { db in try Player(...).insert(db) }
thenRead: { db, _ in try Player.fetchCount(db) })
}
```
It publishes exactly the same values as [`writePublisher(receiveOn:updates:)`]:
```swift
// DatabasePublishers.Write<Int>
let newPlayerCount = dbQueue.writePublisher { db -> Int in
try Player(...).insert(db)
return try Player.fetchCount(db)
}
```
The difference is that the last fetches are performed in the `thenRead` function. This function accepts two arguments: a readonly database connection, and the result of the `updates` function. This allows you to pass information from a function to the other (it is ignored in the sample code above).
When you use a [database pool], this method applies a scheduling optimization: the `thenRead` function sees the database in the state left by the `updates` function, and yet does not block any concurrent writes. This can reduce database write contention. See [Advanced DatabasePool](../README.md#advanced-databasepool) for more information.
When you use a [database queue], the results are guaranteed to be identical, but no scheduling optimization is applied.
This publisher can be subscribed from any thread. A new database access starts on every subscription.
It completes on the main queue, unless you provide a specific [scheduler] to the `receiveOn` argument.
# Database Observation
Database Observation publishers are based on [ValueObservation] and [DatabaseRegionObservation]. Please refer to their documentation for more information. If your application needs change notifications that are not built as Combine publishers, check the general [Database Changes Observation] chapter.
- [`ValueObservation.publisher(in:scheduling:)`]
- [`DatabaseRegionObservation.publisher(in:)`]
#### `ValueObservation.publisher(in:scheduling:)`
[ValueObservation] tracks changes in database values. You can turn it into a Combine publisher:
```swift
let observation = ValueObservation.tracking { db in
try Player.fetchAll(db)
}
// A publisher with output [Player] and failure Error
let publisher = observation.publisher(in: dbQueue)
```
This publisher has the same behavior as ValueObservation:
- It notifies an initial value before the eventual changes.
- It may coalesce subsequent changes into a single notification.
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](../README.md#valueobservationremoveduplicates) GRDB operator also.
- It stops emitting any value after the database connection is closed. But it never completes.
- By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously.
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservation scheduler](../README.md#valueobservation-scheduling).
For example, the `.immediate` scheduler makes sure the initial value is notified immediately when the publisher is subscribed. It can help your application update the user interface without having to wait for any asynchronous notifications:
```swift
// Immediate notification of the initial value
let cancellable = observation
.publisher(
in: dbQueue,
scheduling: .immediate) // <-
.sink(
receiveCompletion: { completion in ... },
receiveValue: { (players: [Player]) in print("Fresh players: \(players)") })
// <- here "fresh players" is already printed.
```
Note that the `.immediate` scheduler requires that the publisher is subscribed from the main thread. It raises a fatal error otherwise.
See [ValueObservation Scheduling](../README.md#valueobservation-scheduling) for more information.
:warning: **ValueObservation and Data Consistency**
When you compose ValueObservation publishers together with the [combineLatest](https://developer.apple.com/documentation/combine/publisher/3333677-combinelatest) operator, you lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
Instead, compose requests together into **one single** ValueObservation, as below:
```swift
struct HallOfFame {
var totalPlayerCount: Int
var bestPlayers: [Player]
}
// DATA CONSISTENCY GUARANTEED
let hallOfFamePublisher = ValueObservation
.tracking { db -> HallOfFame in
let totalPlayerCount = try Player.fetchCount(db)
let bestPlayers = try Player
.order(Column("score").desc)
.limit(10)
.fetchAll(db)
return HallOfFame(
totalPlayerCount: totalPlayerCount,
bestPlayers: bestPlayers)
}
.publisher(in: dbQueue)
```
See [ValueObservation] for more information.
#### `DatabaseRegionObservation.publisher(in:)`
[DatabaseRegionObservation] notifies all transactions that impact a tracked database region. You can turn it into a Combine publisher:
```swift
let request = Player.all()
let observation = DatabaseRegionObservation.tracking(request)
// A publisher with output Database and failure Error
let publisher = observation.publisher(in: dbQueue)
```
This publisher can be created and subscribed from any thread. It delivers database connections in a "protected dispatch queue", serialized with all database updates. It only completes when a database error happens.
```swift
let request = Player.all()
let cancellable = DatabaseRegionObservation
.tracking(request)
.publisher(in: dbQueue)
.sink(
receiveCompletion: { completion in ... },
receiveValue: { (db: Database) in
print("Players have changed.")
})
try dbQueue.write { db in
try Player(name: "Arthur").insert(db)
try Player(name: "Barbara").insert(db)
}
// Prints "Players have changed."
try dbQueue.write { db in
try Player.deleteAll(db)
}
// Prints "Players have changed."
```
See [DatabaseRegionObservation] for more information.
[Database Connections]: ../README.md#database-connections
[Usage]: #usage
[Asynchronous Database Access]: #asynchronous-database-access
[Combine]: https://developer.apple.com/documentation/combine
[Database Changes Observation]: ../README.md#database-changes-observation
[Database Observation]: #database-observation
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[Demo Application]: DemoApps/GRDBCombineDemo/README.md
[SQLite]: http://sqlite.org
[ValueObservation]: ../README.md#valueobservation
[`DatabaseRegionObservation.publisher(in:)`]: #databaseregionobservationpublisherin
[`ValueObservation.publisher(in:scheduling:)`]: #valueobservationpublisherinscheduling
[`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue
[`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
[configured]: ../README.md#databasepool-configuration
[database pool]: ../README.md#database-pools
[database queue]: ../README.md#database-queues
[database snapshot]: ../README.md#database-snapshots
[scheduler]: https://developer.apple.com/documentation/combine/scheduler
-423
View File
@@ -1,423 +0,0 @@
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
+5 -7
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.33.0](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.28.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).
@@ -19,9 +19,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
git submodule update --init SQLiteCustom/src
```
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](../README.md#valueobservation) when you use a [Database Pool](../README.md#database-pools).
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5` and `SQLITE_ENABLE_PREUPDATE_HOOK`.
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
@@ -32,7 +30,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```xcconfig
// As many -D options as there are custom SQLite compilation options
// Note: there is no space between -D and the option name.
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_SNAPSHOT -DSQLITE_ENABLE_FTS5
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_FTS5 -DSQLITE_ENABLE_PREUPDATE_HOOK
```
- `GRDBCustomSQLite-USER.xcconfig`: this file lets GRDB know about extra compilation flags, and enables extra GRDB APIs.
@@ -40,15 +38,15 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```xcconfig
// As many -D options as there are custom SQLite compilation options
// Note: there is one space between -D and the option name.
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_SNAPSHOT -D SQLITE_ENABLE_FTS5
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK
```
- `GRDBCustomSQLite-USER.h`: this file lets your application know about extra compilation flags.
```c
// As many #define as there are custom SQLite compilation options
#define SQLITE_ENABLE_SNAPSHOT
#define SQLITE_ENABLE_FTS5
#define SQLITE_ENABLE_PREUPDATE_HOOK
```
- `GRDBCustomSQLite-INSTALL.sh`: this file installs the three other files.
@@ -1,732 +0,0 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 50;
objects = {
/* Begin PBXBuildFile section */
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 */
56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
remoteInfo = GRDBCombineDemo;
};
567C3E342520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = DC3773F319C8CBB3004FCF85;
remoteInfo = GRDBOSX;
};
567C3E362520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
remoteInfo = GRDBOSXTests;
};
567C3E382520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56553C181C3E906C00522B5C;
remoteInfo = GRDBOSXCrashTests;
};
567C3E3A2520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7CA1B4D3FED00430942;
remoteInfo = GRDBiOS;
};
567C3E3C2520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
remoteInfo = GRDBiOSTests;
};
567C3E3E2520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 565490A01D5A4798005622CB;
remoteInfo = GRDBWatchOS;
};
567C3E402520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = AAA4DCFE230F1E0600C74B15;
remoteInfo = GRDBtvOS;
};
567C3E422520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = AAA4DDD4230F262000C74B15;
remoteInfo = GRDBtvOSTests;
};
567C3E512520B71C0011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
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 */
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 */
56026C9525B8A7D000D1DF3F /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
567C3E132520B6DE0011F6E9 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
567C3E4E2520B70E0011F6E9 /* GRDB.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */ = {
isa = PBXGroup;
children = (
56026C9C25B8A7D000D1DF3F /* Info.plist */,
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */,
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */,
);
path = GRDBCombineDemoTests;
sourceTree = "<group>";
};
56185BC125B8047D00B9C30F /* Resources */ = {
isa = PBXGroup;
children = (
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>";
};
567C3E172520B6DE0011F6E9 /* Products */ = {
isa = PBXGroup;
children = (
567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */,
56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */ = {
isa = PBXGroup;
children = (
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>";
};
567C3E1F2520B6DF0011F6E9 /* Preview Content */ = {
isa = PBXGroup;
children = (
567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */,
);
path = "Preview Content";
sourceTree = "<group>";
};
567C3E2A2520B7000011F6E9 /* Products */ = {
isa = PBXGroup;
children = (
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>";
};
567C3E4D2520B70E0011F6E9 /* Frameworks */ = {
isa = PBXGroup;
children = (
);
name = Frameworks;
sourceTree = "<group>";
};
567C3E552520B75C0011F6E9 /* ViewModels */ = {
isa = PBXGroup;
children = (
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>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoTests" */;
buildPhases = (
56026C9425B8A7D000D1DF3F /* Sources */,
56026C9525B8A7D000D1DF3F /* Frameworks */,
56026C9625B8A7D000D1DF3F /* Resources */,
);
buildRules = (
);
dependencies = (
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 = GRBCombineDemo;
productReference = 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1230;
LastUpgradeCheck = 1200;
TargetAttributes = {
56026C9725B8A7D000D1DF3F = {
CreatedOnToolsVersion = 12.3;
TestTargetID = 567C3E152520B6DE0011F6E9;
};
567C3E152520B6DE0011F6E9 = {
CreatedOnToolsVersion = 12.0;
};
};
};
buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 567C3E0D2520B6DE0011F6E9;
productRefGroup = 567C3E172520B6DE0011F6E9 /* Products */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = 567C3E2A2520B7000011F6E9 /* Products */;
ProjectRef = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
},
);
projectRoot = "";
targets = (
567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */,
56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */,
);
};
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
567C3E352520B7000011F6E9 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 567C3E342520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567C3E372520B7000011F6E9 /* GRDBOSXTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXTests.xctest;
remoteRef = 567C3E362520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567C3E392520B7000011F6E9 /* GRDBOSXCrashTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXCrashTests.xctest;
remoteRef = 567C3E382520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567C3E3B2520B7000011F6E9 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 567C3E3A2520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567C3E3D2520B7000011F6E9 /* GRDBiOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBiOSTests.xctest;
remoteRef = 567C3E3C2520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567C3E3F2520B7000011F6E9 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 567C3E3E2520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567C3E412520B7000011F6E9 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 567C3E402520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567C3E432520B7000011F6E9 /* GRDBtvOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBtvOSTests.xctest;
remoteRef = 567C3E422520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
56026C9625B8A7D000D1DF3F /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
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 */
56026C9425B8A7D000D1DF3F /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
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 */
56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */;
targetProxy = 56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */;
};
567C3E522520B71C0011F6E9 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBiOS;
targetProxy = 567C3E512520B71C0011F6E9 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
567C3E752520BB650011F6E9 /* Localizable.stringsdict */ = {
isa = PBXVariantGroup;
children = (
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 */
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;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_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;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
567C3E242520B6DF0011F6E9 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_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;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
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",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 1;
};
name = Debug;
};
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",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 1;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
56026C9F25B8A7D000D1DF3F /* Debug */,
56026CA025B8A7D000D1DF3F /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
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 = 567C3E0E2520B6DE0011F6E9 /* Project object */;
}
@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:/Users/groue/Documents/git/groue/GRDB.swift/Documentation/DemoApps/GRBCombineDemo/GRDBCombineDemo.xcodeproj">
</FileRef>
</Workspace>
@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -1,88 +0,0 @@
<?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>
@@ -1,143 +0,0 @@
import Combine
import GRDB
/// AppDatabase lets the application access the database.
///
/// It applies the pratices recommended at
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
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
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
// Speed up development by nuking the database when migrations change
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
migrator.eraseDatabaseOnSchemaChange = true
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
// See https://github.com/groue/GRDB.swift#create-tables
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
}
}
// MARK: - Database Access: Writes
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)
}
}
/// 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)
}
}
/// 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.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) {
$0.score = Player.randomScore()
}
}
}
}
}
/// 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)
}
}
}
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
private func createRandomPlayers(_ db: Database) throws {
for _ in 0..<8 {
var player = Player.newRandom()
try player.insert(db)
}
}
}
// 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)
.publisher(in: dbWriter, scheduling: .immediate)
.eraseToAnyPublisher()
}
/// Returns a publisher that tracks changes in players ordered by score
func playersOrderedByScorePublisher() -> AnyPublisher<[Player], Error> {
ValueObservation
.tracking(Player.all().orderedByScore().fetchAll)
.publisher(in: dbWriter, scheduling: .immediate)
.eraseToAnyPublisher()
}
}
@@ -1,12 +0,0 @@
import SwiftUI
@main
struct GRDBCombineDemoApp: App {
let appDatabase = AppDatabase.shared
var body: some Scene {
WindowGroup {
PlayerList(viewModel: PlayerListViewModel(database: appDatabase))
}
}
}
@@ -1,50 +0,0 @@
<?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>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<true/>
</dict>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UILaunchScreen</key>
<dict/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
@@ -1,58 +0,0 @@
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
}
}
@@ -1,105 +0,0 @@
import GRDB
/// The Player struct.
///
/// 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.
/// Use nil for players that are not inserted yet in the database.
var id: Int64?
var name: String
var score: Int
}
extension Player {
private static let names = [
"Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David",
"Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette",
"Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl",
"Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole",
"Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul",
"Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain",
"Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann",
"Zazie", "Zoé"]
/// Creates a new player with empty name and zero score
static func new() -> Player {
Player(id: nil, name: "", score: 0)
}
/// 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)
}
}
// MARK: - Persistence
/// Make Player a Codable Record.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
fileprivate enum Columns {
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
}
/// Updates a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
// MARK: - Player Database Requests
/// Define some player requests used by the application.
///
/// 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.
///
/// 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
// 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.
///
/// 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
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
order(
Player.Columns.score.desc,
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
}
@@ -1,6 +0,0 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -1,11 +0,0 @@
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -1,6 +0,0 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -1,12 +0,0 @@
{
"images" : [
{
"filename" : "LaunchIcon.pdf",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -1,42 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<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="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>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="LaunchIcon" translatesAutoresizingMaskIntoConstraints="NO" id="Sgi-te-PKu">
<rect key="frame" x="123.5" y="334.5" width="167" height="237"/>
</imageView>
</subviews>
<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>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</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,42 +0,0 @@
<?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>%lld Players</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@VARIABLE@</string>
<key>VARIABLE</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>lld</string>
<key>zero</key>
<string>No Player</string>
<key>one</key>
<string>1 Player</string>
<key>other</key>
<string>%lld Players</string>
</dict>
</dict>
<key>%lld points</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@VARIABLE@</string>
<key>VARIABLE</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>lld</string>
<key>zero</key>
<string>0 point</string>
<key>one</key>
<string>1 point</string>
<key>other</key>
<string>%lld points</string>
</dict>
</dict>
</dict>
</plist>
@@ -1,67 +0,0 @@
import Combine
import Foundation
/// The view model that validates and saves an edited player into the database.
///
/// It feeds `PlayerForm`, `PlayerCreationSheet` and `PlayerEditionView`.
final class PlayerFormViewModel: ObservableObject {
/// A validation error that prevents the player from being saved into
/// the database.
enum ValidationError: LocalizedError {
case missingName
var errorDescription: String? {
switch self {
case .missingName:
return "Please give a name to this player."
}
}
}
@Published var name: String = ""
@Published var score: String = ""
private let database: AppDatabase
private var player: Player
init(database: AppDatabase, player: Player) {
self.database = database
self.player = player
updateViewFromPlayer()
}
// MARK: - Manage the Player Form
/// Validates and saves the player into the database.
func savePlayer() throws {
if name.isEmpty {
throw ValidationError.missingName
}
player.name = name
player.score = Int(score) ?? 0
try database.savePlayer(&player)
}
/// Resets form values to the original player values.
func reset() {
updateViewFromPlayer()
}
/// Edits a new player
func editNewPlayer() {
player = .new()
updateViewFromPlayer()
}
// MARK: - Private
private func updateViewFromPlayer() {
self.name = player.name
if player.score == 0 && player.id == nil {
// Avoid displaying "0" for a new player: it does not look good.
self.score = ""
} else {
self.score = "\(player.score)"
}
}
}
@@ -1,118 +0,0 @@
import Combine
import Foundation
/// The view model that feeds `PlayerList`, and performs list modifications
/// in the database.
final class PlayerListViewModel: ObservableObject {
enum Ordering {
case byScore
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 playerList = PlayerList(players: [], animatedChanges: false)
/// The view model that edits a new player
let newPlayerViewModel: PlayerFormViewModel
private let database: AppDatabase
private var playersCancellable: AnyCancellable?
init(database: AppDatabase) {
self.database = database
newPlayerViewModel = PlayerFormViewModel(database: database, player: .new())
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
/// Deletes all players
func deleteAllPlayers() {
// Eventual error presentation is left as an exercise for the reader.
try! database.deleteAllPlayers()
}
func deletePlayers(atOffsets offsets: IndexSet) {
// Eventual error presentation is left as an exercise for the reader.
let playerIDs = offsets.compactMap { playerList.players[$0].id }
try! database.deletePlayers(ids: playerIDs)
}
/// Refreshes the list of players
func refreshPlayers() {
// Eventual error presentation is left as an exercise for the reader.
try! database.refreshPlayers()
}
/// Spawns many concurrent database updates, for demo purpose
func stressTest() {
for _ in 0..<50 {
DispatchQueue.global().async {
self.refreshPlayers()
}
}
}
// MARK: - Change Player Ordering
/// Toggles between the available orderings
func toggleOrdering() {
switch ordering {
case .byName:
ordering = .byScore
case .byScore:
ordering = .byName
}
}
// MARK: - Player Edition
/// Returns a view model suitable for editing a player.
func formViewModel(for player: Player) -> PlayerFormViewModel {
PlayerFormViewModel(database: database, player: player)
}
// MARK: - Private
/// Returns a publisher of the players in the list
private func playersPublisher(in database: AppDatabase) -> AnyPublisher<[Player], Never> {
// Players depend on the current ordering
$ordering.map { ordering -> AnyPublisher<[Player], Error> in
switch ordering {
case .byScore:
return database.playersOrderedByScorePublisher()
case .byName:
return database.playersOrderedByNamePublisher()
}
}
.map { playersPublisher in
// Turn database errors into an empty players list.
// Eventual error presentation is left as an exercise for the reader.
playersPublisher.catch { error in
Just<[Player]>([])
}
}
.switchToLatest()
.eraseToAnyPublisher()
}
}
@@ -1,52 +0,0 @@
import SwiftUI
/// The Player creation sheet
struct PlayerCreationSheet: View {
/// Manages the player form
let viewModel: PlayerFormViewModel
/// Executed when user cancels or saves the new user.
let dismissAction: () -> Void
@State private var errorAlertIsPresented = false
@State private var errorAlertTitle = ""
var body: some View {
NavigationView {
PlayerForm(viewModel: viewModel)
.alert(
isPresented: $errorAlertIsPresented,
content: { Alert(title: Text(errorAlertTitle)) })
.navigationBarTitle("New Player")
.navigationBarItems(
leading: Button(
action: self.dismissAction,
label: { Text("Cancel") }),
trailing: Button(
action: self.save,
label: { Text("Save") }))
}
}
private func save() {
do {
try viewModel.savePlayer()
dismissAction()
} catch {
errorAlertTitle = (error as? LocalizedError)?.errorDescription ?? "An error occurred"
errorAlertIsPresented = true
}
}
}
struct PlayerCreationSheet_Previews: PreviewProvider {
static var previews: some View {
let viewModel = PlayerFormViewModel(
database: .empty(),
player: .new())
return PlayerCreationSheet(
viewModel: viewModel,
dismissAction: { })
}
}
@@ -1,29 +0,0 @@
import SwiftUI
/// The Player edition view, designed to be the destination of
/// a NavigationLink.
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()
})
}
}
struct PlayerEditionView_Previews: PreviewProvider {
static var previews: some View {
let viewModel = PlayerFormViewModel(
database: .empty(),
player: .newRandom())
return NavigationView {
PlayerEditionView(viewModel: viewModel)
.navigationBarTitle("Player Edition")
}
}
}
@@ -1,39 +0,0 @@
import SwiftUI
/// The Player editing form, embedded in both
/// `PlayerCreationSheet` and `PlayerEditionView`.
struct PlayerForm: View {
/// Manages the player form
@ObservedObject var viewModel: PlayerFormViewModel
var body: some View {
List {
TextField("Name", text: $viewModel.name)
TextField("Score", text: $viewModel.score)
.keyboardType(.numberPad)
}
.listStyle(GroupedListStyle())
// Make sure the form is reset, in case a previous edition ended
// with a validation error.
//
// The bug we want to prevent is the following:
//
// 1. Launch the app
// 2. Tap a player
// 3. Erase the name so that validation fails
// 4. Hit the back button
// 5. Tap the same player
// 6. Bug: the form displays an empty name.
.onAppear(perform: viewModel.reset)
}
}
struct PlayerFormView_Previews: PreviewProvider {
static var previews: some View {
let viewModel = PlayerFormViewModel(
database: .empty(),
player: .newRandom())
return PlayerForm(viewModel: viewModel)
}
}
@@ -1,131 +0,0 @@
import SwiftUI
/// The list of players
struct PlayerList: View {
/// Manages the list of players
@ObservedObject var viewModel: PlayerListViewModel
/// Controls the presentation of the player creation sheet.
@State private var newPlayerIsPresented = false
var body: some View {
NavigationView {
VStack {
playerList
toolbar
}
.navigationBarTitle(Text("\(viewModel.playerList.players.count) Players"))
.navigationBarItems(
leading: HStack {
EditButton()
newPlayerButton
},
trailing: toggleOrderingButton)
}
}
private var playerList: some View {
List {
ForEach(viewModel.playerList.players) { player in
NavigationLink(destination: self.editionView(for: player)) {
PlayerRow(player: player)
.animation(nil)
}
}
.onDelete(perform: { offsets in
self.viewModel.deletePlayers(atOffsets: offsets)
})
}
.listStyle(PlainListStyle())
.animation(viewModel.playerList.animatedChanges ? .default : nil)
}
private var toolbar: some View {
HStack {
Button(
action: viewModel.deleteAllPlayers,
label: { Image(systemName: "trash").imageScale(.large) })
Spacer()
Button(
action: viewModel.refreshPlayers,
label: { Image(systemName: "arrow.clockwise").imageScale(.large) })
Spacer()
Button(
action: viewModel.stressTest,
label: { Image(systemName: "tornado").imageScale(.large) })
}
.padding()
}
/// The button that toggles between name/score ordering.
private var toggleOrderingButton: some View {
switch viewModel.ordering {
case .byName:
return Button(action: viewModel.toggleOrdering, label: {
HStack {
Text("Name")
Image(systemName: "arrowtriangle.up.fill")
.imageScale(.small)
}
})
case .byScore:
return Button(action: viewModel.toggleOrdering, label: {
HStack {
Text("Score")
Image(systemName: "arrowtriangle.down.fill")
.imageScale(.small)
}
})
}
}
/// The view that edits a player in the list.
private func editionView(for player: Player) -> some View {
PlayerEditionView(
viewModel: viewModel.formViewModel(for: player))
.navigationBarTitle(player.name)
}
/// The button that presents the player creation sheet.
private var newPlayerButton: some View {
Button(
action: {
// 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,
content: { self.newPlayerCreationSheet })
}
/// The player creation sheet.
private var newPlayerCreationSheet: some View {
PlayerCreationSheet(
viewModel: self.viewModel.newPlayerViewModel,
dismissAction: {
self.newPlayerIsPresented = false
})
}
}
struct PlayerRow: View {
var player: Player
var body: some View {
HStack {
Text(player.name)
Spacer()
Text("\(player.score) points").foregroundColor(.gray)
}
}
}
struct PlayerListView_Previews: PreviewProvider {
static var previews: some View {
let viewModel = PlayerListViewModel(database: .random())
return PlayerList(viewModel: viewModel)
}
}
@@ -1,254 +0,0 @@
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)
}
}
@@ -1,22 +0,0 @@
<?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>
@@ -1,108 +0,0 @@
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])
}
}
@@ -1,48 +0,0 @@
Combine + SwiftUI Demo Application
==================================
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBCombineDemo/Screenshot.png" width="50%">
**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.
- How to define a simple [Codable Record](../../../README.md#codable-records).
- How to track database changes and animate a SwiftUI List with [ValueObservation](../../../README.md#valueobservation) Combine publishers.
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
- How to feed SwiftUI previews with a transient database.
**Files of interest:**
- [GRDBCombineDemoApp.swift](GRDBCombineDemo/GRDBCombineDemoApp.swift)
`GRDBCombineDemoApp` feeds the app views with a database.
- [AppDatabase.swift](GRDBCombineDemo/AppDatabase.swift)
`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)
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). It defines the database requests used by the application.
- [PlayerList.swift](GRDBCombineDemo/Views/PlayerList.swift) and [PlayerListViewModel.swift](GRDBCombineDemo/ViewModels/PlayerListViewModel.swift)
`PlayerList` is the SwiftUI view that displays the list of players, fed by `PlayerListViewModel`.
- [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 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.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 799 KiB

@@ -25,7 +25,7 @@
<key>NSExtensionAttributes</key>
<dict>
<key>WKAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS.watchkitapp</string>
<string>com.github.groue.GRDBDemoiOS2.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.GRDBDemoiOS</string>
<string>com.github.groue.GRDBDemoiOS2</string>
<key>WKWatchKitApp</key>
<true/>
</dict>
@@ -7,9 +7,6 @@
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 */; };
@@ -28,18 +25,10 @@
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; };
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 */; };
56FE6F2624A90CE400711EDF /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FE6F2524A90CE400711EDF /* SceneDelegate.swift */; };
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayersViewController.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 */;
@@ -174,11 +163,6 @@
/* 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>"; };
@@ -197,19 +181,11 @@
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
56B0361A1E8D9F38003B6DA4 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = "<group>"; };
56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewController.swift; sourceTree = "<group>"; };
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = "<group>"; };
56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
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;
@@ -229,16 +205,6 @@
/* 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 = (
@@ -289,7 +255,6 @@
56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */,
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */,
568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */,
56185BF125B80B8900B9C30F /* GRDBDemoiOSTests */,
56B036041E8D9EBE003B6DA4 /* Products */,
56606D1F2355938A00185962 /* Frameworks */,
);
@@ -301,7 +266,6 @@
56B036031E8D9EBE003B6DA4 /* GRDBDemoiOS.app */,
568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */,
568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */,
56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */,
);
name = Products;
sourceTree = "<group>";
@@ -309,66 +273,22 @@
56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */ = {
isa = PBXGroup;
children = (
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
56185BBE25B8036100B9C30F /* Persistence.swift */,
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
56B0361A1E8D9F38003B6DA4 /* Player.swift */,
56FE6F2524A90CE400711EDF /* SceneDelegate.swift */,
56FE6F4E24A9112900711EDF /* Resources */,
56FE6F5124A9118000711EDF /* Support */,
56FE6F4F24A9114200711EDF /* ViewControllers */,
);
path = GRDBDemoiOS;
sourceTree = "<group>";
};
56FE6F4E24A9112900711EDF /* Resources */ = {
isa = PBXGroup;
children = (
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */,
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */,
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */,
56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */,
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
);
path = Resources;
sourceTree = "<group>";
};
56FE6F4F24A9114200711EDF /* ViewControllers */ = {
isa = PBXGroup;
children = (
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */,
56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */,
);
path = ViewControllers;
sourceTree = "<group>";
};
56FE6F5124A9118000711EDF /* Support */ = {
isa = PBXGroup;
children = (
56B036121E8D9EBE003B6DA4 /* Info.plist */,
);
name = Support;
path = GRDBDemoiOS;
sourceTree = "<group>";
};
/* 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" */;
@@ -432,16 +352,10 @@
56B035FB1E8D9EBE003B6DA4 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1230;
LastUpgradeCheck = 1200;
LastSwiftUpdateCheck = 0830;
LastUpgradeCheck = 1020;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
56185BEF25B80B8900B9C30F = {
CreatedOnToolsVersion = 12.3;
DevelopmentTeam = AMD8W895CT;
ProvisioningStyle = Automatic;
TestTargetID = 56B036021E8D9EBE003B6DA4;
};
568E5FBE1E926430002582E0 = {
CreatedOnToolsVersion = 8.3;
DevelopmentTeam = AMD8W895CT;
@@ -483,7 +397,6 @@
56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */,
568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */,
568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */,
56185BEF25B80B8900B9C30F /* GRDBDemoiOSTests */,
);
};
/* End PBXProject section */
@@ -548,13 +461,6 @@
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
56185BEE25B80B8900B9C30F /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
568E5FBD1E926430002582E0 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
@@ -585,15 +491,6 @@
/* 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;
@@ -607,12 +504,10 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
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 */,
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */,
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -620,11 +515,6 @@
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
56185BF625B80B8900B9C30F /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */;
targetProxy = 56185BF525B80B8900B9C30F /* PBXContainerItemProxy */;
};
56606D1E2355937900185962 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBiOS;
@@ -675,51 +565,6 @@
/* 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 = {
@@ -728,7 +573,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.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -744,7 +589,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.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -761,7 +606,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -778,7 +623,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -812,7 +657,6 @@
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;
@@ -874,7 +718,6 @@
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;
@@ -912,7 +755,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
@@ -926,7 +769,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
@@ -934,15 +777,6 @@
/* 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,7 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1200"
LastUpgradeVersion = "1130"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -55,17 +55,16 @@
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
BuildableName = "GRDBDemoWatchOS.app"
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56185BEF25B80B8900B9C30F"
BuildableName = "GRDBDemoiOSTests.xctest"
BlueprintName = "GRDBDemoiOSTests"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
@@ -78,8 +77,10 @@
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<RemoteRunnable
runnableDebuggingMode = "2"
BundleIdentifier = "com.apple.carousel"
RemotePath = "/GRDBDemoiOS">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
@@ -87,7 +88,7 @@
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</RemoteRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -95,8 +96,10 @@
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<RemoteRunnable
runnableDebuggingMode = "2"
BundleIdentifier = "com.apple.carousel"
RemotePath = "/GRDBDemoiOS">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
@@ -104,7 +107,16 @@
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</RemoteRunnable>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
BuildableName = "GRDBDemoWatchOS.app"
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1230"
LastUpgradeVersion = "1130"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -27,21 +27,20 @@
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
BuildableName = "GRDBDemoiOS.app"
BlueprintName = "GRDBDemoiOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56185BEF25B80B8900B9C30F"
BuildableName = "GRDBDemoiOSTests.xctest"
BlueprintName = "GRDBDemoiOSTests"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
@@ -1,154 +1,56 @@
import GRDB
/// AppDatabase lets the application access the database.
/// A type responsible for initializing the application database.
///
/// It applies the pratices recommended at
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
final class AppDatabase {
/// Creates an `AppDatabase`, and make sure the database schema is ready.
init(_ dbWriter: DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
}
/// See AppDelegate.setupDatabase()
struct AppDatabase {
/// 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
/// Creates a fully initialized database at path
static func openDatabase(atPath path: String) throws -> DatabaseQueue {
// Connect to the database
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let dbQueue = try DatabaseQueue(path: path)
// Define the database schema
try migrator.migrate(dbQueue)
return dbQueue
}
/// The DatabaseMigrator that defines the database schema.
///
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
private var migrator: DatabaseMigrator {
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#migrations
static var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
// Speed up development by nuking the database when migrations change
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
migrator.eraseDatabaseOnSchemaChange = true
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
// See https://github.com/groue/GRDB.swift#create-tables
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
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
t.column("score", .integer).notNull()
}
}
// Migrations for future application versions will be inserted here:
// migrator.registerMigration(...) { db in
// ...
// }
migrator.registerMigration("fixtures") { db in
// Populate the players table with random data
for _ in 0..<8 {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
}
// // Migrations for future application versions will be inserted here:
// migrator.registerMigration(...) { db in
// ...
// }
return migrator
}
}
// MARK: - Database Access: Writes
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)
}
}
/// 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)
}
}
/// 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.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) {
$0.score = Player.randomScore()
}
}
}
}
}
/// 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)
}
}
}
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
private func createRandomPlayers(_ db: Database) throws {
for _ in 0..<8 {
var player = Player.newRandom()
try player.insert(db)
}
}
}
// MARK: - Database Access: Reads
extension AppDatabase {
/// Tracks changes in players ordered by name
func observePlayersOrderedByName(
onError: @escaping (Error) -> Void,
onChange: @escaping ([Player]) -> Void)
-> DatabaseCancellable
{
ValueObservation
.tracking(Player.all().orderedByName().fetchAll)
.start(
in: dbWriter,
onError: onError,
onChange: onChange)
}
/// Tracks changes in players ordered by score
func observePlayersOrderedByScore(
onError: @escaping (Error) -> Void,
onChange: @escaping ([Player]) -> Void)
-> DatabaseCancellable
{
ValueObservation
.tracking(Player.all().orderedByScore().fetchAll)
.start(
in: dbWriter,
onError: onError,
onChange: onChange)
}
}
@@ -1,22 +1,22 @@
import UIKit
import GRDB
// The shared database queue
var dbQueue: DatabaseQueue!
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
try! setupDatabase(application)
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.
private func setupDatabase(_ application: UIApplication) throws {
let databaseURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path)
}
}
File renamed without changes.

Before

Width:  |  Height:  |  Size: 329 KiB

After

Width:  |  Height:  |  Size: 329 KiB

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="8150" systemVersion="15A204g" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="8122"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Llm-lL-Icb"/>
<viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<animations/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
@@ -1,8 +1,8 @@
<?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" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15505" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15510"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
@@ -10,25 +10,25 @@
<scene sceneID="Juk-Ad-tZ2">
<objects>
<tableViewController id="iNr-Oe-muq" customClass="PlayerEditionViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="insetGrouped" separatorStyle="none" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="-1" estimatedSectionHeaderHeight="-1" sectionFooterHeight="-1" estimatedSectionFooterHeight="-1" id="vlV-lc-eQA">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="plain" separatorStyle="none" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="vlV-lc-eQA">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<sections>
<tableViewSection headerTitle="Name" id="Nzq-eO-jT3">
<tableViewSection id="Nzq-eO-jT3">
<cells>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="2gb-gB-918">
<rect key="frame" x="20" y="55.5" width="374" height="44"/>
<rect key="frame" x="0.0" y="28" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="2gb-gB-918" id="iyM-TJ-JB4">
<rect key="frame" x="0.0" y="0.0" width="374" height="44"/>
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
<rect key="frame" x="20" y="11" width="334" height="22"/>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Name" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
<rect key="frame" x="16" y="11.5" width="343" height="21"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no" returnKeyType="next"/>
<connections>
<action selector="textFieldDidChange:" destination="iNr-Oe-muq" eventType="editingChanged" id="EmC-Rp-f6S"/>
<outlet property="delegate" destination="iNr-Oe-muq" id="K2p-7d-teD"/>
</connections>
</textField>
@@ -40,24 +40,17 @@
</constraints>
</tableViewCellContentView>
</tableViewCell>
</cells>
</tableViewSection>
<tableViewSection headerTitle="Score" id="Urb-uF-sj1">
<cells>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="vp3-Ft-Gth">
<rect key="frame" x="20" y="155" width="374" height="44"/>
<rect key="frame" x="0.0" y="72" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="vp3-Ft-Gth" id="ccO-0O-u72">
<rect key="frame" x="0.0" y="0.0" width="374" height="44"/>
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="0" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
<rect key="frame" x="20" y="11" width="334" height="22"/>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Score" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
<rect key="frame" x="16" y="11.5" width="343" height="21"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no" keyboardType="numberPad" returnKeyType="done"/>
<connections>
<action selector="textFieldDidChange:" destination="iNr-Oe-muq" eventType="editingChanged" id="ebo-2z-Z9P"/>
</connections>
</textField>
</subviews>
<constraints>
@@ -108,7 +101,7 @@
<objects>
<navigationController id="ein-Sr-i8w" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="zIT-dB-Mfo">
<rect key="frame" x="0.0" y="0.0" width="414" height="56"/>
<rect key="frame" x="0.0" y="0.0" width="375" height="56"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
@@ -124,7 +117,7 @@
<objects>
<navigationController id="UAh-8N-CM8" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="U7d-1C-GnL">
<rect key="frame" x="0.0" y="44" width="414" height="44"/>
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
@@ -138,27 +131,27 @@
<!--Hall Of Fame-->
<scene sceneID="9su-ms-vdJ">
<objects>
<tableViewController id="PJp-Eq-ZjA" customClass="PlayerListViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<tableViewController id="PJp-Eq-ZjA" customClass="PlayersViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="-1" estimatedSectionHeaderHeight="-1" sectionFooterHeight="-1" estimatedSectionFooterHeight="-1" id="tX0-ON-WSI">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<prototypes>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Player" textLabel="G8y-VE-YRu" detailTextLabel="NNc-J4-xiE" style="IBUITableViewCellStyleValue1" id="bFj-Hd-fwd">
<rect key="frame" x="0.0" y="28" width="414" height="43.5"/>
<rect key="frame" x="0.0" y="28" width="375" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="bFj-Hd-fwd" id="kDf-TZ-xhb">
<rect key="frame" x="0.0" y="0.0" width="383" height="43.5"/>
<rect key="frame" x="0.0" y="0.0" width="348" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontForContentSizeCategory="YES" adjustsFontSizeToFit="NO" id="G8y-VE-YRu">
<rect key="frame" x="20" y="12" width="33.5" height="20.5"/>
<rect key="frame" x="16" y="12" width="33.5" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontForContentSizeCategory="YES" adjustsFontSizeToFit="NO" id="NNc-J4-xiE">
<rect key="frame" x="331" y="12" width="44" height="20.5"/>
<rect key="frame" x="296" y="12" width="44" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
@@ -3,7 +3,7 @@
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
@@ -13,32 +13,15 @@
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<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>
<key>UISceneStoryboardFile</key>
<string>Main</string>
</dict>
</array>
</dict>
</dict>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
@@ -50,11 +33,6 @@
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
@@ -1,43 +0,0 @@
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)")
}
}
}
@@ -1,18 +1,50 @@
import GRDB
/// The Player struct.
///
/// Hashable conformance supports table view updates
struct Player: Hashable {
/// The player id.
///
/// Int64 is the recommended type for auto-incremented database ids.
/// Use nil for players that are not inserted yet in the database.
// A plain Player struct
struct Player {
// Prefer Int64 for auto-incremented database ids
var id: Int64?
var name: String
var score: Int
}
// Hashable conformance supports tableView diffing
extension Player: Hashable { }
// MARK: - Persistence
// Turn Player into a Codable Record.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
private enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
}
// Update a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
// MARK: - Database access
// Define some useful player requests.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
extension Player {
static func orderedByName() -> QueryInterfaceRequest<Player> {
Player.order(Columns.name)
}
static func orderedByScore() -> QueryInterfaceRequest<Player> {
Player.order(Columns.score.desc, Columns.name)
}
}
// MARK: - Player Randomization
extension Player {
private static let names = [
"Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David",
@@ -24,81 +56,11 @@ extension Player {
"Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann",
"Zazie", "Zoé"]
/// Creates a new player with empty name and zero score
static func new() -> Player {
Player(id: nil, name: "", score: 0)
}
/// 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)
}
}
// MARK: - Persistence
/// Make Player a Codable Record.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
fileprivate enum Columns {
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
}
/// Updates a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
// MARK: - Player Database Requests
/// Define some player requests used by the application.
///
/// 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.
///
/// 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
// 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.
///
/// 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
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
order(
Player.Columns.score.desc,
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
}
@@ -2,44 +2,55 @@ import UIKit
class PlayerEditionViewController: UITableViewController {
enum Presentation {
/// Modal presentation: edition ends with the "Commit" unwind segue.
/// Modal presentation: edition ends with the "Commit" segue.
case modal
/// Push presentation: edition ends when user hits the back button.
case push
}
/// The edited player
var player: Player! {
didSet {
configureForm()
}
}
/// The presentation mode
var presentation: Presentation! {
didSet {
configureNavigationItem()
}
}
@IBOutlet private weak var cancelBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var commitBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var nameCell: UITableViewCell!
@IBOutlet private weak var nameTextField: UITextField!
@IBOutlet private weak var scoreCell: UITableViewCell!
@IBOutlet private weak var scoreTextField: UITextField!
var player: Player! { didSet { configureView() } }
var presentation: Presentation! { didSet { configureView() } }
@IBOutlet fileprivate weak var cancelBarButtonItem: UIBarButtonItem!
@IBOutlet fileprivate weak var commitBarButtonItem: UIBarButtonItem!
@IBOutlet fileprivate weak var nameCell: UITableViewCell!
@IBOutlet fileprivate weak var nameTextField: UITextField!
@IBOutlet fileprivate weak var scoreCell: UITableViewCell!
@IBOutlet fileprivate weak var scoreTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
configureForm()
configureNavigationItem()
configureView()
}
fileprivate func configureView() {
guard isViewLoaded else { return }
nameTextField.text = player.name
if player.score == 0 && player.id == nil {
scoreTextField.text = ""
} else {
scoreTextField.text = "\(player.score)"
}
switch presentation! {
case .modal:
navigationItem.leftBarButtonItem = cancelBarButtonItem
navigationItem.rightBarButtonItem = commitBarButtonItem
case .push:
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
}
}
}
// MARK: - Navigation
extension PlayerEditionViewController {
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
// Force keyboard to dismiss early
view.endEditing(true)
@@ -55,31 +66,24 @@ extension PlayerEditionViewController {
override func willMove(toParent parent: UIViewController?) {
super.willMove(toParent: parent)
if case .push = presentation, parent == nil {
// Self is popping from its navigation controller
saveChanges()
}
}
private func configureNavigationItem() {
guard isViewLoaded else { return }
if let presentation = presentation {
switch presentation {
case .modal:
navigationItem.leftBarButtonItem = cancelBarButtonItem
navigationItem.rightBarButtonItem = commitBarButtonItem
case .push:
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
switch presentation! {
case .modal:
break
case .push:
if parent == nil {
// Self is popping from its navigation controller
saveChanges()
}
}
}
}
// MARK: - Form
extension PlayerEditionViewController: UITextFieldDelegate {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
nameTextField.becomeFirstResponder()
@@ -102,32 +106,16 @@ extension PlayerEditionViewController: UITextFieldDelegate {
return false
}
@IBAction func textFieldDidChange(_ textField: UITextField) {
// User has edited the player: prevent interactive dismissal
if case .modal = presentation {
isModalInPresentation = true
}
}
private func configureForm() {
guard isViewLoaded else { return }
nameTextField.text = player.name
if player.score == 0 && player.id == nil {
scoreTextField.text = ""
} else {
scoreTextField.text = "\(player.score)"
}
}
private func saveChanges() {
guard var player = self.player else {
return
}
player.name = nameTextField.text ?? ""
player.score = scoreTextField.text.flatMap { Int($0) } ?? 0
try! AppDatabase.shared.savePlayer(&player)
self.player = player
try! dbQueue.inDatabase { db in
try player.save(db)
}
}
}
@@ -0,0 +1,267 @@
import UIKit
import GRDB
/// PlayersViewController displays the list of players.
class PlayersViewController: UITableViewController {
private enum PlayerOrdering {
case byName
case byScore
}
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
private var players: [Player] = []
private var playersCancellable: DatabaseCancellable?
private var playerCountCancellable: DatabaseCancellable?
private var playerOrdering: PlayerOrdering = .byScore {
didSet {
configureOrderingBarButtonItem()
configureTableView()
}
}
private var playersRequest: QueryInterfaceRequest<Player> {
switch playerOrdering {
case .byName:
return Player.orderedByName()
case .byScore:
return Player.orderedByScore()
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureToolbar()
configureNavigationItem()
configureTableView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isToolbarHidden = false
}
private func configureToolbar() {
toolbarItems = [
UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)),
]
}
private func configureNavigationItem() {
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
configureOrderingBarButtonItem()
configureTitle()
}
private func configureOrderingBarButtonItem() {
switch playerOrdering {
case .byScore:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Score ▼",
style: .plain,
target: self, action: #selector(sortByName))
case .byName:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Name ▲",
style: .plain,
target: self, action: #selector(sortByScore))
}
}
private func configureTitle() {
// Track changes in the number of players
let observation = ValueObservation.tracking { db in
try Player.fetchCount(db)
}
playerCountCancellable = observation.start(
in: dbQueue,
scheduling: .immediate,
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 configureTableView() {
// Track changes in the list of players
let request = self.playersRequest
let observation = ValueObservation.tracking { db in
try request.fetchAll(db)
}
playersCancellable = observation.start(
in: dbQueue,
scheduling: .immediate,
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(players)
})
}
private func updateTableView(_ players: [Player]) {
// 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)
}
}
// MARK: - Navigation
extension PlayersViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Edit" {
let player = players[tableView.indexPathForSelectedRow!.row]
let controller = segue.destination as! PlayerEditionViewController
controller.title = player.name
controller.player = player
controller.presentation = .push
}
else if segue.identifier == "New" {
setEditing(false, animated: true)
let navigationController = segue.destination as! UINavigationController
let controller = navigationController.viewControllers.first as! PlayerEditionViewController
controller.title = "New Player"
controller.player = Player(id: nil, name: "", score: 0)
controller.presentation = .modal
}
}
@IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) {
// Player creation cancelled
}
@IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) {
// Player creation committed
}
}
// MARK: - UITableViewDataSource
extension PlayersViewController {
override func 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
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
// Delete the player
let player = players[indexPath.row]
try! dbQueue.write { db in
_ = try player.delete(db)
}
}
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
let player = players[indexPath.row]
if player.name.isEmpty {
cell.textLabel?.text = "-"
} else {
cell.textLabel?.text = player.name
}
cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point"
}
}
// MARK: - Actions
extension PlayersViewController {
@IBAction func sortByName() {
setEditing(false, animated: true)
playerOrdering = .byName
}
@IBAction func sortByScore() {
setEditing(false, animated: true)
playerOrdering = .byScore
}
@IBAction func deletePlayers() {
setEditing(false, animated: true)
try! dbQueue.write { db in
_ = try Player.deleteAll(db)
}
}
@IBAction func refresh() {
setEditing(false, animated: true)
refreshPlayers()
}
@IBAction func stressTest() {
setEditing(false, animated: true)
for _ in 0..<50 {
DispatchQueue.global().async {
self.refreshPlayers()
}
}
}
private func refreshPlayers() {
try! dbQueue.write { db in
if try Player.fetchCount(db) == 0 {
// Insert new random players
for _ in 0..<8 {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
} else {
// Insert a player
if Bool.random() {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
// Delete a random player
if Bool.random() {
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
}
// Update some players
for var player in try Player.fetchAll(db) where Bool.random() {
player.score = Player.randomScore()
try player.update(db)
}
}
}
}
}
@@ -1,116 +0,0 @@
{
"images" : [
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "icon_20pt@2x.png",
"scale" : "2x"
},
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "icon_20pt@3x.png",
"scale" : "3x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "icon_29pt@2x.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "icon_29pt@3x.png",
"scale" : "3x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "icon_40pt@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "icon_40pt@3x.png",
"scale" : "3x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "icon_60pt@2x.png",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "icon_60pt@3x.png",
"scale" : "3x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "icon_20pt.png",
"scale" : "1x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "icon_20pt@2x-1.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "icon_29pt.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "icon_29pt@2x-1.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "icon_40pt.png",
"scale" : "1x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "icon_40pt@2x-1.png",
"scale" : "2x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "icon_76pt.png",
"scale" : "1x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "icon_76pt@2x.png",
"scale" : "2x"
},
{
"size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "icon_83.5@2x.png",
"scale" : "2x"
},
{
"size" : "1024x1024",
"idiom" : "ios-marketing",
"filename" : "Icon.png",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 329 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

@@ -1,6 +0,0 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -1,12 +0,0 @@
{
"images" : [
{
"filename" : "LaunchIcon.pdf",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -1,38 +0,0 @@
<?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">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="LaunchIcon" translatesAutoresizingMaskIntoConstraints="NO" id="10v-qH-Qer">
<rect key="frame" x="123.5" y="334.5" width="167" height="237"/>
</imageView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="10v-qH-Qer" firstAttribute="centerX" secondItem="5Q0-b7-anu" secondAttribute="centerX" id="CgU-Ob-iCK"/>
<constraint firstItem="10v-qH-Qer" firstAttribute="centerY" secondItem="5Q0-b7-anu" secondAttribute="centerY" id="l2h-yP-koC"/>
</constraints>
<viewLayoutGuide key="safeArea" id="5Q0-b7-anu"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
<resources>
<image name="LaunchIcon" width="167" height="237"/>
</resources>
</document>
@@ -1,40 +0,0 @@
import UIKit
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).
guard let _ = (scene as? UIWindowScene) else { return }
}
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.
}
}
@@ -1,214 +0,0 @@
import UIKit
import GRDB
/// PlayerListViewController displays the list of players.
class PlayerListViewController: UITableViewController {
private enum PlayerOrdering {
case byName
case byScore
}
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
private var dataSource: PlayerDataSource!
private var animatesPlayersChange = false // Don't animate first update
private var playersCancellable: DatabaseCancellable?
private var playerOrdering: PlayerOrdering = .byScore {
didSet {
configureOrderingBarButtonItem()
observePlayers()
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureToolbar()
configureNavigationItem()
configureDataSource()
observePlayers()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isToolbarHidden = false
}
private func configureToolbar() {
toolbarItems = [
UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(image: UIImage(systemName: "tornado"), style: .plain, target: self, action: #selector(stressTest)),
]
}
private func configureNavigationItem() {
navigationItem.backBarButtonItem = UIBarButtonItem(
title: "Players", style: .plain,
target: nil, action: nil)
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
configureOrderingBarButtonItem()
}
private func configureOrderingBarButtonItem() {
switch playerOrdering {
case .byScore:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Score ▼",
style: .plain,
target: self, action: #selector(sortByName))
case .byName:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Name ▲",
style: .plain,
target: self, action: #selector(sortByScore))
}
}
private func 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 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 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
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)
})
}
}
}
// MARK: - Navigation
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,
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 }
setEditing(false, animated: true)
controller.title = "New Player"
controller.player = Player(id: nil, name: "", score: 0)
controller.presentation = .modal
}
}
@IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) {
// Player creation cancelled
}
@IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) {
// Player creation committed
}
}
// MARK: - UITableViewDataSource
/// 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 player = itemIdentifier(for: indexPath), let id = player.id {
try! AppDatabase.shared.deletePlayers(ids: [id])
}
}
}
// MARK: - Actions
extension PlayerListViewController {
@IBAction func sortByName() {
setEditing(false, animated: true)
playerOrdering = .byName
}
@IBAction func sortByScore() {
setEditing(false, animated: true)
playerOrdering = .byScore
}
@IBAction func deletePlayers() {
setEditing(false, animated: true)
try! AppDatabase.shared.deleteAllPlayers()
}
@IBAction func refresh() {
setEditing(false, animated: true)
try! AppDatabase.shared.refreshPlayers()
}
@IBAction func stressTest() {
setEditing(false, animated: true)
for _ in 0..<50 {
DispatchQueue.global().async {
try! AppDatabase.shared.refreshPlayers()
}
}
}
}
@@ -1,234 +0,0 @@
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])
}
}
@@ -1,22 +0,0 @@
<?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>
@@ -1,108 +0,0 @@
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])
}
}
+16 -27
View File
@@ -1,43 +1,32 @@
UIKit Demo Application
======================
Demo Application
================
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png" width="50%">
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/Images/GRDBDemoScreenshot.png" width="50%">
**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).
**This demo application shows you:**
> :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.
- How to define a simple [Codable Record](../../../README.md#codable-records).
- How to track database changes and animate a table view with [ValueObservation](../../../README.md#valueobservation).
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
- how to setup a database in an iOS app
- how to define a simple [Codable Record](../../README.md#codable-records)
- how to track database changes and animate a table view with [ValueObservation](../../README.md#valueobservation).
**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` 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.
`AppDatabase` defines the database for the whole application. It uses [DatabaseMigrator](../../README.md#migrations) in order to setup the database schema.
- [Player.swift](GRDBDemoiOS/Player.swift)
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). It defines the database requests used by the application.
`Player` is a [Record](../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../README.md#codable-records).
- [PlayerListViewController.swift](GRDBDemoiOS/ViewControllers/PlayerListViewController.swift)
- [PlayersViewController.swift](GRDBDemoiOS/PlayersViewController.swift)
`PlayerListViewController` displays the list of players.
`PlayersViewController` displays a list of players. It keeps its view up-to-date with [ValueObservation](../../README.md#valueobservation).
- [PlayerEditionViewController.swift](GRDBDemoiOS/ViewControllers/PlayerEditionViewController.swift)
- [PlayerEditionViewController.swift](GRDBDemoiOS/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.
Loaded 100 of 418 files, more files were not shown because too many files have changed in this diff. Show more