Compare commits

..
Author SHA1 Message Date
Gwendal Roué 60beb7cd9c DocC: document extensions 2023-06-17 17:03:55 +02:00
Gwendal Roué 284a4ee1ac Merge branch 'development' 2023-06-17 12:59:06 +02:00
Gwendal Roué b27e378cfa v6.15.1 2023-06-17 12:04:26 +02:00
Gwendal Roué 459726f9af Improve documentation of erase() 2023-06-15 14:17:48 +02:00
Gwendal Roué 4f00e405c3 CHANGELOG 2023-06-11 15:40:02 +02:00
Gwendal Roué 87f4d816e6 Merge pull request #1391 from groue/dev/issue-1390
Fix upsert in FTS5-synchronized tables
2023-06-11 15:36:52 +02:00
Gwendal Roué ea7ebe1ff5 Fix failing test for #1390 2023-06-11 13:15:55 +02:00
Gwendal Roué 89899432ba Failing test for #1390 2023-06-11 13:15:55 +02:00
Gwendal Roué 3a1c211746 Address #1389 by forcing the user to specify a tracked region
This is technically a breaking change, but nobody will notice it.
2023-06-08 12:17:27 +02:00
Gwendal Roué c3664e2b16 Fix Xcode 15 DocC warnings 2023-06-06 08:15:02 +02:00
Gwendal Roué ea1353bd6c Remove invalid documentation link 2023-06-06 08:13:43 +02:00
Gwendal Roué 4a5d4d6e49 Fix Xcode 15 warnings 2023-06-06 08:06:06 +02:00
Gwendal Roué c85abdba86 Fix typo 2023-06-02 16:13:51 +02:00
Gwendal Roué 57aa4c30bf Merge branch 'development' 2023-06-02 16:07:14 +02:00
Gwendal Roué 67b7941129 v6.15.0 2023-06-02 15:39:29 +02:00
Gwendal Roué db01b0063c Fix a test that relied on observation of every single changes 2023-06-02 15:39:26 +02:00
Gwendal Roué e1ddc8154f Merge pull request #1382 from groue/dev/request-all
Add `DerivableRequest.all()`
2023-06-02 13:34:43 +02:00
Gwendal Roué e637c156a2 CHANGELOG 2023-06-02 13:31:19 +02:00
Gwendal Roué 60ad8a809a Tests for FilteredRequest.all() and none() 2023-06-02 13:31:02 +02:00
Gwendal Roué 84ac401886 Add FilteredRequest.all()
This method does nothing: it returns `self`. It exists in order to match `none()`.
2023-06-02 13:31:02 +02:00
Gwendal Roué 26b875f64c Merge pull request #1384 from groue/dev/issue-1383
Allow ValueObservation to start from a truncated wal file
2023-06-02 13:29:27 +02:00
Gwendal Roué fdc8abfdbe CHANGELOG 2023-06-02 12:07:35 +02:00
Gwendal Roué fc641092f7 Document how truncating wal checkpoints impact ValueObservation 2023-06-02 12:04:28 +02:00
Gwendal Roué 63d360053b Fix typo and obsolete comments 2023-06-02 10:20:42 +02:00
Gwendal Roué dc440d5a8f Fix failing tests for non-empty wal files on DatabasePool creation 2023-06-02 09:44:18 +02:00
Gwendal Roué 5ab0d18055 Failing tests for non-empty wal files on DatabasePool creation 2023-06-02 09:35:51 +02:00
Gwendal Roué 437b800d8c Add test for the SQLite file provided by @kustra
https://github.com/groue/GRDB.swift/issues/1383#issuecomment-1572897011
2023-06-02 08:34:14 +02:00
Gwendal Roué b840babb55 Document the intent of #1383 regression tests 2023-06-01 20:15:05 +02:00
Gwendal Roué 725d4a3fba When a wal snapshot can't be created, ValueConcurrentObserver fallbacks to plain reads
This commit fixes #1383
2023-06-01 20:00:04 +02:00
Gwendal Roué 4ab8ac8d3f Failing test for #1383 (async version) 2023-06-01 19:53:34 +02:00
Gwendal Roué 73b279b5c1 Document methods that fail if the wal file is missing or truncated 2023-06-01 19:15:21 +02:00
Gwendal Roué fa681fb8c6 Enhance error message when WALSnapshot initializer fails 2023-06-01 19:07:28 +02:00
Gwendal Roué cedcfbe330 Mark opportunities for snapshot creation failure (including #1383) 2023-06-01 17:26:04 +02:00
Gwendal Roué abd3ba39b1 Explicit tests that a DatabasePool can read from a new instance, and from a truncated wal file 2023-06-01 17:20:25 +02:00
Gwendal Roué d66d2118b5 Failing test for #1383 2023-06-01 17:05:06 +02:00
Gwendal Roué 0a92a99223 Merge branch 'development' 2023-05-25 18:29:47 +02:00
Gwendal Roué 19e5e62098 v6.14.0 2023-05-25 18:29:15 +02:00
Gwendal Roué d948e37388 CHANGELOG 2023-05-25 18:25:04 +02:00
Gwendal Roué 60de81633e Merge pull request #1379 from groue/dev/default-index-name
Create indexes with a default name
2023-05-25 18:24:06 +02:00
Gwendal Roué c02139c045 Default name for newly created indexes 2023-05-25 09:03:09 +02:00
Gwendal Roué 93bd527984 Merge pull request #1376 from groue/dev/bitwise-operations
Bitwise operations
2023-05-23 14:03:01 +02:00
Gwendal Roué 157d02b55c CHANGELOG 2023-05-23 08:21:35 +02:00
Gwendal Roué 82d28b3167 Bitwise assignment operators &= |= <<= >>= 2023-05-23 08:16:14 +02:00
Gwendal Roué 717c2836ec Bitwise operators & | ~ << >> 2023-05-23 08:15:04 +02:00
Gwendal Roué cf8fa0e5f8 Merge branch 'development' 2023-05-15 20:06:01 +02:00
Gwendal Roué 84ef0a92da v6.13.0 2023-05-15 20:05:30 +02:00
Gwendal Roué 2ae000df43 CHANGELOG 2023-05-15 19:05:30 +02:00
Gwendal Roué 738a187f68 Merge pull request #1373 from groue/dev/issue-1371
Disallow string literals in check()
2023-05-15 18:57:29 +02:00
Gwendal Roué 4ff057ac3b Deprecate table constraints built from SQLExpressible - prefer SQLSpecificExpressible instead
Fixes #1371
2023-05-15 12:45:33 +02:00
Gwendal Roué 0d49d7612f Enhance wording 2023-05-01 12:16:48 +02:00
Gwendal Roué 342b81f65e Update dark logo 2023-04-30 12:55:56 +02:00
Gwendal Roué a651f34f67 Upgrade performance test dependencies 2023-04-30 12:20:21 +02:00
Gwendal Roué 5475dc98dc Merge branch 'development' 2023-04-29 18:29:02 +02:00
Gwendal Roué 3692ba2293 v6.12.0 2023-04-29 17:37:22 +02:00
Gwendal Roué 266efa041c Expose FetchableRecordDecoder 2023-04-29 17:15:54 +02:00
Gwendal Roué ebb2f7346d Cleanup FTS5 documentation 2023-04-29 16:50:15 +02:00
Gwendal Roué f955e5fabc Merge pull request #1364 from groue/issue1362-test
Fix ValueObservation deadlock
2023-04-29 16:34:58 +02:00
Gwendal Roué 65c803a110 Fix #1362 2023-04-29 13:24:46 +02:00
Gwendal Roué 8b1b3b0396 Fix tests that relied on observation of every single changes 2023-04-29 12:47:25 +02:00
Gwendal Roué bf28d1bd85 Disable xcpretty on $CI 2023-04-29 12:47:15 +02:00
Gwendal Roué 45edf58f9e Refactor ValueObservationRecorder matching test 2023-04-29 12:47:00 +02:00
Gwendal Roué d07e8bd3a0 The scenario that leads to the #1362 deadlock 2023-04-18 18:22:47 +02:00
Matt Gallagher 7feaa748a4 Removed some unneeded configuration from the test. 2023-04-18 13:06:05 +10:00
Matt Gallagher c159638498 A test demonstrating deadlock when observer count exceeds size of DatabasePool. 2023-04-18 12:48:06 +10:00
Gwendal Roué 5aa385094b Merge branch 'development' 2023-04-17 20:20:50 +02:00
Gwendal Roué 1cd20176c6 v6.11.0 2023-04-17 20:20:30 +02:00
Gwendal Roué 06891e99e1 Prepare for release 2023-04-17 20:20:30 +02:00
Gwendal Roué d5f38a6a24 Fix Swiftlint warning 2023-04-17 19:17:50 +02:00
Gwendal Roué 68d23a5f33 README layout 2023-04-17 08:36:32 +02:00
Gwendal Roué 75f92f6f14 Dark logo 2023-04-17 08:35:31 +02:00
Gwendal Roué 6c70ee6b77 Remove the Swift language versions 2023-04-16 16:51:33 +02:00
Gwendal Roué c8ae3cb61c Update usage sample code 2023-04-16 14:07:43 +02:00
Gwendal Roué dd4d3e35f3 Concurrency Guide layout 2023-04-16 13:27:11 +02:00
Gwendal Roué 7b2619e757 Refactor README introduction 2023-04-16 13:25:24 +02:00
Gwendal Roué a7b9a27c51 DocC home page layout 2023-04-16 13:09:31 +02:00
Gwendal Roué fcfd6e9028 ValueConcurrentObserver releases its initial WAL transaction earlier 2023-04-15 11:59:19 +02:00
Gwendal Roué 9011f71247 Fix tests for unavailable wal snapshots 2023-04-15 09:50:46 +02:00
Gwendal Roué 069bce217d Attempts at finding regression tests for #1362 2023-04-14 08:28:34 +02:00
Gwendal Roué 5a91340671 CHANGELOG 2023-04-13 08:02:41 +02:00
Gwendal Roué ba2e3cb468 Merge pull request #1361 from groue/dev/issue-1360
DatabaseMigrator.eraseDatabaseOnSchemaChange ignores internal schema objects
2023-04-13 08:00:05 +02:00
Gwendal Roué f633be4ba1 Fix test for #1360 2023-04-12 08:02:38 +02:00
Gwendal Roué 4074fcfcc7 Failing test for #1360 2023-04-12 08:00:19 +02:00
Gwendal Roué 18cdf4956e Fix typos 2023-04-10 16:52:03 +02:00
Gwendal Roué 18e06a78a3 Merge branch 'development' 2023-04-10 15:06:33 +02:00
Gwendal Roué 065ca71876 v6.10.2 2023-04-10 14:16:41 +02:00
Gwendal Roué 859a1d6184 Enhance Recommended Practices for Designing Record Types 2023-04-10 14:11:39 +02:00
Gwendal Roué f2ea4e91db CHANGELOG 2023-04-10 11:32:12 +02:00
Gwendal Roué 1add9a9752 Fix incorrect test 2023-04-10 11:31:19 +02:00
Gwendal Roué 17c3f82f50 Remove weird Xcode error regarding the Scripts "project" 2023-04-10 11:31:19 +02:00
Gwendal Roué 52a3d6ba23 Move the "Recommended Practices for Designing Record Types" to DocC 2023-04-10 09:51:38 +02:00
Gwendal Roué 54007a9ce1 Refactor demo apps for enhanced configuration management 2023-04-09 11:40:40 +02:00
Gwendal Roué 77d8a46039 Remove obsolete TODOs 2023-04-08 12:30:55 +02:00
Gwendal Roué f6e695a21d More explicit any/some 2023-04-08 12:01:59 +02:00
Gwendal Roué 3184334535 Merge branch 'development' 2023-04-01 17:22:35 +02:00
Gwendal Roué 12e3923af1 v6.10.1 2023-04-01 16:01:43 +02:00
Gwendal Roué b81e858ca0 Better fix for #1357
Previous fix would not correctly address #1357 when invalid double-quoted identifiers are interpreted as string literals (Configuration.acceptsDoubleQuotedStringLiterals = true, or SQLCipher 3)
2023-04-01 14:59:42 +02:00
Gwendal Roué 82f300e534 GitHub actions: Xcode 14.2 2023-04-01 14:30:57 +02:00
Gwendal Roué 9df1cfd110 CHANGELOG 2023-04-01 14:12:50 +02:00
Gwendal Roué 373fe467d6 Fix failing test for #1357 2023-04-01 14:09:50 +02:00
Gwendal Roué 81eb6b128f Failing test for #1357 2023-04-01 14:09:50 +02:00
Gwendal Roué c7ee12eff7 Remove deprecated swiftlint rule 2023-04-01 13:14:45 +02:00
Gwendal Roué 89330daa52 Use xcbeautify when available 2023-04-01 13:05:43 +02:00
Gwendal Roué e408bd17d8 Fix Swiftlint warning 2023-04-01 13:04:52 +02:00
Gwendal Roué 99ddc5e13c Makefile: add explicit macOS destinations 2023-04-01 12:56:44 +02:00
Gwendal Roué 4c0cc84c2d Improve DatabaseEventPredicate usage with SQLITE_ENABLE_PREUPDATE_HOOK 2023-03-31 08:02:04 +02:00
Gwendal Roué 4762f8bb36 Fix spawnConcurrentRead documentation 2023-03-29 13:02:49 +02:00
Gwendal Roué 7e6f71912c Enhance DatabaseQueue read-only transactions 2023-03-29 13:02:31 +02:00
Gwendal Roué 6b311941b1 Remove WWDCCompanion from the release process 2023-03-22 18:40:48 +01:00
Gwendal Roué 5facc24ebb Fix compiler warnings for Swift 5.8 2023-03-22 18:40:37 +01:00
Gwendal Roué 018ae03f8e Improve DatabaseEventPredicate usage 2023-03-22 08:30:21 +01:00
Gwendal Roué 52aef76b63 Fix Swiftlint warning 2023-03-22 08:25:37 +01:00
Gwendal Roué 2fa5ca767f WALSnapshot is only available when the SQLite feature is
Since #1350 we no longer need to expose it and check for failures at runtime.
2023-03-20 15:05:17 +01:00
154 changed files with 3667 additions and 2042 deletions

No files matched your search

+32 -12
View File
@@ -38,6 +38,18 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
destination: "OS=16.2,name=iPhone 14"
name: "iOS"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
destination: "OS=16.1,name=Apple TV"
name: "tvOS"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
destination: "platform=macOS"
@@ -46,10 +58,6 @@ jobs:
runsOn: macOS-12
destination: "OS=16.1,name=iPhone 14"
name: "iOS"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
destination: "OS=16.1,name=Apple TV"
name: "tvOS"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
destination: "platform=macOS"
@@ -72,6 +80,9 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
name: "Xcode 14.1"
@@ -92,9 +103,9 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.1.app"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.1"
name: "Xcode 14.2"
steps:
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
@@ -109,9 +120,12 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.1.app"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.1"
name: "Xcode 14.2"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
@@ -126,9 +140,12 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.1.app"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.1"
name: "Xcode 14.2"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
@@ -143,9 +160,12 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.1.app"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.1"
name: "Xcode 14.2"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
+64 -1
View File
@@ -7,7 +7,12 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 6.x Releases
- `6.10.x` Releases - [6.10.0](#6100)
- `6.15.x` Releases - [6.15.0](#6150) - [6.15.1](#6151)
- `6.14.x` Releases - [6.14.0](#6140)
- `6.13.x` Releases - [6.13.0](#6130)
- `6.12.x` Releases - [6.12.0](#6120)
- `6.11.x` Releases - [6.11.0](#6110)
- `6.10.x` Releases - [6.10.0](#6100) - [6.10.1](#6101) - [6.10.2](#6102)
- `6.9.x` Releases - [6.9.0](#690) - [6.9.1](#691) - [6.9.2](#692)
- `6.8.x` Releases - [6.8.0](#680)
- `6.7.x` Releases - [6.7.0](#670)
@@ -108,6 +113,64 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 6.15.1
Released June 17, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.15.0...v6.15.1)
- **Fixed**: Fixed Xcode 15 warnings
- **Fixed**: [#1391](https://github.com/groue/GRDB.swift/pull/1391) Fix upsert in FTS5-synchronized tables
## 6.15.0
Released June 2, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.14.0...v6.15.0)
- **New**: [#1382](https://github.com/groue/GRDB.swift/pull/1382) Add `DerivableRequest.all()`
- **New**: [#1384](https://github.com/groue/GRDB.swift/pull/1384) Allow ValueObservation to start from a truncated wal file
- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`.
## 6.14.0
Released May 25, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.13.0...v6.14.0)
- **New**: [#1376](https://github.com/groue/GRDB.swift/pull/1376) Bitwise operations
- **New**: [#1379](https://github.com/groue/GRDB.swift/pull/1379) Create indexes with a default name
## 6.13.0
Released May 15, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.12.0...v6.13.0)
- **New**: [#1373](https://github.com/groue/GRDB.swift/pull/1373) Deprecate string literal arguments for `TableDefinition.check()`
## 6.12.0
Released April 29, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.11.0...v6.12.0)
- **Fixed**: [#1364](https://github.com/groue/GRDB.swift/pull/1364) Fix a regression introduced with version 6.10.0, where starting multiple observations while performing writes could create a deadlock.
- **New**: `FetchableRecordDecoder` is an object that decodes `Decodable` fetchable records from database rows. You may want to use this decoder when you want to use the `Decodable` initializer from `init(row: Row)`.
## 6.11.0
Released April 17, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.10.2...v6.11.0)
- **New**: [#1361](https://github.com/groue/GRDB.swift/pull/1361) `DatabaseMigrator.eraseDatabaseOnSchemaChange` ignores internal schema objects
## 6.10.2
Released April 10, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.10.1...v6.10.2)
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC.
- **Documentation Update**: The [Demo Applications](Documentation/DemoApps/) demonstrate how their `AppDatabase` "database manager" can provide a base database configuration.
## 6.10.1
Released April 1, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.10.0...v6.10.1)
- **Fixed**: [#1357](https://github.com/groue/GRDB.swift/pull/1357) `QueryInterfaceRequest.fetchCount` no longer executes invalid SQL queries for some requests.
## 6.10.0
Released March 20, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.9.2...v6.10.0)
+3 -3
View File
@@ -2000,7 +2000,7 @@ Each association included in the request can feed a property of the decoded reco
- [Decoding a Joined Request with a Decodable Record]
- [Decoding a Joined Request with FetchableRecord]
- [Debugging Request Decoding]
- [Good Practices for Designing Record Types] - in this general guide about records, check out the "Compose Records" chapter.
- [Recommended Practices for Designing Record Types] - in this general guide about records, check out the "Associations" chapter.
## The Structure of a Joined Request
@@ -2860,7 +2860,7 @@ extension DerivableRequest<Book> {
}
```
See [Good Practices for Designing Record Types] for more information.
See [Recommended Practices for Designing Record Types] for more information.
## Known Issues
@@ -2999,7 +2999,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Row Adapters]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter
[query interface requests]: ../README.md#requests
[TableRecord]: ../README.md#tablerecord-protocol
[Good Practices for Designing Record Types]: GoodPracticesForDesigningRecordTypes.md
[Recommended Practices for Designing Record Types]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices
[regular aggregating methods]: ../README.md#fetching-aggregated-values
[Record class]: ../README.md#record-class
[EncodableRecord]: ../README.md#persistablerecord-protocol
@@ -61,6 +61,13 @@
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "SQL_TRACE"
value = "1"
isEnabled = "NO">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,12 +1,29 @@
import Foundation
import GRDB
import os.log
/// AppDatabase lets the application access the database.
/// A database of players.
///
/// It applies the pratices recommended at
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
/// You create an `AppDatabase` with a connection to an SQLite database
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
///
/// Create those connections with a configuration returned from
/// `AppDatabase/makeConfiguration(_:)`.
///
/// For example:
///
/// ```swift
/// // Create an in-memory AppDatabase
/// let config = AppDatabase.makeConfiguration()
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
struct AppDatabase {
/// Creates an `AppDatabase`, and make sure the database schema is ready.
/// Creates an `AppDatabase`, and makes sure the database schema
/// is ready.
///
/// - important: Create the `DatabaseWriter` with a configuration
/// returned by ``makeConfiguration(_:)``.
init(_ dbWriter: any DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
@@ -19,18 +36,67 @@ struct AppDatabase {
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
private let dbWriter: any DatabaseWriter
}
// MARK: - Database Configuration
extension AppDatabase {
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
/// Returns a database configuration suited for `PlayerRepository`.
///
/// SQL statements are logged if the `SQL_TRACE` environment variable
/// is set.
///
/// - parameter base: A base configuration.
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
var config = base
// An opportunity to add required custom SQL functions or
// collations, if needed:
// config.prepareDatabase { db in
// db.add(function: ...)
// }
// Log SQL statements if the `SQL_TRACE` environment variable is set.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
config.prepareDatabase { db in
db.trace {
// It's ok to log statements publicly. Sensitive
// information (statement arguments) are not logged
// unless config.publicStatementArguments is set
// (see below).
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
}
}
}
#if DEBUG
// Protect sensitive information by enabling verbose debugging in
// DEBUG builds only.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
config.publicStatementArguments = true
#endif
return config
}
}
// MARK: - Database Migrations
extension AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
#if DEBUG
// Speed up development by nuking the database when migrations change
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
@@ -52,6 +118,7 @@ struct AppDatabase {
}
// MARK: - Database Access: Writes
// The write methods execute invariant-preserving database transactions.
extension AppDatabase {
/// A validation error that prevents some players from being saved into
@@ -127,8 +194,8 @@ extension AppDatabase {
}
}
}
static let uiTestPlayers = [
private static let uiTestPlayers = [
Player(id: nil, name: "Arthur", score: 5),
Player(id: nil, name: "Barbara", score: 6),
Player(id: nil, name: "Craig", score: 8),
@@ -137,7 +204,7 @@ extension AppDatabase {
Player(id: nil, name: "Frederik", score: 2),
Player(id: nil, name: "Gilbert", score: 7),
Player(id: nil, name: "Henriette", score: 3)]
func createPlayersForUITests() throws {
try dbWriter.write { db in
try AppDatabase.uiTestPlayers.forEach { player in
@@ -7,26 +7,31 @@ extension AppDatabase {
private static func makeShared() -> AppDatabase {
do {
// Pick 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)
// Apply recommendations from
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
//
// Create the "Application Support/Database" directory if needed
let fileManager = FileManager.default
let appSupportURL = try fileManager.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
// Support for tests: delete the database if requested
if CommandLine.arguments.contains("-reset") {
try? fileManager.removeItem(at: folderURL)
try? fileManager.removeItem(at: directoryURL)
}
// Create the database folder if needed
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
// Connect to a database on disk
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Open or create the database
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
NSLog("Database stored at \(databaseURL.path)")
let dbPool = try DatabasePool(
path: databaseURL.path,
// Use default AppDatabase configuration
configuration: AppDatabase.makeConfiguration())
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
@@ -59,7 +64,7 @@ extension AppDatabase {
static func empty() -> AppDatabase {
// Connect to an in-memory database
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbQueue = try! DatabaseQueue()
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
return try! AppDatabase(dbQueue)
}
@@ -69,8 +69,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// 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>
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
extension DerivableRequest<Player> {
/// A request of players ordered by name.
///
@@ -5,7 +5,7 @@ import GRDB
class AppDatabaseTests: XCTestCase {
func test_database_schema() throws {
// Given an empty database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
// When we instantiate an AppDatabase
_ = try AppDatabase(dbQueue)
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_inserts() async throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we save a new player
@@ -35,7 +35,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_updates() async throws {
// Given a players database that contains a player
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = try await dbQueue.write { db in
try Player(id: nil, name: "Arthur", score: 100).inserted(db)
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
func test_deletePlayers() async throws {
// Given a players database that contains four players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
let playerIds: [Int64] = try await dbQueue.write { db in
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
func test_deleteAllPlayers() async throws {
// Given a players database that contains players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
try await dbQueue.write { db in
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
@@ -102,7 +102,7 @@ class AppDatabaseTests: XCTestCase {
func test_refreshPlayers_populates_an_empty_database() async throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we refresh players
@@ -115,7 +115,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we create random players
@@ -127,7 +127,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
// Given a players database that contains one player
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -5,7 +5,7 @@ import GRDB
class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
@@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
func testInsert() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
func testRoundtrip() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player and fetch the player with the same id
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScore() throws {
// Given a players database that contains players with distinct scores
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScoreSortsIdenticalScoresByName() throws {
// Given a players database that contains players with common scores
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
func testOrderedByName() throws {
// Given a players database that contains players with distinct names
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -14,7 +14,7 @@ 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 an async sequence built from [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
- How to feed SwiftUI previews with a transient database.
**Files of interest:**
@@ -61,6 +61,13 @@
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "SQL_TRACE"
value = "1"
isEnabled = "NO">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,13 +1,29 @@
import Combine
import Foundation
import GRDB
import os.log
/// AppDatabase lets the application access the database.
/// A database of players.
///
/// It applies the pratices recommended at
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
/// You create an `AppDatabase` with a connection to an SQLite database
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
///
/// Create those connections with a configuration returned from
/// `AppDatabase/makeConfiguration(_:)`.
///
/// For example:
///
/// ```swift
/// // Create an in-memory AppDatabase
/// let config = AppDatabase.makeConfiguration()
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
struct AppDatabase {
/// Creates an `AppDatabase`, and make sure the database schema is ready.
/// Creates an `AppDatabase`, and makes sure the database schema
/// is ready.
///
/// - important: Create the `DatabaseWriter` with a configuration
/// returned by ``makeConfiguration(_:)``.
init(_ dbWriter: any DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
@@ -20,18 +36,67 @@ struct AppDatabase {
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
private let dbWriter: any DatabaseWriter
}
// MARK: - Database Configuration
extension AppDatabase {
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
/// Returns a database configuration suited for `PlayerRepository`.
///
/// SQL statements are logged if the `SQL_TRACE` environment variable
/// is set.
///
/// - parameter base: A base configuration.
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
var config = base
// An opportunity to add required custom SQL functions or
// collations, if needed:
// config.prepareDatabase { db in
// db.add(function: ...)
// }
// Log SQL statements if the `SQL_TRACE` environment variable is set.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
config.prepareDatabase { db in
db.trace {
// It's ok to log statements publicly. Sensitive
// information (statement arguments) are not logged
// unless config.publicStatementArguments is set
// (see below).
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
}
}
}
#if DEBUG
// Protect sensitive information by enabling verbose debugging in
// DEBUG builds only.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
config.publicStatementArguments = true
#endif
return config
}
}
// MARK: - Database Migrations
extension AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
#if DEBUG
// Speed up development by nuking the database when migrations change
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
@@ -53,6 +118,7 @@ struct AppDatabase {
}
// MARK: - Database Access: Writes
// The write methods execute invariant-preserving database transactions.
extension AppDatabase {
/// A validation error that prevents some players from being saved into
@@ -128,8 +194,8 @@ extension AppDatabase {
}
}
}
static let uiTestPlayers = [
private static let uiTestPlayers = [
Player(id: nil, name: "Arthur", score: 5),
Player(id: nil, name: "Barbara", score: 6),
Player(id: nil, name: "Craig", score: 8),
@@ -138,7 +204,7 @@ extension AppDatabase {
Player(id: nil, name: "Frederik", score: 2),
Player(id: nil, name: "Gilbert", score: 7),
Player(id: nil, name: "Henriette", score: 3)]
func createPlayersForUITests() throws {
try dbWriter.write { db in
try AppDatabase.uiTestPlayers.forEach { player in
@@ -7,26 +7,31 @@ extension AppDatabase {
private static func makeShared() -> AppDatabase {
do {
// Pick 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)
// Apply recommendations from
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
//
// Create the "Application Support/Database" directory if needed
let fileManager = FileManager.default
let appSupportURL = try fileManager.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
// Support for tests: delete the database if requested
if CommandLine.arguments.contains("-reset") {
try? fileManager.removeItem(at: folderURL)
try? fileManager.removeItem(at: directoryURL)
}
// Create the database folder if needed
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
// Connect to a database on disk
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Open or create the database
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
NSLog("Database stored at \(databaseURL.path)")
let dbPool = try DatabasePool(
path: databaseURL.path,
// Use default AppDatabase configuration
configuration: AppDatabase.makeConfiguration())
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
@@ -59,7 +64,7 @@ extension AppDatabase {
static func empty() -> AppDatabase {
// Connect to an in-memory database
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbQueue = try! DatabaseQueue()
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
return try! AppDatabase(dbQueue)
}
@@ -69,8 +69,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// 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>
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
extension DerivableRequest<Player> {
/// A request of players ordered by name.
///
@@ -5,7 +5,7 @@ import GRDB
class AppDatabaseTests: XCTestCase {
func test_database_schema() throws {
// Given an empty database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
// When we instantiate an AppDatabase
_ = try AppDatabase(dbQueue)
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_inserts() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we save a new player
@@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_updates() throws {
// Given a players database that contains a player
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
func test_deletePlayers() throws {
// Given a players database that contains four players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
func test_deleteAllPlayers() throws {
// Given a players database that contains players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase {
func test_refreshPlayers_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we refresh players
@@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we create random players
@@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
// Given a players database that contains one player
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -5,7 +5,7 @@ import GRDB
class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
@@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
func testInsert() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
func testRoundtrip() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player and fetch the player with the same id
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScore() throws {
// Given a players database that contains players with distinct scores
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScoreSortsIdenticalScoresByName() throws {
// Given a players database that contains players with common scores
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
func testOrderedByName() throws {
// Given a players database that contains players with distinct names
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -14,7 +14,7 @@ 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](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) Combine publishers.
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
- How to feed SwiftUI previews with a transient database.
**Files of interest:**
@@ -61,6 +61,13 @@
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "SQL_TRACE"
value = "1"
isEnabled = "NO">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,11 +1,28 @@
import GRDB
import os.log
/// AppDatabase lets the application access the database.
/// `AppDatabase` lets the application access the 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.
/// You create an `AppDatabase` with a connection to an SQLite database
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
///
/// Create those connections with a configuration returned from
/// `AppDatabase/makeConfiguration(_:)`.
///
/// For example:
///
/// ```swift
/// // Create an in-memory AppDatabase
/// let config = AppDatabase.makeConfiguration()
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
struct AppDatabase {
/// Creates an `AppDatabase`, and makes sure the database schema
/// is ready.
///
/// - important: Create the `DatabaseWriter` with a configuration
/// returned by ``makeConfiguration(_:)``.
init(_ dbWriter: any DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
@@ -18,18 +35,67 @@ final class AppDatabase {
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
private let dbWriter: any DatabaseWriter
}
// MARK: - Database Configuration
extension AppDatabase {
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
/// Returns a database configuration suited for `PlayerRepository`.
///
/// SQL statements are logged if the `SQL_TRACE` environment variable
/// is set.
///
/// - parameter base: A base configuration.
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
var config = base
// An opportunity to add required custom SQL functions or
// collations, if needed:
// config.prepareDatabase { db in
// db.add(function: ...)
// }
// Log SQL statements if the `SQL_TRACE` environment variable is set.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
config.prepareDatabase { db in
db.trace {
// It's ok to log statements publicly. Sensitive
// information (statement arguments) are not logged
// unless config.publicStatementArguments is set
// (see below).
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
}
}
}
#if DEBUG
// Protect sensitive information by enabling verbose debugging in
// DEBUG builds only.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
config.publicStatementArguments = true
#endif
return config
}
}
// MARK: - Database Migrations
extension AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
#if DEBUG
// Speed up development by nuking the database when migrations change
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
@@ -51,6 +117,7 @@ final class AppDatabase {
}
// MARK: - Database Access: Writes
// The write methods execute invariant-preserving database transactions.
extension AppDatabase {
/// Saves (inserts or updates) a player. When the method returns, the
@@ -7,19 +7,24 @@ extension AppDatabase {
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)
// Apply recommendations from
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
//
// Create the "Application Support/Database" directory if needed
let fileManager = FileManager.default
let appSupportURL = try fileManager.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
// Connect to a database on disk
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Open or create the database
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
NSLog("Database stored at \(databaseURL.path)")
let dbPool = try DatabasePool(
path: databaseURL.path,
// Use default AppDatabase configuration
configuration: AppDatabase.makeConfiguration())
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
@@ -68,8 +68,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// 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>
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
extension DerivableRequest<Player> {
/// A request of players ordered by name.
///
@@ -5,7 +5,7 @@ import GRDB
class AppDatabaseTests: XCTestCase {
func test_database_schema() throws {
// Given an empty database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
// When we instantiate an AppDatabase
_ = try AppDatabase(dbQueue)
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_inserts() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we save a new player
@@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_updates() throws {
// Given a players database that contains a player
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
func test_deletePlayers() throws {
// Given a players database that contains four players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
func test_deleteAllPlayers() throws {
// Given a players database that contains players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase {
func test_refreshPlayers_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we refresh players
@@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we create random players
@@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
// Given a players database that contains one player
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
func testInsert() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
func testRoundtrip() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player and fetch the player with the same id
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScore() throws {
// Given a players database that contains players with distinct scores
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScoreSortsIdenticalScoresByName() throws {
// Given a players database that contains players with common scores
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
func testOrderedByName() throws {
// Given a players database that contains players with distinct names
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
+1 -1
View File
@@ -14,7 +14,7 @@ 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](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
**Files of interest:**
@@ -1,836 +1,4 @@
Good Practices for Designing Record Types
=========================================
This guide aims at helping you leverage the best of GRDB [records] and [associations].
Since GRDB sits right between low-level libraries like SQLite itself or [FMDB], and high-level ORM like [Core Data] or [Realm], you may face questions when designing the model layer of your application.
To support this guide, we'll design a simple library application that lets the user crawl through books and their authors.
- [Trust SQLite More Than Yourself]
- [Persistable Record Types are Responsible for Their Tables]
- [Record Types Hide Intimate Database Details]
- [Singleton Records]
- [Define Record Requests]
- [Compose Records]
- [How to Design Database Managers]
- [Observe the Database and Refetch when Needed]
## Trust SQLite More Than Yourself
It is important to put things in the right order. An SQLite database stored on one of your user's device is more important than the Swift code that accesses it. When a user installs a new version of your application, all the code may change, but the database remains the same.
This is why we recommend defining a **robust database schema** even before playing with record types.
SQLite is a battle-tested database. Even if you don't know it well, and aren't familiar with the SQL language, you are able to take profit from its solid foundation. It is very difficult to corrupt an SQLite database file. And it can make sure that only valid information is persisted on disk.
This is important because we developers write bugs, and some of them will ship in the wild, affecting the users of our applications. But SQLite will prevent many of those bugs from corrupting our precious users' data.
For example, if we were to define a [migration] that sets up our library database, made of books and their authors, we could write:
```swift
var migrator = DatabaseMigrator()
migrator.registerMigration("createLibrary") { db in
try db.create(table: "author") { t in // (1)
t.autoIncrementedPrimaryKey("id") // (2)
t.column("name", .text).notNull() // (3)
t.column("country", .text) // (4)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text).notNull() // (5)
t.column("authorId", .integer) // (6)
.notNull() // (7)
.indexed() // (8)
.references("author", onDelete: .cascade) // (9)
}
}
try migrator.migrate(dbQueue)
```
1. Our database table names follow the [recommended convention]: they are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
2. Each author has a unique id.
3. An author must have a name.
4. The country of an author is not always known.
5. A book must have a title.
6. The `book.authorId` column is used to link a book to the author it belongs to.
7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
8. The `book.authorId` column is indexed in order to ease the selection of an author's books.
9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
Thanks to this database schema, you can be confident that no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc.
> :bulb: **Tip**: Don't look at your local SQLite database as you look at the JSON you load from a remote server. You can't control the JSON, its format and content: your application must defend itself against wacky servers. But you can control the database. Put the database on your side, make it trustable. Learn about relational databases, and how they can help you guarantee the quality of your application data. Put as much energy as you can in the proper definition of your database schema.
>
> :bulb: **Tip**: Plan early for future versions of your application, and use [migrations].
>
> :bulb: **Tip**: In the definition of your migrations, define tables and their columns with **strings**:
>
> ```swift
> migrator.registerMigration("createLibrary") { db in
> // RECOMMENDED
> try db.create(table: "author") { t in
> t.autoIncrementedPrimaryKey("id")
> ...
> }
>
> // NOT RECOMMENDED
> try db.create(table: Author.databaseTableName) { t in
> t.autoIncrementedPrimaryKey(Author.Columns.id.name)
> ...
> }
> }
> ```
>
> By using strings, you make sure that you will not have to change the Swift code of your migrations in the future. Even if author columns eventually change. Even if the Author type eventually gets replaced with another type. Even when your startup eventually pivots and starts selling pet food. A good migration that never changes is easy to test once and for good. A good migration that never changes will run smoothly on all devices in the wild, even if a user upgrades straight from version 1.0 to version 5.0 of your application.
>
> So make sure that migrations don't use application types and values: migrations should talk to the database, only to the database, and use the database language: **strings**.
## Persistable Record Types are Responsible for Their Tables
Define one record type per database table, and make it adopt a [PersistableRecord] protocol.
In this sample code, we'll use Codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
```swift
struct Author: Codable, Identifiable {
var id: Int64?
var name: String
var country: String?
}
struct Book: Codable, Identifiable {
var id: Int64?
var authorId: Int64
var title: String
}
```
We add database powers to our types with [record protocols]. Since our records use auto-incremented ids, we provide an implementation of the `didInsert` method:
```swift
// Add Database access
extension Author: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
extension Book: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
```
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`.
> :bulb: **Tip**: When a column of a database table can't be NULL, store it in a non-optional property of your record type. On the other side, when the database may contain NULL, define an optional property.
>
> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(_:)` method:
>
> ```swift
> try dbQueue.write { db in
> var author = Author(id: nil, name: "Hermann Melville", country: "United States")
> try author.insert(db)
> print(author.id!) // Guaranteed non-nil id
> }
> ```
>
> :bulb: **Tip**: When the database table has a single-column primary key, have your record type adopt the standard [Identifiable] protocol. This allows GRDB to define type-safe id-related methods:
>
> ```swift
> let authorID: Int64 = ...
> let author: Author? = try dbQueue.read { db in
> try Author.fetchOne(db, id: authorID)
> }
> ```
Now that `Author` and `Book` can read and write in their own database tables, they are responsible for it. Make sure each record type deals with one database table, and only one database table!
## Record Types Hide Intimate Database Details
The application uses `Book` and `Author` as regular structs, using their properties. Each of those properties matches a column in the database (`Book.title`, `Author.id`), and is defined with a Swift type that is natively supported by SQLite (`String`, `Int`, etc.)
Sometimes, it happens that raw database column names and types are not a very good fit for the application.
Let's look at three examples:
1. Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. For easy debugging of the database contents, a book kind is represented as a string ("novel", "essay", etc.):
```swift
try db.create(table: "book") { t in
...
t.column("kind", .text).notNull()
}
```
In Swift, it is not a good practice to use `String` for the type of the `kind` property. We want an enum instead:
```swift
struct Book: Codable {
enum Kind: String, Codable {
case novel, poems, essay, play
}
var id: Int64?
var authorId: Int64
var title: String
var kind: Kind
}
```
In order to make it possible to use `Book.Kind` in book requests (see [Define Record Requests] below), we add this conformance:
```swift
extension Book.Kind: DatabaseValueConvertible { }
```
> :bulb: Records can pick the best suited [Value] type for their column properties (Bool, Int, String, Date, etc.) Thanks to its enum property, the `Book` record prevents unknown book kinds from entering the database.
2. GPS coordinates are usually stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
When this happens, keep column properties private, and provide sensible accessors instead:
```swift
struct Place: Codable {
var id: Int64?
var name: String
private var latitude: CLLocationDegrees
private var longitude: CLLocationDegrees
var coordinate: CLLocationCoordinate2D {
get {
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
set {
latitude = newValue.latitude
longitude = newValue.longitude
}
}
}
```
> :bulb: Private properties make it possible to hide raw columns from the rest of the application.
3. The record below exposes a `price: Decimal` property ($12.00), backed by an integer column that stores a quantity of cents (1200). An integer column is preferred because it allows SQLite to compute exact sums of prices.
```swift
struct Product: Codable {
var id: Int64?
var name: String
private var priceCents: Int
var price: Decimal {
get { Decimal(priceCents) / 100 }
set { priceCents = NSDecimalNumber(decimal: newValue * 100).intValue }
}
}
```
> :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface.
**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#persistence-callbacks) before they enter the database.
## Singleton Records
**Singleton Records** are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row.
The recommended setup for such records is described in the [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide. Go check it, and come back when you're done!
## Define Record Requests
Now that we have record types that are able to read and write in the database, we'd like to put them to good use.
> :bulb: **Tip**: Define an enumeration of columns that you will use in order to filter, sort, etc.
When your record type is a [Codable Record], derive columns from the [CodingKeys] enum:
```swift
// For a codable record
extension Author {
// Define database columns from CodingKeys
enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let country = Column(CodingKeys.country)
}
}
```
Otherwise, declare a plain `String` enum that conforms to the `ColumnExpression` protocol:
```swift
// For a non-codable record
extension Author {
// Define database columns as an enum
enum Columns: String, ColumnExpression {
case id, name, country
}
}
```
Those columns let you define requests:
```swift
try dbQueue.read { db in
// Order authors by name, in a localized case-insensitive fashion
let sortedAuthors: [Author] = try Author.all()
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
.fetchAll(db)
// French authors
let frenchAuthors: [Author] = try Author.all()
.filter(Author.Columns.country == "France")
.fetchAll(db)
}
```
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
When you find yourself build similar requests over and over in your application, you may want to define a reusable and composable request vocabulary. This will avoid repetition in your app, ease refactoring, and enable [testability](DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift).
To do so, extend the `DerivableRequest` protocol. It generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc:
```swift
// Author requests
extension DerivableRequest<Author> {
/// Order authors by name, in a localized case-insensitive fashion
func orderByName() -> Self {
let name = Author.Columns.name
return order(name.collating(.localizedCaseInsensitiveCompare))
}
/// Filters authors from a country
func filter(country: String) -> Self {
filter(Author.Columns.country == country)
}
/// Filters authors with at least one book
func havingBooks() -> Self {
having(Author.books.isEmpty == false)
}
}
```
Those methods encapsulate intimate database details, and allow you to compose database requests in a fluent and legible style:
```swift
try dbQueue.read { db in
let sortedAuthors: [Author] = try Author.all()
.orderByName()
.fetchAll(db)
let frenchAuthors: [Author] = try Author.all()
.filter(country: "France")
.fetchAll(db)
let sortedSpanishAuthorsHavingBooks: [Author] = try Author.all()
.filter(country: "Spain")
.havingBooks()
.orderByName()
.fetchAll(db)
}
```
Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(authorCountry:)` for books, below, uses the `filter(country:)` for authors:
```swift
// Book requests
extension DerivableRequest<Book> {
/// Filters books by kind
func filter(kind: Book.Kind) -> Self {
filter(Book.Columns.kind == kind)
}
/// Filters books from a country
func filter(authorCountry: String) -> Self {
// Books do not have any country column. But their author has one.
// A book is from a country if it can be joined to an author from this country:
joining(required: Book.author.filter(country: authorCountry))
}
}
try dbQueue.read { db in
let italianNovels: [Book] = try Book.all()
.filter(kind: .novel)
.filter(authorCountry: "Italy")
.fetchAll(db)
}
```
Extensions to the `DerivableRequest` protocol can not change the type of requests. This has to be expressed in an extension to `QueryInterfaceRequest`. For example:
```swift
// Author requests
extension QueryInterfaceRequest<Author> {
// Selects author ids
func selectId() -> QueryInterfaceRequest<Int64> {
selectPrimaryKey(as: Int64.self)
}
}
// IDs of French authors
let ids: [Int64] = try Author.all().filter(country: "France").selectId().fetchAll(db)
```
## Compose Records
We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
GRDB can help you do this with [associations]. In our case, each author **has many** books, and each book **belongs to** its author. Here is how you define those associations:
```swift
extension Author {
static let books = hasMany(Book.self)
}
extension Book {
static let author = belongsTo(Author.self)
}
```
Thanks to this setup, you can fetch associated records, or compute aggregated values from associated records. For example:
```swift
// Fetch all authors and their number of books
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookCount: Int
}
let authorInfos: [AuthorInfo] = try dbQueue.read { db in
let request = Author.annotated(with: Author.books.count)
return try AuthorInfo.fetchAll(db, request)
}
// Fetch all Colombian books and their authors:
struct Authorship: Decodable, FetchableRecord {
var book: Book
var author: Author
}
let authorships: [Authorship] = try dbQueue.read { db in
let request = Book.including(required: Book.author.filter(country: "Colombia"))
return try Authorship.fetchAll(db, request)
}
```
As in the sample code above, requests which feed from several associated records will often have you define extra record types, such as `AuthorInfo` and `Authorship`. Those extra record types are designed to be able to decode database requests. The names and types of their properties follow the conventions defined by [associations]. Make them conform to the Decodable and FetchableRecord protocols so that they can decode database rows in a breeze.
Unlike the primitive persistable record types `Author` and `Book`, those records can not write in the database. They are simple data types, passive views on the database content. Remember, only [Persistable Record Types are Responsible for Their Tables].
> **Note**: The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they?
>
> That is because other ORMs perform lazy loading:
>
> ```ruby
> # Ruby's Active Record
> author = Author.find(123) # fetch author
> book_count = author.books.count # lazily counts books on demand
> ```
>
> GRDB does not perform lazy loading. Lazy loading either requires records to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation] against concurrent changes. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer.
>
> This is why GRDB has removed lazy loading from the list of desirable features. Instead, it provides the tooling needed to fetch data, even complex ones, in a single and safe stroke. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information.
Granted with primitive and derived record types, your application will load the data it needs, at the moment it needs it, as below:
1. Prepare the application screen that lists all authors:
```swift
let authors: [Author] = try dbQueue.read { db in
try Author.all().orderByName().fetchAll(db)
}
```
2. Prepare the application screen that displays an author and her books:
```swift
struct AuthorInfo: Codable, FetchableRecord {
var author: Author
var books: [Book]
}
let authorId = 123
let authorInfo: AuthorInfo? = try dbQueue.read { db in
let request = Author
.filter(id: authorId)
.including(all: Author.books)
return try AuthorInfo.fetchOne(db, request)
}
```
3. Prepare the application screen that displays a book information:
```swift
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var author: Author
}
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
let request = Book
.filter(id: bookId)
.including(required: Book.author)
return try BookInfo.fetchOne(db, request)
}
```
> :bulb: **Tip**: Identify the various **graph of objects** needed by the various parts of your application. Design them independently, by composing primitive record types linked by associations. Fetch the data your application needs, at the moment it needs it, no more, no less.
A last extension on your record types will further help navigation from records to associated ones:
```swift
extension Author {
/// The request for the author's books
var books: QueryInterfaceRequest<Book> {
request(for: Author.books)
}
}
extension Book {
/// The request for the author of the book
var author: QueryInterfaceRequest<Author> {
request(for: Book.author)
}
}
```
Those properties provide an alternative way to feed our application:
1. Prepare the application screen that displays an author and her books:
```swift
struct AuthorInfo {
var author: Author
var books: [Book]
}
let authorId = 123
let authorInfo: AuthorInfo? = try dbQueue.read { db in
guard let author = try Author.fetchOne(db, id: authorId) else {
return nil
}
let books = try author.books.fetchAll(db)
return AuthorInfo(
author: author,
books: books)
}
```
2. Prepare the application screen that displays a book information:
```swift
struct BookInfo {
var book: Book
var author: Author
}
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
guard let book = try Book.fetchOne(db, id: bookId) else {
return nil
}
guard let author = try book.author.fetchOne(db) else {
return nil
}
return BookInfo(book: book, author: author)
}
```
## How to Design Database Managers
Many developers want to hide GRDB database queues and pools inside "database managers":
```swift
// LibraryManager grants access to the library database.
class LibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
}
```
> :bulb: **Tip**: Don't let your database managers create their own databases. Instead, give them a database created by, say, the ApplicationDelegate. This will allow you to efficiently test the database manager with an in-memory database, for example.
Design your database managers with the [GRDB concurrency rules] in mind.
Practically, let's start with a naive example, and gradually improve it:
```swift
// A naive manager that we will improve
class NaiveLibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
func author(id: Int64) -> Author? {
do {
return try dbQueue.read { db in
try Author.fetchOne(db, id: id)
}
} catch {
return nil
}
}
func book(id: Int64) -> Book? {
do {
return try dbQueue.read { db in
try Book.fetchOne(db, id: id)
}
} catch {
return nil
}
}
func books(writtenBy author: Author) -> [Book] {
do {
return try dbQueue.read { db in
try author.books.fetchAll(db)
}
} catch {
return []
}
}
}
```
**This manager can be improved in two ways.**
- [Embrace Errors]
- [Thread-Safety is also an Application Concern]
### Embrace Errors
Have database managers throw database errors instead of catching them.
Consider Apple's [CNContactStore](https://developer.apple.com/documentation/contacts/cncontactstore), for example. Does it hide errors when you fetch or save address book contacts? No it does not. Keychain, Media assets, File system, Core Data? No they do not hide errors either. Follow the practices of Apple engineers: do not hide errors :muscle:
Exposing errors will help you building your application:
- You will be able to inspect errors during development, and fix bugs. `do { ... } catch { print(error) }` will save you hours of clueless questioning.
- You will be able to opt in for advanced OS features like [data protection].
> :bulb: **Tip**: Don't hide database errors. Let the application handle them, because only application can decide how to handle them.
This gives the improved manager below. And it has less code, which means less bugs :bowtie:
```swift
// An improved manager that does not hide errors
class ImprovedLibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
func author(id: Int64) throws -> Author? {
try dbQueue.read { db in
try Author.fetchOne(db, id: id)
}
}
func book(id: Int64) throws -> Book? {
try dbQueue.read { db in
try Book.fetchOne(db, id: id)
}
}
func books(writtenBy author: Author) throws -> [Book] {
try dbQueue.read { db in
try author.books.fetchAll(db)
}
}
}
```
### Thread-Safety is also an Application Concern
Now, let's make our database manager **thread-safe**.
This one is more subtle. In order to understand what is wrong in our naive manager, one has to consider how it is used by the application.
For example, in the screen that displays an author and her books, we would write:
```swift
let authorId = 123
if let author = libraryManager.author(id: authorId) {
let books = libraryManager.books(writtenBy: author)
// Use author and books
}
```
This code is not thread-safe, because other application threads may have modified the database between the two database accesses. You may end up with an author without any book, and this sure does not make a pretty application screen.
Such bugs are uneasy to reproduce. Sometimes your application will refresh the library content from the network, and delete an author right at the wrong time. The more users your application has, the more users will see weird screens. And of course, you'll be bitten right on the day of the demo in front of the boss.
Fortunately, GRDB has all the tools you need to prevent such nasty data races:
> :bulb: **Tip**: Make sure you fetch all the data your application needs at a given moment of time, in a **single database read**.
This gives a much safer manager:
```swift
// A manager that actually manages
class LibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
}
// Feeds the list of authors
extension LibraryManager {
struct AuthorListItem: Decodable, FetchableRecord {
let author: Author
let bookCount: Int
}
func authorList() throws -> [AuthorListItem] {
try dbQueue.read { db in
let request = Author
.annotated(with: Author.books.count)
.orderByName()
return try AuthorListItem.fetchAll(db, request)
}
}
}
// Feeds a book screen
extension LibraryManager {
struct BookInfo {
var book: Book
var author: Author
}
func bookInfo(bookId: Int64) throws -> BookInfo? {
try dbQueue.read { db in
guard let book = try Book.fetchOne(db, id: bookId) else {
return nil
}
guard let author = try book.author.fetchOne(db) else {
return nil
}
return BookInfo(book: book, author: author)
}
}
}
// Feeds an author screen
extension LibraryManager {
struct AuthorInfo {
var author: Author
var books: [Book]
}
func authorInfo(authorId: Int64) throws -> AuthorInfo? {
try dbQueue.read { db in
guard let author = try Author.fetchOne(db, id: authorId) else {
return nil
}
let books = try author.books.fetchAll(db)
return AuthorInfo(author: author, books: books)
}
}
}
```
The `AuthorListItem`, `BookInfo`, `AuthorInfo` types returned by the manager are designed to feed your views.
When a new screen is added to your application, and you want to make sure it displays **consistent data** free from any data race, make sure you update the manager if needed. The rule is very simple: consumed data must come from a **single** database access method (`dbQueue.read`, `write`, etc.), or [ValueObservation].
In other words: since GRDB is an unmanaged ORM, some amount of management must be imported into your application in order to make it fully thread-safe.
> **Note**: Wrapping several fetches in a single `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony:
>
> ```ruby
> # Ruby's Active Record
> book = Book.find(123) # fetch book
> author = book.author # fetch author
> # use book and author
> ```
>
> The problem is that it is very hard to guarantee that you will surely fetch an author after you have fetched a book, despite the constraints of the database schema. One has to perform subsequent fetches in the proper [isolation] level, so that eventual concurrent writes that modify the database are unable to mess with subsequent requests.
>
> This isolation can be achieved with record management, as in [Core Data] or [Realm], that target long-running multi-threaded applications. On the other side, most web-oriented ORMs rely on short-lived database transactions, so that each HTTP request can be processed independently of others.
>
> GRDB is not a managed ORM. It thus has to use the same isolation techniques as web-oriented ORMs. But unlike web-oriented ORMs, GRDB can't provide implicit isolation: the application must decide when it wants to safely read information in the database, and this decision is made explicit, in your application code, with database access methods such as `dbQueue.read`.
>
> See the [Concurrency Guide] for detailed information, and the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more rationale.
## Observe the Database and Refetch when Needed
We have seen above that the primitive Author and Book record types are [responsible](#persistable-record-types-are-responsible-for-their-tables) for their own database tables. Later we built [requests](#define-record-requests) and [composed](#compose-records) records into more complex ones such as BookInfo or AuthorInfo. We have shown how [database managers](#how-to-design-database-managers) should expose database content to the rest of the application.
Database content which has been fetched into memory eventually becomes obsoleted, as the application modifies the database content.
It is up to the application to decide how long it should keep fetched information in memory. Very often though, the application will want to keep memory information synchronized with the database content.
This synchronization is not automatic with GRDB: records do not "auto-update". That is because applications do not always want this feature, and because it is difficult to write correct multi-threaded applications when values can change in unexpected ways.
Instead, have a look at [Database Observation]:
> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes.
>
> :bulb: **Tip**: [Combine Support] allows automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way.
>
> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way.
>
> :bulb: **Tip**: [TransactionObserver] provides low-level database observation, for your most advanced needs.
>
> :bulb: **Tip**: Don't try to write complex methods that both modify the database and the values in memory at the same time. Instead, modify the database with plain record types, and rely on database observation for automatically refreshing values, even complex ones.
[records]: ../README.md#records
[associations]: AssociationsBasics.md
[FMDB]: https://github.com/ccgus/fmdb
[Core Data]: https://developer.apple.com/documentation/coredata
[Realm]: https://realm.io
[Active Record]: http://guides.rubyonrails.org/active_record_basics.html
[Django]: https://docs.djangoproject.com/en/2.0/topics/db/
[record protocols]: ../README.md#record-protocols-overview
[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns
[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
[Why Adopt GRDB?]: WhyAdoptGRDB.md
[isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
[migrations]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
[migration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
[Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
[GRDB concurrency rules]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
[PersistableRecord]: ../README.md#persistablerecord-protocol
[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[TransactionObserver]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables
[Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details
[Singleton Records]: #singleton-records
[Define Record Requests]: #define-record-requests
[Compose Records]: #compose-records
[How to Design Database Managers]: #how-to-design-database-managers
[Observe the Database and Refetch when Needed]: #observe-the-database-and-refetch-when-needed
[query interface]: ../README.md#the-query-interface
[observe database changes]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[data protection]: ../README.md#data-protection
[Embrace Errors]: #embrace-errors
[Thread-Safety is also an Application Concern]: #thread-safety-is-also-an-application-concern
[recommended convention]: AssociationsBasics.md#associations-and-the-database-schema
[Association Aggregates]: AssociationsBasics.md#association-aggregates
[Codable Record]: ../README.md#codable-records
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[Combine Support]: Combine.md
[Value]: ../README.md#values
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
+1 -1
View File
@@ -195,7 +195,7 @@ protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredRequest,
- `SelectionRequest` provides selection methods such as `select(selection)` or `annotated(with: selection)`
- `TableRequest` provides table targeting methods such as `aliased(tableAlias)`
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) and [Associations](AssociationsBasics.md).
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) and [Associations](AssociationsBasics.md).
### FetchRequest
-1
View File
@@ -21,7 +21,6 @@ To release a new GRDB version:
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
- Push to the master & development branch
- `pod trunk push --allow-warnings GRDB.swift.podspec`
- Update https://github.com/groue/WWDCCompanion
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
`make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb`
+2 -2
View File
@@ -90,7 +90,7 @@ For your convenience, those record protocols can be derived from the [Decodable
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
See [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) for some practical advice.
See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) for some practical advice.
### Allow database records to cross threads
@@ -190,7 +190,7 @@ Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and
For detailed information about GRDB concurrency, check the [Concurrency Guide].
For practical advice on designing the database access layer of your application, see the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md).
For practical advice on designing the database access layer of your application, see the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
### Never pay for using raw SQL
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '6.10.0'
s.version = '6.15.1'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+4 -14
View File
@@ -71,6 +71,7 @@
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */; };
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; };
@@ -374,7 +375,6 @@
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; };
56E9FADA221053DD00C703A8 /* SQL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQL.swift */; };
56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; };
56F0383B28C21814000DEBFB /* Database+Cache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0383A28C21814000DEBFB /* Database+Cache.swift */; };
56F34FBA24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; };
56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
@@ -459,6 +459,7 @@
56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
@@ -513,7 +514,6 @@
56419A6C24A51601004967E1 /* Support.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Support.swift; sourceTree = "<group>"; };
56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = "<group>"; };
56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = "<group>"; };
5643676D272EDF2400C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = "<group>"; };
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
@@ -778,7 +778,6 @@
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = "<group>"; };
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = "<group>"; };
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
56F0383A28C21814000DEBFB /* Database+Cache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Cache.swift"; sourceTree = "<group>"; };
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionIsConstantTests.swift; sourceTree = "<group>"; };
56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = "<group>"; };
@@ -1059,6 +1058,7 @@
563B06BF2185CD1700B38F35 /* ValueObservation */ = {
isa = PBXGroup;
children = (
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */,
560233C82724338800529DF3 /* SharedValueObservationTests.swift */,
563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */,
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */,
@@ -1115,13 +1115,6 @@
path = GRDBCombineTests;
sourceTree = "<group>";
};
564390D42414FC2C00BA61E6 /* Frameworks */ = {
isa = PBXGroup;
children = (
);
name = Frameworks;
sourceTree = "<group>";
};
5653EABF20944B1300F46237 /* Association */ = {
isa = PBXGroup;
children = (
@@ -1446,7 +1439,6 @@
56A238701B9C75030082EB20 /* Configuration.swift */,
56DAA2DA1DE9C827006E10C8 /* Cursor.swift */,
56A238711B9C75030082EB20 /* Database.swift */,
56F0383A28C21814000DEBFB /* Database+Cache.swift */,
566B91221FA4CF810012D5B0 /* Database+Schema.swift */,
566B91081FA4C3960012D5B0 /* Database+Statements.swift */,
4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */,
@@ -1591,8 +1583,6 @@
DC37742D19C8CC90004FCF85 /* GRDB */,
DC10500F19C904DD00D8CA30 /* Tests */,
DC3773F419C8CBB3004FCF85 /* Products */,
564390D42414FC2C00BA61E6 /* Frameworks */,
5643676D272EDF2400C718C7 /* Scripts */,
);
indentWidth = 4;
sourceTree = "<group>";
@@ -1746,6 +1736,7 @@
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */,
569BBA4622906A8200478429 /* InflectionsTests.json in Resources */,
56D496C21D81374C008276D7 /* Betty.jpeg in Resources */,
);
@@ -2026,7 +2017,6 @@
buildActionMask = 2147483647;
files = (
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
56F0383B28C21814000DEBFB /* Database+Cache.swift in Sources */,
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
56158780288D875E00A67323 /* Optional.swift in Sources */,
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
+1 -1
View File
@@ -182,7 +182,7 @@ public struct Configuration {
/// var config = Configuration()
/// config.transactionClock = .custom { db in /* return some Date */ }
/// ```
public var transactionClock: TransactionClock = .default
public var transactionClock: any TransactionClock = .default
// MARK: - Managing SQLite Connections
+188 -77
View File
@@ -14,9 +14,14 @@
extension RangeReplaceableCollection {
/// Creates a collection containing the elements of a cursor.
///
/// // [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor)
/// For example, you can turn a cursor of strings into an array
/// of strings:
///
/// ```swift
/// // Create a [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor)
/// ```
///
/// - parameter cursor: The cursor whose elements feed the collection.
public init(_ cursor: some Cursor<Element>) throws {
@@ -26,9 +31,14 @@ extension RangeReplaceableCollection {
/// Creates a collection containing the elements of a cursor.
///
/// // [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor, minimumCapacity: 100)
/// For example, you can turn a cursor of strings into an array
/// of strings:
///
/// ```swift
/// // Create a [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor, minimumCapacity: 100)
/// ```
///
/// - parameter cursor: The cursor whose elements feed the collection.
/// - parameter minimumCapacity: Prepares the returned collection to store
@@ -41,8 +51,8 @@ extension RangeReplaceableCollection {
/// Adds the elements of a cursor to the end of this collection.
///
/// In case of error, an unspecified amount of elements have been added to
/// the collection.
/// - Important: If an error is thrown, an unspecified amount of
/// elements have been added to the collection.
///
/// - parameter newElements: The elements to append to the collection.
public mutating func append(contentsOf newElements: some Cursor<Element>) throws {
@@ -58,9 +68,13 @@ extension Dictionary {
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// // [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
/// For example:
///
/// ```swift
/// // Create a [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
/// ```
///
/// - parameter cursor: A cursor of values to group into a dictionary.
/// - parameter keyForValue: A closure that returns a key for each element
@@ -81,12 +95,16 @@ extension Dictionary {
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// // [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(
/// minimumCapacity: 100,
/// grouping: cursor,
/// by: { $0.teamID })
/// For example:
///
/// ```swift
/// // Create a [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(
/// minimumCapacity: 100,
/// grouping: cursor,
/// by: { $0.teamID })
/// ```
///
/// - parameter minimumCapacity: The minimum number of key-value pairs that
/// the newly created dictionary should be able to store without
@@ -112,9 +130,13 @@ extension Dictionary {
/// of key-value tuples with unique keys. Passing a cursor with duplicate
/// keys to this initializer results in a fatal error.
///
/// // [Int64: Player]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
/// For example:
///
/// ```swift
/// // Create a [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
/// ```
///
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
/// new dictionary. Every key in `keysAndValues` must be unique.
@@ -137,11 +159,15 @@ extension Dictionary {
/// of key-value tuples with unique keys. Passing a cursor with duplicate
/// keys to this initializer results in a fatal error.
///
/// // [Int64: Player]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(
/// minimumCapacity: 100,
/// uniqueKeysWithValues: cursor)
/// For example:
///
/// ```swift
/// // Create a [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(
/// minimumCapacity: 100,
/// uniqueKeysWithValues: cursor)
/// ```
///
/// - parameter minimumCapacity: The minimum number of key-value pairs that
/// the newly created dictionary should be able to store without
@@ -165,9 +191,13 @@ extension Dictionary {
extension Set {
/// Creates a set containing the elements of a cursor.
///
/// // Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor)
/// For example, you can turn a cursor of strings into a set of strings:
///
/// ```swift
/// // Create a Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor)
/// ```
///
/// - parameter cursor: A cursor of values to gather into a set.
public init(_ cursor: some Cursor<Element>) throws {
@@ -180,9 +210,13 @@ extension Set {
/// Creates a set containing the elements of a cursor.
///
/// // Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor, minimumCapacity: 100)
/// For example, you can turn a cursor of strings into a set of strings:
///
/// ```swift
/// // Create a Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor, minimumCapacity: 100)
/// ```
///
/// - parameter cursor: A cursor of values to gather into a set.
/// - parameter minimumCapacity: The minimum number of elements that the
@@ -240,6 +274,75 @@ extension Sequence {
///
/// ## Topics
///
/// ### Iterating Over a Cursor’s Elements
///
/// - ``next()``
/// - ``forEach(_:)-4ib2m``
/// - ``enumerated()``
/// - ``isEmpty``
///
/// ### Finding Elements
///
/// - ``contains(_:)``
/// - ``contains(where:)``
/// - ``first(where:)``
/// - ``min()``
/// - ``min(by:)``
/// - ``max()``
/// - ``max(by:)``
///
/// ### Selecting Elements
///
/// - ``prefix(_:)``
/// - ``prefix(while:)``
/// - ``suffix(_:)``
///
/// ### Excluding Elements
///
/// - ``dropFirst()``
/// - ``dropFirst(_:)``
/// - ``dropLast()``
/// - ``dropLast(_:)``
/// - ``drop(while:)``
/// - ``filter(_:)``
///
/// ### Transforming a Cursor
///
/// - ``map(_:)``
/// - ``compactMap(_:)``
/// - ``flatMap(_:)-5ci2v``
/// - ``flatMap(_:)-8jxlj``
/// - ``reduce(_:_:)``
/// - ``reduce(into:_:)``
///
/// ### Transforming a Sequence into a Cursor
///
/// - ``Swift/Sequence/flatMap(_:)``
///
/// ### Joining Elements
///
/// - ``joined()-5r5ja``
/// - ``joined()-7bnrx``
/// - ``joined(separator:)``
///
/// ### Filling RangeReplaceableCollection with the contents of a Cursor
///
/// - ``Swift/RangeReplaceableCollection/init(_:)``
/// - ``Swift/RangeReplaceableCollection/init(_:minimumCapacity:)``
/// - ``Swift/RangeReplaceableCollection/append(contentsOf:)``
///
/// ### Creating a Dictionary from the contents of a Cursor
///
/// - ``Swift/Dictionary/init(grouping:by:)``
/// - ``Swift/Dictionary/init(minimumCapacity:grouping:by:)``
/// - ``Swift/Dictionary/init(uniqueKeysWithValues:)``
/// - ``Swift/Dictionary/init(minimumCapacity:uniqueKeysWithValues:)``
///
/// ### Creating a Set from the contents of a Cursor
///
/// - ``Swift/Set/init(_:)``
/// - ``Swift/Set/init(_:minimumCapacity:)``
///
/// ### Supporting Types
///
/// - ``AnyCursor``
@@ -269,7 +372,7 @@ extension Cursor {
/// Returns a Boolean value indicating whether the cursor does not contain
/// any element.
///
/// - important: This property may consume elements.
/// - important: This property consumes an element.
public var isEmpty: Bool {
get throws { try next() == nil }
}
@@ -294,13 +397,17 @@ extension Cursor {
/// Returns a cursor of pairs (n, x), where n represents a consecutive
/// integer starting at zero, and x represents an element of the cursor.
///
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let c = cursor.enumerated()
/// while let (n, x) = c.next() {
/// print("\(n): \(x)")
/// }
/// // Prints: "0: foo"
/// // Prints: "1: bar"
/// ```swift
/// let cursor = try String.fetchCursor(db, sql: """
/// SELECT 'foo' UNION ALL SELECT 'bar'
/// """)
/// let c = cursor.enumerated()
/// while let (n, x) = c.next() {
/// print("\(n): \(x)")
/// }
/// // Prints: "0: foo"
/// // Prints: "1: bar"
/// ```
public func enumerated() -> EnumeratedCursor<Self> {
EnumeratedCursor(self)
}
@@ -346,11 +453,13 @@ extension Cursor {
/// If the number of elements to drop exceeds the number of elements in
/// the cursor, the result is an empty cursor.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// try print(numbers.dropFirst(10))
/// // Prints "[]"
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// try print(numbers.dropFirst(10))
/// // Prints "[]"
/// ```
///
/// - Parameter n: The number of elements to drop from the beginning of
/// the cursor. `n` must be greater than or equal to zero.
@@ -364,9 +473,11 @@ extension Cursor {
///
/// The following example drops the first element from a cursor of integers.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst())
/// // Prints "[2, 3, 4, 5]"
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst())
/// // Prints "[2, 3, 4, 5]"
/// ```
///
/// If the cursor has no elements, the result is an empty cursor.
///
@@ -381,11 +492,13 @@ extension Cursor {
/// The cursor must be finite. If the number of elements to drop exceeds
/// the number of elements in the cursor, the result is an empty array.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// try print(numbers.dropLast(10))
/// // Prints "[]"
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// try print(numbers.dropLast(10))
/// // Prints "[]"
/// ```
///
/// - Parameter n: The number of elements to drop off the end of the
/// cursor. `n` must be greater than or equal to zero.
@@ -414,9 +527,11 @@ extension Cursor {
///
/// The following example drops the last element from a cursor of integers.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast())
/// // Prints "[1, 2, 3, 4]"
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast())
/// // Prints "[1, 2, 3, 4]"
/// ```
///
/// If the cursor has no elements, the result is an empty cursor.
///
@@ -502,11 +617,13 @@ extension Cursor {
/// If the maximum length exceeds the number of elements in the cursor,
/// the result contains all the elements in the cursor.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// try print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// try print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
/// ```
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
@@ -562,11 +679,13 @@ extension Cursor {
/// elements in the cursor, the result contains all the elements in the
/// cursor.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// try print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// try print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
/// ```
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
@@ -620,24 +739,16 @@ extension Cursor where Element: Equatable {
extension Cursor where Element: Comparable {
/// Returns the maximum element in the cursor.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's maximum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns
/// `nil`.
/// - Returns: The cursor's maximum element. If the cursor has no
/// elements, returns `nil`.
public func max() throws -> Element? {
try max(by: <)
}
/// Returns the minimum element in the cursor.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's minimum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns
/// `nil`.
/// - Returns: The cursor's minimum element. If the cursor has no
/// elements, returns `nil`.
public func min() throws -> Element? {
try min(by: <)
}
-74
View File
@@ -1,74 +0,0 @@
extension Database {
func withCache<T>(atPath path: String, execute: () throws -> T) throws -> T {
GRDBPrecondition(attachedCache == nil, "Database is already cached.")
return try throwingFirstError {
attachedCache = AttachedCache(
schema: .attached("cache"),
statementCache: StatementCache(database: self))
try self.execute(literal: "ATTACH DATABASE \(path) AS cache")
return try execute()
} finally: {
attachedCache = nil
try self.execute(sql: "DETACH DATABASE cache")
}
}
}
extension Statement {
/// Returns a statement ready for iterating the results of this statement
/// with a DatabaseCursor.
///
/// The result is not the same statement as the receiver if we cache the
/// statement's results.
func databaseCursorStatement(with arguments: StatementArguments?) throws -> Statement {
// Should we cache statement results and return a new statement on the cached values?
guard
// Don't cache until we were instructed to.
let attachedCache = database.attachedCache,
// Only cache read-only statements.
isReadonly,
// Only cache statements that access user tables.
databaseRegion
.filteringTables({ !Database.isSQLiteInternalTable($0) && !Database.isGRDBInternalTable($0) })
.isEmpty == false,
// Only cache statements that can build a name for the cache table.
let cacheTableName,
// Only cache statements for which we can guarantee rowid ordering
// without ambiguity.
case let statementColumns = columnNames.map({ $0.lowercased() }),
let rowid = ["rowid", "_rowid_", "oid"].first(where: { !statementColumns.contains($0) })
else {
// Don't cache: return self.
// Reset before cursor iteration: the statement may be reused.
try prepareExecution(withArguments: arguments)
return self
}
// Cache the results if not done yet
let cacheTable = Database.TableIdentifier(schemaID: attachedCache.schema, name: cacheTableName)
try database.execute(sql: """
CREATE TABLE IF NOT EXISTS \(cacheTable.quotedDatabaseIdentifier) AS \(sql)
""", arguments: arguments ?? self.arguments)
// Return a statement on the cached values, preserving the order of the
// original rows.
//
// Quoting <https://sqlite.org/lang_createtable.html#create_table_as_select_statements>:
//
// > Tables created using CREATE TABLE AS are initially populated with
// > the rows of data returned by the SELECT statement. Rows are
// > assigned contiguously ascending rowid values, starting with 1, in
// > the order that they are returned by the SELECT statement.
let statement = try attachedCache.statementCache.statement("""
SELECT * FROM \(cacheTable.quotedDatabaseIdentifier) ORDER BY \(rowid)
""")
// Reset before cursor iteration: the statement may be reused.
try statement.reset()
return statement
}
}
+31 -17
View File
@@ -57,10 +57,6 @@ extension Database {
case let .attached(name): return "\(name).sqlite_master"
}
}
func table(_ name: String) -> TableIdentifier {
TableIdentifier(schemaID: self, name: name)
}
}
/// The identifier of a database table or view.
@@ -214,7 +210,7 @@ extension Database {
}
}
func tableExists(_ table: TableIdentifier) throws -> Bool {
private func tableExists(_ table: TableIdentifier) throws -> Bool {
try exists(type: .table, name: table.name, in: table.schemaID)
}
@@ -1317,11 +1313,33 @@ struct TableInfo: FetchableRecord {
}
}
enum SchemaObjectType: String {
case index
case table
case trigger
case view
/// A value in the `type` column of `sqlite_master`.
struct SchemaObjectType: Hashable, RawRepresentable, DatabaseValueConvertible {
var rawValue: String
init(rawValue: String) {
self.rawValue = rawValue
}
static let index = SchemaObjectType(rawValue: "index")
static let table = SchemaObjectType(rawValue: "table")
static let trigger = SchemaObjectType(rawValue: "trigger")
static let view = SchemaObjectType(rawValue: "view")
}
/// A row in `sqlite_master`.
struct SchemaObject: Hashable, FetchableRecord {
var type: SchemaObjectType
var name: String
var tbl_name: String?
var sql: String?
init(row: Row) throws {
// "rootpage" column is not always there: avoid using numerical indexes
type = row["type"]
name = row["name"]
tbl_name = row["tbl_name"]
sql = row["sql"]
}
}
/// All objects in a database schema (tables, views, indexes, triggers).
@@ -1332,7 +1350,6 @@ struct SchemaInfo: Equatable {
/// (case-insensitive).
func containsObjectNamed(_ name: String, ofType type: SchemaObjectType) -> Bool {
let name = name.lowercased()
let type = type.rawValue
return objects.contains {
$0.type == type && $0.name.lowercased() == name
}
@@ -1345,15 +1362,12 @@ struct SchemaInfo: Equatable {
func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? {
let name = name.lowercased()
return objects
.first { $0.type == type.rawValue && $0.name.lowercased() == name }?
.first { $0.type == type && $0.name.lowercased() == name }?
.name
}
private struct SchemaObject: Codable, Hashable, FetchableRecord {
var type: String
var name: String
var tbl_name: String?
var sql: String?
func filter(_ isIncluded: (SchemaObject) -> Bool) -> Self {
SchemaInfo(objects: objects.filter(isIncluded))
}
}
+1 -14
View File
@@ -94,6 +94,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
///
/// ### Other Database Operations
///
/// - ``add(tokenizer:)``
/// - ``backup(to:pagesPerStep:progress:)``
/// - ``checkpoint(_:on:)``
/// - ``clearSchemaCache()``
@@ -331,20 +332,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
class AttachedCache {
var schema: SchemaIdentifier
var statementCache: StatementCache
init(schema: Database.SchemaIdentifier, statementCache: StatementCache) {
self.schema = schema
self.statementCache = statementCache
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The attached database that caches the results of requests.
var attachedCache: AttachedCache?
// MARK: - Private properties
/// Support for ``Configuration/busyMode``.
+19 -9
View File
@@ -84,12 +84,20 @@ public final class DatabasePool {
// > Many applications choose NORMAL when in WAL mode
try db.execute(sql: "PRAGMA synchronous = NORMAL")
if !FileManager.default.fileExists(atPath: path + "-wal") {
// Create the -wal file if it does not exist yet. This
// avoids an SQLITE_CANTOPEN (14) error whenever a user
// opens a pool to an existing non-WAL database, and
// attempts to read from it.
// See https://github.com/groue/GRDB.swift/issues/102
// Make sure a non-empty wal file exists.
//
// The presence of the wal file avoids an SQLITE_CANTOPEN (14)
// error when the user opens a pool and reads from it.
// See <https://github.com/groue/GRDB.swift/issues/102>.
//
// The non-empty wal file avoids an SQLITE_ERROR (1) error
// when the user opens a pool and creates a wal snapshot
// (which happens when starting a ValueObservation).
// See <https://github.com/groue/GRDB.swift/issues/1383>.
let walPath = path + "-wal"
if try FileManager.default.fileExists(atPath: walPath) == false
|| (URL(fileURLWithPath: walPath).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0
{
try db.inSavepoint {
try db.execute(sql: """
CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY);
@@ -900,9 +908,11 @@ extension DatabasePool {
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html), or
/// if this method is called from a database access where a write
/// transaction is open.
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html),
/// or if this method is called from a write transaction, or if the
/// wal file is missing or truncated (size zero).
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
public func makeSnapshotPool() throws -> DatabaseSnapshotPool {
try unsafeReentrantRead { db in
try DatabaseSnapshotPool(db)
+29 -25
View File
@@ -225,21 +225,22 @@ extension DatabaseQueue: DatabaseReader {
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
writer.async { db in
do {
// The transaction guarantees snapshot isolation against eventual
// external connection.
try db.beginTransaction(.deferred)
try db.beginReadOnly()
} catch {
value(.failure(error))
return
defer {
// Ignore error because we can not notify it.
try? db.commit()
try? db.endReadOnly()
}
value(.success(db))
// Ignore error because we can not notify it.
try? db.endReadOnly()
try? db.commit()
do {
// Enter read-only mode before starting a transaction, so that the
// transaction commit does not trigger database observation.
// See <https://github.com/groue/GRDB.swift/pull/1213>.
try db.beginReadOnly()
try db.beginTransaction(.deferred)
value(.success(db))
} catch {
value(.failure(error))
}
}
}
@@ -273,20 +274,23 @@ extension DatabaseQueue: DatabaseReader {
writer.execute { db in
// ... and that no transaction is opened.
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
do {
try db.beginTransaction(.deferred)
try db.beginReadOnly()
} catch {
value(.failure(error))
return
defer {
// Ignore error because we can not notify it.
try? db.commit()
try? db.endReadOnly()
}
value(.success(db))
// Ignore error because we can not notify it.
try? db.endReadOnly()
try? db.commit()
do {
// Enter read-only mode before starting a transaction, so that the
// transaction commit does not trigger database observation.
// See <https://github.com/groue/GRDB.swift/pull/1213>.
try db.beginReadOnly()
try db.beginTransaction(.deferred)
value(.success(db))
} catch {
value(.failure(error))
}
}
}
+4 -9
View File
@@ -168,14 +168,9 @@ public struct DatabaseRegion {
// TransactionObserver protocol. By removing internal SQLite tables from
// the observed region, we optimize database observation.
//
// We also remove GRDB internal tables (cache tables).
//
// And by canonicalizing table names, we remove views, and help the
// `isModified` methods.
let notInternalTables = filteringTables {
!Database.isSQLiteInternalTable($0) && !Database.isGRDBInternalTable($0)
}
return try notInternalTables.canonicalTables(db)
try ignoringInternalSQLiteTables().canonicalTables(db)
}
/// Returns a region only made of actual tables with their canonical names.
@@ -195,11 +190,11 @@ public struct DatabaseRegion {
return region
}
/// Returns a region which only contains the filtered tables
func filteringTables(_ predicate: (String) -> Bool) -> DatabaseRegion {
/// Returns a region which doesn't contain any SQLite internal table.
private func ignoringInternalSQLiteTables() -> DatabaseRegion {
guard let tableRegions else { return .fullDatabase }
let filteredRegions = tableRegions.filter {
predicate($0.key.rawValue)
!Database.isSQLiteInternalTable($0.key.rawValue)
}
return DatabaseRegion(tableRegions: filteredRegions)
}
+7 -9
View File
@@ -108,12 +108,10 @@ public final class DatabaseSnapshotPool {
/// assert(count == 0)
/// ```
///
/// If any of the following statements are false when the snapshot is
/// created, a ``DatabaseError`` of code `SQLITE_ERROR` is thrown:
///
/// - The database connection must be in the
/// [WAL mode](https://www.sqlite.org/wal.html).
/// - There must not be a write transaction open.
/// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html),
/// or if this method is called from a write transaction, or if the
/// wal file is missing or truncated (size zero).
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
///
@@ -175,9 +173,9 @@ public final class DatabaseSnapshotPool {
/// let snapshot = try DatabaseSnapshotPool(path: "/path/to/database.sqlite")
/// ```
///
/// If the database at `path` is not in the
/// [WAL mode](https://www.sqlite.org/wal.html), a ``DatabaseError`` of code
/// `SQLITE_ERROR` is thrown.
/// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html),
/// or if the wal file is missing or truncated (size zero).
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
///
-19
View File
@@ -342,25 +342,6 @@ extension DatabaseValue: CustomStringConvertible {
}
}
extension DatabaseValue {
/// A string that represented the value in a lossless and
/// unambiguous way.
var losslessDescription: String {
switch storage {
case .null:
return "NULL"
case let .string(string):
return String(reflecting: string)
case let .double(double):
return double.description
case let .int64(int64):
return int64.description
case let .blob(data):
return "X'" + data.map { String(format: "%02X", $0) }.joined() + "'"
}
}
}
/// Compares DatabaseValue like SQLite.
///
/// See RxGRDB for tests.
+3 -1
View File
@@ -147,7 +147,6 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
private let columnIndex: CInt
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
let statement = try statement.databaseCursorStatement(with: arguments)
self._statement = statement
if let adapter {
// adapter may redefine the index of the leftmost column
@@ -155,6 +154,9 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
} else {
columnIndex = 0
}
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
+10 -7
View File
@@ -289,14 +289,13 @@ public protocol DatabaseWriter: DatabaseReader {
/// ```
///
/// - note: Usage of this method is discouraged, because waiting on the
/// returned ``DatabaseFuture`` blocks a thread. You may prefer the
/// asynchronous version of this method: ``spawnConcurrentRead(_:)``.
/// returned ``DatabaseFuture`` blocks a thread. You may prefer
/// ``spawnConcurrentRead(_:)`` instead.
/// - parameter value: A closure which accesses the database.
func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T>
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
/// Schedules read-only database operations for execution, and
/// returns immediately.
/// Schedules read-only database operations for execution.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
@@ -311,7 +310,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// by the database writer.
///
/// In the example below, the number of players is fetched concurrently with
/// the player insertion. Yet the future is guaranteed to return zero:
/// the player insertion. Yet it is guaranteed to return zero:
///
/// ```swift
/// try writer.writeWithoutTransaction { db in
@@ -334,6 +333,10 @@ public protocol DatabaseWriter: DatabaseReader {
/// }
/// ```
///
/// - important: The database operations are executed immediately,
/// or asynchronously, depending on the actual class
/// of `DatabaseWriter`.
///
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
@@ -465,7 +468,7 @@ extension DatabaseWriter {
// MARK: - Erasing the content of the database
/// Erases the content of the database.
/// Erase the database: delete all content, drop all tables, etc.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func erase() throws {
try barrierWriteWithoutTransaction { try $0.erase() }
@@ -684,7 +687,7 @@ extension DatabaseWriter {
}
}
/// Erases the content of the database.
/// Erase the database: delete all content, drop all tables, etc.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
+2 -6
View File
@@ -58,10 +58,6 @@
/// - ``makePreparedRequest(_:forSingleResult:)``
/// - ``PreparedRequest``
///
/// ### Database Observation Support
///
/// - ``databaseRegion(_:)``
///
/// ### Adapting the Fetched Rows
///
/// - ``adapted(_:)``
@@ -217,8 +213,8 @@ public struct AnyFetchRequest<RowDecoder> {
///
/// // AnyFetchRequest<Row>
/// let rowRequest = playerRequest.asRequest(of: Row.self)
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> AnyFetchRequest<RowDecoder> {
AnyFetchRequest<RowDecoder>(request: request)
public func asRequest<T>(of type: T.Type) -> AnyFetchRequest<T> {
AnyFetchRequest<T>(request: request)
}
}
+3 -1
View File
@@ -1360,9 +1360,11 @@ public final class RowCursor: DatabaseCursor {
@usableFromInline let _row: Row // Reused for performance
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
let statement = try statement.databaseCursorStatement(with: arguments)
self._statement = statement
self._row = try Row(statement: statement).adapted(with: adapter, layout: statement)
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
+1 -1
View File
@@ -572,7 +572,7 @@ public struct ScopeAdapter: RowAdapter {
///
/// - parameter scopes: A dictionary that maps scope names to
/// row adapters.
public init(_ scopes: [String: RowAdapter]) {
public init(_ scopes: [String: any RowAdapter]) {
// Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes)
}
+5 -3
View File
@@ -39,6 +39,8 @@
///
/// - ``append(literal:)``
/// - ``append(sql:arguments:)``
/// - ``Swift/Collection/joined(separator:)``
/// - ``Swift/Sequence/joined(separator:)``
public struct SQL {
/// `SQL.Element` is a component of an `SQL` literal.
///
@@ -316,12 +318,12 @@ extension SQL: SQLOrderingTerm {
}
extension Sequence where Element == SQL {
/// Returns the concatenated `SQL` literal of this sequence of literals,
/// Concatenates the sequence elements into a new `SQL` literal,
/// inserting the given raw SQL separator between each element.
///
/// For example:
///
/// ```
/// ```swift
/// let components: [SQL] = [
/// "UPDATE player",
/// "SET name = \(name)",
@@ -341,7 +343,7 @@ extension Sequence where Element == SQL {
}
extension Collection where Element == SQL {
/// Returns the concatenated `SQL` literal of this collection of literals,
/// Concatenates the collection elements into a new `SQL` literal,
/// inserting the given raw SQL separator between each element.
///
/// For example:
+5 -35
View File
@@ -1,4 +1,3 @@
import CryptoKit
import Foundation
/// A raw SQLite statement, suitable for the SQLite C API.
@@ -96,23 +95,6 @@ public final class Statement {
authorizerEventKinds.contains(where: \.isDelete)
}
/// A string that represented the statement in a lossless and
/// unambiguous way.
lazy var losslessDescription: String = {
"\(sql); -- \(arguments.losslessDescription)"
}()
/// A table name for caching the results of this statement
lazy var cacheTableName: String? = {
guard #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *),
let losslessDescription = losslessDescription.data(using: .utf8)
else {
return nil
}
let digest = Insecure.SHA1.hash(data: losslessDescription)
return "grdb_cache_" + digest.map { String(format: "%02X", $0) }.joined()
}()
@usableFromInline
unowned let database: Database
@@ -797,7 +779,10 @@ final class StatementCursor: DatabaseCursor {
// Use Statement.makeCursor() instead
init(statement: Statement, arguments: StatementArguments? = nil) throws {
_statement = try statement.databaseCursorStatement(with: arguments)
self._statement = statement
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
@@ -1045,7 +1030,7 @@ public struct StatementArguments: Hashable {
/// The result is nil unless all array elements conform to the
/// ``DatabaseValueConvertible`` protocol.
public init?(_ array: [Any]) {
var values = [DatabaseValueConvertible?]()
var values = [(any DatabaseValueConvertible)?]()
for value in array {
guard let dbValue = DatabaseValue(value: value) else {
return nil
@@ -1404,19 +1389,4 @@ extension StatementArguments: CustomStringConvertible {
}
}
extension StatementArguments {
/// A string that represented the value in a lossless and
/// unambiguous way.
var losslessDescription: String {
var chunks: [String] = []
for value in values {
chunks.append(value.losslessDescription)
}
for (key, value) in namedValues.sorted(by: { $0.key < $1.key }) {
chunks.append("\(key): \(value.losslessDescription)")
}
return chunks.joined(separator: ",")
}
}
extension StatementArguments: Sendable { }
+4 -2
View File
@@ -89,7 +89,7 @@ public protocol StatementColumnConvertible {
///
/// Do not check for `NULL` in your implementation of this method. Null
/// database values are handled
/// in ``fromStatement(_:atUncheckedIndex:)-2i8y6``.
/// in ``StatementColumnConvertible/fromStatement(_:atUncheckedIndex:)-2i8y6``.
///
/// For example, here is the how Int64 adopts StatementColumnConvertible:
///
@@ -214,7 +214,6 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
@usableFromInline let columnIndex: CInt
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
let statement = try statement.databaseCursorStatement(with: arguments)
self._statement = statement
if let adapter {
// adapter may redefine the index of the leftmost column
@@ -222,6 +221,9 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
} else {
columnIndex = 0
}
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
+1 -1
View File
@@ -1,7 +1,7 @@
#if canImport(CoreGraphics)
import CoreGraphics
/// CGFloat adopts DatabaseValueConvertible
/// `CGFloat` is a database value.
extension CGFloat: DatabaseValueConvertible {
/// Returns a REAL database value.
public var databaseValue: DatabaseValue {
+1 -1
View File
@@ -1,6 +1,6 @@
import Foundation
/// Data is convertible to and from DatabaseValue.
/// `Data` is a database value.
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
public init(sqliteStatement: SQLiteStatement, index: CInt) {
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
+2 -4
View File
@@ -1,8 +1,7 @@
import Foundation
#if !os(Linux)
/// NSDate is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
/// `NSDate` is a database value.
extension NSDate: DatabaseValueConvertible {
/// Returns a TEXT database value that contains the date encoded as
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
@@ -31,8 +30,6 @@ extension NSDate: DatabaseValueConvertible {
}
#endif
/// Date is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension Date: DatabaseValueConvertible {
/// Returns a TEXT database value that contains the date encoded as
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
@@ -115,6 +112,7 @@ extension Date: DatabaseValueConvertible {
}
}
/// `Date` is a database value.
extension Date: StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
+1 -1
View File
@@ -1,7 +1,7 @@
#if !os(Linux)
import Foundation
/// Decimal adopts DatabaseValueConvertible
/// `Decimal` is a database value.
extension Decimal: DatabaseValueConvertible {
/// Returns a TEXT decimal value.
public var databaseValue: DatabaseValue {
+1 -1
View File
@@ -1,7 +1,7 @@
#if !os(Linux)
import Foundation
/// NSData is convertible to and from DatabaseValue.
/// `NSData` is a database value.
extension NSData: DatabaseValueConvertible {
/// Returns a BLOB database value.
+1 -1
View File
@@ -1,6 +1,6 @@
import Foundation
/// NSNull adopts DatabaseValueConvertible
/// `NSDate` is a database value.
extension NSNull: DatabaseValueConvertible {
/// Returns the NULL database value.
+1 -1
View File
@@ -9,7 +9,7 @@ private let integerRoundingBehavior = NSDecimalNumberHandler(
raiseOnUnderflow: false,
raiseOnDivideByZero: false)
/// NSNumber adopts DatabaseValueConvertible
/// `NSNumber` is a database value.
extension NSNumber: DatabaseValueConvertible {
/// A database value.
+1 -1
View File
@@ -1,7 +1,7 @@
#if !os(Linux)
import Foundation
/// NSString adopts DatabaseValueConvertible
/// `NSString` is a database value.
extension NSString: DatabaseValueConvertible {
/// Returns a TEXT database value.
+6 -2
View File
@@ -1,7 +1,9 @@
import Foundation
#if !os(Linux)
/// NSURL stores its absoluteString in the database.
/// `NSURL` is a database value.
///
/// `NSURL` stores its `absoluteString` in the database.
extension NSURL: DatabaseValueConvertible {
/// Returns a TEXT database value containing the absolute URL.
@@ -18,5 +20,7 @@ extension NSURL: DatabaseValueConvertible {
}
#endif
/// URL stores its absoluteString in the database.
/// `URL` is a database value.
///
/// `URL` stores its `absoluteString` in the database.
extension URL: DatabaseValueConvertible { }
+2 -2
View File
@@ -1,7 +1,7 @@
import Foundation
#if !os(Linux)
/// NSUUID adopts DatabaseValueConvertible
/// `NSUUID` is a database value.
extension NSUUID: DatabaseValueConvertible {
/// Returns a BLOB database value containing the uuid bytes.
public var databaseValue: DatabaseValue {
@@ -35,7 +35,7 @@ extension NSUUID: DatabaseValueConvertible {
}
#endif
/// UUID adopts DatabaseValueConvertible
/// `UUID` is a database value.
extension UUID: DatabaseValueConvertible {
/// Returns a BLOB database value containing the uuid bytes.
public var databaseValue: DatabaseValue {
@@ -136,7 +136,7 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
if let type = T.self as? DatabaseValueConvertible.Type {
if let type = T.self as? any DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows custom database decoding, such as decoding Date from
// String, for example.
@@ -44,6 +44,7 @@ extension Optional: SQLSelectable where Wrapped: SQLSelectable {
extension Optional: SQLSpecificExpressible where Wrapped: SQLSpecificExpressible { }
/// `Optional` is a database value when it wrapped type is.
extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
switch self {
@@ -1,6 +1,6 @@
// MARK: - Value Types
/// Bool adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Bool` is a database value.
extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -95,7 +95,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// Int adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Int` is a database value.
extension Int: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -134,7 +134,7 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Int8` is a database value.
extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -173,7 +173,7 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Int16` is a database value.
extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -212,7 +212,7 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Int32` is a database value.
extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -251,7 +251,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// Int64 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Int64` is a database value.
extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -294,7 +294,7 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// UInt adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `UInt` is a database value.
extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -333,7 +333,7 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `UInt8` is a database value.
extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -372,7 +372,7 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `UInt16` is a database value.
extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -411,7 +411,7 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `UInt32` is a database value.
extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -450,7 +450,7 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `UInt64` is a database value.
extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -489,7 +489,7 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// Double adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Double` is a database value.
extension Double: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -529,7 +529,7 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// Float adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Float` is a database value.
extension Float: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -569,7 +569,7 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// String adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `String` is a database value.
extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
+13 -7
View File
@@ -454,7 +454,7 @@ class DatabaseObservationBroker {
if savepointStack.isEmpty {
// Notify now
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
for statementObservation in statementObservations where statementObservation.tracksEvent(event) {
statementObservation.transactionObservation.databaseWillChange(with: event)
}
} else {
@@ -479,7 +479,7 @@ class DatabaseObservationBroker {
if savepointStack.isEmpty {
// Notify now
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
for statementObservation in statementObservations where statementObservation.tracksEvent(event) {
statementObservation.transactionObservation.databaseDidChange(with: event)
}
} else {
@@ -639,7 +639,7 @@ class DatabaseObservationBroker {
for (event, statementObservations) in eventsBuffer {
assert(statementObservations.isEmpty || !database.isReadOnly, "Read-only transactions are not notified")
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
for statementObservation in statementObservations where statementObservation.tracksEvent(event) {
event.send(to: statementObservation.transactionObservation)
}
}
@@ -969,12 +969,18 @@ final class TransactionObservation {
struct StatementObservation {
var transactionObservation: TransactionObservation
/// Filters database events that should be notified.
var predicate: DatabaseEventPredicate
/// A predicate that filters database events that should be notified.
///
/// Call this predicate as a method:
///
/// ```
/// if observation.tracksEvent(event) { ... }
/// ```
var tracksEvent: DatabaseEventPredicate
init(transactionObservation: TransactionObservation, trackingEvents predicate: DatabaseEventPredicate) {
self.transactionObservation = transactionObservation
self.predicate = predicate
self.tracksEvent = predicate
}
}
@@ -1447,7 +1453,7 @@ enum DatabaseEventPredicate {
/// statement authorizer.
case matching(observedEventKinds: [DatabaseEventKind], authorizerEventKinds: [DatabaseEventKind])
func evaluate(_ event: some DatabaseEventProtocol) -> Bool {
func callAsFunction(_ event: some DatabaseEventProtocol) -> Bool {
switch self {
case .all:
return true
+30 -19
View File
@@ -1,3 +1,5 @@
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
/// An instance of WALSnapshot records the state of a WAL mode database for some
/// specific point in history.
///
@@ -20,13 +22,6 @@
///
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
final class WALSnapshot: Sendable {
// Xcode 14 (Swift 5.7) ships with a macOS SDK that misses snapshot support.
// Xcode 14.1 (Swift 5.7.1) ships with a macOS SDK that has snapshot support.
// This is the meaning of (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
static let available = true
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
init(_ db: Database) throws {
@@ -35,11 +30,30 @@ final class WALSnapshot: Sendable {
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
}
guard code == SQLITE_OK else {
// <https://www.sqlite.org/c3ref/snapshot_get.html>
//
// > The following must be true for sqlite3_snapshot_get() to succeed. [...]
// >
// > 1. The database handle must not be in autocommit mode.
// > 2. Schema S of database connection D must be a WAL
// > mode database.
// > 3. There must not be a write transaction open on schema S
// > of database connection D.
// > 4. One or more transactions must have been written to the
// > current wal file since it was created on disk (by any
// > connection). This means that a snapshot cannot be taken
// > on a wal mode database with no wal file immediately
// > after it is first opened. At least one transaction must
// > be written to it first.
// Test condition 1:
if sqlite3_get_autocommit(db.sqliteConnection) != 0 {
throw DatabaseError(resultCode: code, message: """
Can't create snapshot because database is in autocommit mode.
""")
}
// Test condition 2:
if let journalMode = try? String.fetchOne(db, sql: "PRAGMA journal_mode"),
journalMode != "wal"
{
@@ -47,7 +61,14 @@ final class WALSnapshot: Sendable {
Can't create snapshot because database is not in WAL mode.
""")
}
throw DatabaseError(resultCode: code)
// Condition 3 can't happen because GRDB only calls this
// initializer from read transactions.
//
// Hence it is condition 4 that is false:
throw DatabaseError(resultCode: code, message: """
Can't create snapshot from a missing or empty wal file.
""")
}
guard let sqliteSnapshot else {
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
@@ -67,15 +88,5 @@ final class WALSnapshot: Sendable {
func compare(_ other: WALSnapshot) -> CInt {
sqlite3_snapshot_cmp(sqliteSnapshot, other.sqliteSnapshot)
}
#else
static let available = false
init(_ db: Database) throws {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "snapshots are not available")
}
func compare(_ other: WALSnapshot) -> CInt {
preconditionFailure("snapshots are not available")
}
#endif
}
#endif
+7 -7
View File
@@ -14,7 +14,7 @@ The other chapters cover, with more details, the fundamentals of SQLite concurre
**The two concurrency rules are strongly recommended practices.** They are all about SQLite, a robust and reliable database that takes great care of your data: don't miss an opportunity to put it on your side!
### Rule 1: Connect to any database file only once
#### Rule 1: Connect to any database file only once
Open one single ``DatabaseQueue`` or ``DatabasePool`` per database file, for the whole duration of your use of the database. Not for the duration of _each_ database access, but really for the duration of _all_ database accesses to this file.
@@ -27,7 +27,7 @@ Open one single ``DatabaseQueue`` or ``DatabasePool`` per database file, for the
- You will not be able to use the <doc:DatabaseObservation> features.
- You will see SQLite errors ([`SQLITE_BUSY`]).
### Rule 2: Mind your transactions
#### Rule 2: Mind your transactions
Database operations that are grouped in a transaction are guaranteed to be either fully saved on disk, or not at all. Read-only transactions guarantee a stable and immutable view of the database, and do not see changes performed by eventual concurrent writes.
@@ -150,31 +150,31 @@ This prevents the database operations from various concurrent accesses from bein
**You will generally use the safe database access methods `read` and `write`.** In this context, "safe" means that a database access is concurrency-friendly, because GRDB provides the following guarantees:
### Serialized Writes
#### Serialized Writes
**All writes performed by one ``DatabaseQueue`` or ``DatabasePool`` instance are serialized.**
This guarantee prevents [`SQLITE_BUSY`] errors during concurrent writes.
### Write Transactions
#### Write Transactions
**All writes are wrapped in a transaction.**
Concurrent reads can not see partial database updates (even reads performed by other processes).
### Isolated Reads
#### Isolated Reads
**All reads are wrapped in a transaction.**
An isolated read sees a stable and immutable state of the database, and does not see changes performed by eventual concurrent writes (even writes performed by other processes). See [Isolation In SQLite](https://www.sqlite.org/isolation.html) for more information.
### Forbidden Writes
#### Forbidden Writes
**Inside a read access, all attempts to write raise an error.**
This enforces the immutability of the database during a read.
### Non-Reentrancy
#### Non-Reentrancy
**Database accesses methods are not reentrant.**
+6 -6
View File
@@ -249,8 +249,8 @@ try db.create(table: "player") { t in
// One single player at any given position in a team
try db.create(
index: "playerTeamPosition",
on: "player", columns: ["teamId", "position"],
indexOn: "player",
columns: ["teamId", "position"],
options: .unique)
```
@@ -268,10 +268,7 @@ try db.create(
> try db.create(table: "team") { t in
> t.column("name", .text)
> }
> try db.create(
> index: "teamName",
> on: "team", columns: ["name"],
> options: .unique)
> try db.create(indexOn: "team", columns: ["name"], options: .unique)
> ```
>
> If you want to turn an undroppable constraint into a droppable index, you'll need to recreate the database table. See <doc:Migrations> for the detailed procedure.
@@ -365,6 +362,7 @@ extension Team: TableRecord {
- ``Database/create(virtualTable:ifNotExists:using:_:)``
- ``Database/drop(table:)``
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
- ``Database/rename(table:to:)``
- ``Database/ColumnType``
- ``Database/ConflictResolution``
@@ -376,7 +374,9 @@ extension Team: TableRecord {
### Database Indexes
- ``Database/create(indexOn:columns:options:condition:)``
- ``Database/create(index:on:columns:options:condition:)``
- ``Database/drop(indexOn:columns:)``
- ``Database/drop(index:)``
- ``IndexOptions``
-47
View File
@@ -1,47 +0,0 @@
# ``GRDB``
A toolkit for SQLite databases, with a focus on application development
## Overview
Use GRDB to save your application’s permanent data into SQLite databases.
The library provides raw access to SQL and advanced SQLite features, because one sometimes enjoys a sharp tool.
It has robust concurrency primitives, so that multi-threaded applications can efficiently use their databases.
It grants your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to.
Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMDB](https://github.com/ccgus/fmdb), GRDB can spare you a lot of glue code. Compared to [Core Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/) or [Realm](http://realm.io), it can simplify your multi-threaded applications.
## Topics
### Fundamentals
- <doc:DatabaseConnections>
- <doc:SQLSupport>
- <doc:Concurrency>
- <doc:Transactions>
### Migrations and The Database Schema
- <doc:DatabaseSchema>
- <doc:Migrations>
- <doc:SingleRowTables>
### Records and the Query Interface
- <doc:QueryInterface>
- <doc:RecordTimestamps>
### Responding to Database Changes
- <doc:DatabaseObservation>
### Full-Text Search
- <doc:FullTextSearch>
### Combine Publishers
- ``DatabasePublishers``
@@ -165,6 +165,38 @@ This extra conformance is not required: only aim at the low-level C interface if
- ``fetchSet(_:_:)-1foke``
- ``fetchOne(_:_:)-o6yj``
### Supported Value Types
- ``Swift/Bool``
- ``CoreFoundation/CGFloat``
- ``Foundation/Data``
- ``DatabaseDateComponents``
- ``Foundation/Date``
- ``Swift/Double``
- ``Foundation/Decimal``
- ``Swift/Float``
- ``Swift/Int``
- ``Swift/Int8``
- ``Swift/Int16``
- ``Swift/Int32``
- ``Swift/Int64``
- ``Foundation/NSData``
- ``Foundation/NSDate``
- ``Foundation/NSNull``
- ``Foundation/NSNumber``
- ``Foundation/NSString``
- ``Foundation/NSURL``
- ``Foundation/NSUUID``
- ``Swift/Optional``
- ``Swift/UInt``
- ``Swift/UInt8``
- ``Swift/UInt16``
- ``Swift/UInt32``
- ``Swift/UInt64``
- ``Swift/String``
- ``Foundation/URL``
- ``Foundation/UUID``
### Supporting Types
- ``DatabaseValueCursor``
@@ -159,7 +159,7 @@ let cancellable = try sharedObservation
While the standard ``tracking(_:)`` method lets you track changes to a fetched value and receive any changes to it, sometimes your use case might require more granular control.
Consider a scenario where you'd like to get a specific Player's row, but only when their `score` column changes. You can use ``tracking(region:fetch:)`` to do just that:
Consider a scenario where you'd like to get a specific Player's row, but only when their `score` column changes. You can use ``tracking(region:_:fetch:)`` to do just that:
```swift
let observation = ValueObservation.tracking(
@@ -172,7 +172,7 @@ let observation = ValueObservation.tracking(
)
```
This ``tracking(region:fetch:)`` method lets you entirely separate the **observed region** from the **fetched value** itself, for maximum flexibility. See ``DatabaseRegionConvertible`` for more information about the regions that can be tracked.
This ``tracking(region:_:fetch:)`` method lets you entirely separate the **observed region(s)** from the **fetched value** itself, for maximum flexibility. See ``DatabaseRegionConvertible`` for more information about the regions that can be tracked.
## ValueObservation Performance
@@ -219,13 +219,16 @@ When needed, you can help GRDB optimize observations and reduce database content
> Tip: When the observation tracks a constant database region, create an optimized observation with the ``trackingConstantRegion(_:)`` method. See the documentation of this method for more information about what constitutes a "constant region", and the nature of the optimization.
**Truncating WAL checkpoints impact ValueObservation.** Such checkpoints are performed with ``Database/checkpoint(_:on:)`` or [`PRAGMA wal_checkpoint`](https://www.sqlite.org/pragma.html#pragma_wal_checkpoint). When an observation is started on a ``DatabasePool``, from a database that has a missing or empty [wal file](https://www.sqlite.org/tempfiles.html#write_ahead_log_wal_files), the observation will always notify two values when it starts, even if the database content is not changed. This is a consequence of the impossibility to create the [wal snapshot](https://www.sqlite.org/c3ref/snapshot_get.html) needed for detecting that no changes were performed during the observation startup. If your application performs truncating checkpoints, you will avoid this behavior if you recreate a non-empty wal file before starting observations. To do so, perform any kind of no-op transaction (such a creating and dropping a dummy table).
## Topics
### Creating a ValueObservation
- ``tracking(_:)``
- ``trackingConstantRegion(_:)``
- ``tracking(region:fetch:)``
- ``tracking(region:_:fetch:)``
- ``tracking(regions:fetch:)``
### Creating a Shared Observation
+106
View File
@@ -0,0 +1,106 @@
# ``GRDB``
A toolkit for SQLite databases, with a focus on application development
##
![GRDB Logo](GRDBLogo.png)
- [GitHub Repository](http://github.com/groue/GRDB.swift)
- [Installation Instructions, encryption with SQLCipher, custom SQLite builds](https://github.com/groue/GRDB.swift#installation)
- [GRDBQuery](https://github.com/groue/GRDBQuery), the SwiftUI companion for GRDB
## Overview
Use this library to save your application’s permanent data into SQLite databases. It comes with built-in tools that address common needs:
- **SQL Generation**
Enhance your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to.
- **Database Observation**
Get notifications when database values are modified.
- **Robust Concurrency**
Multi-threaded applications can efficiently use their databases, including WAL databases that support concurrent reads and writes.
- **Migrations**
Evolve the schema of your database as you ship new versions of your application.
- **Leverage your SQLite skills**
Not all developers need advanced SQLite features. But when you do, GRDB is as sharp as you want it to be. Come with your SQL and SQLite skills, or learn new ones as you go!
## Usage
Start using the database in four steps:
```swift
import GRDB
// 1. Open a database connection
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
// 2. Define the database schema
try dbQueue.write { db in
try db.create(table: "player") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
t.column("score", .integer).notNull()
}
}
// 3. Define a record type
struct Player: Codable, FetchableRecord, PersistableRecord {
var id: String
var name: String
var score: Int
}
// 4. Write and read in the database
try dbQueue.write { db in
try Player(id: "1", name: "Arthur", score: 100).insert(db)
try Player(id: "2", name: "Barbara", score: 1000).insert(db)
}
let players: [Player] = try dbQueue.read { db in
try Player.fetchAll(db)
}
```
## Topics
### Fundamentals
- <doc:DatabaseConnections>
- <doc:SQLSupport>
- <doc:Concurrency>
- <doc:Transactions>
### Migrations and The Database Schema
- <doc:DatabaseSchema>
- <doc:Migrations>
### Records and the Query Interface
- <doc:QueryInterface>
- <doc:RecordRecommendedPractices>
- <doc:RecordTimestamps>
- <doc:SingleRowTables>
### Responding to Database Changes
- <doc:DatabaseObservation>
### Full-Text Search
- <doc:FullTextSearch>
### Combine Publishers
- ``DatabasePublishers``
@@ -0,0 +1,581 @@
# Recommended Practices for Designing Record Types
Leverage the best of record types and associations.
## Overview
GRDB sits right between low-level SQLite wrappers, and high-level ORMs like [Core Data], so you may face questions when designing the model layer of your application.
This is the topic of this article. Examples will be illustrated with a simple library database made of books and their authors.
## Trust SQLite More Than Yourself
Let's put things in the right order. An SQLite database stored on a user's device is more important than the Swift code that accesses it. When a user installs a new version of an application, only the database stored on the user's device remains the same. But all the Swift code may have changed.
This is why it is recommended to define a **robust database schema** even before playing with record types.
This is important because SQLite is very robust, whereas we developers write bugs. The more responsibility we give to SQLite, the less code we have to write, and the fewer defects we will ship on our users' devices, affecting their precious data.
For example, if we were to define <doc:Migrations> that configure a database made of books and their authors, we could write:
```swift
var migrator = DatabaseMigrator()
migrator.registerMigration("createLibrary") { db in
try db.create(table: "author") { t in // (1)
t.autoIncrementedPrimaryKey("id") // (2)
t.column("name", .text).notNull() // (3)
t.column("countryCode", .text) // (4)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text).notNull() // (5)
t.column("authorId", .integer) // (6)
.notNull() // (7)
.indexed() // (8)
.references("author", onDelete: .cascade) // (9)
}
}
try migrator.migrate(dbQueue)
```
1. Our database tables follow the <doc:DatabaseSchema#Database-Schema-Recommendations>: table names are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
2. Each author has a unique id.
3. An author must have a name.
4. The country of an author is not always known.
5. A book must have a title.
6. The `book.authorId` column is used to link a book to the author it belongs to.
7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
8. The `book.authorId` column is indexed in order to ease the selection of an author's books.
9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions](https://sqlite.org/foreignkeys.html#fk_actions) for more information.
Thanks to this database schema, the application will always process *consistent data*, no matter how wrong the Swift code can get. Even after a hard crash, all books will have an author, a non-nil title, etc.
> Tip: **A local SQLite database is not a JSON payload loaded from a remote server.**
>
> The JSON format and content can not be controlled, and an application must defend itself against wacky servers. But a local database is under your full control. It is trustable. A relational database such as SQLite guarantees the quality of users data, as long as enough energy is put in the proper definition of the database schema.
> Tip: **Plan early for future versions of your application**: use <doc:Migrations>.
## Record Types
### Persistable Record Types are Responsible for Their Tables
**Define one record type per database table.** This record type will be responsible for writing in this table.
**Let's start from regular structs** whose properties match the columns in their database table. Those structs conform to the standard [`Identifiable`] protocol because they have an identifier (the primary key). They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows.
```swift
struct Author: Codable, Identifiable {
var id: Int64?
var name: String
var countryCode: String?
}
struct Book: Codable, Identifiable {
var id: Int64?
var authorId: Int64
var title: String
}
```
**We add database powers to our types with record protocols.**
The `author` and `book` tables have an auto-incremented id. We want inserted records to learn about their id after a successful insertion. That's why we have them conform to the ``MutablePersistableRecord`` protocol, and implement ``MutablePersistableRecord/didInsert(_:)-109jm``. Other kinds of record types would just use ``PersistableRecord``, and ignore `didInsert`.
On the reading side, we use ``FetchableRecord``, the protocol that can decode database rows.
This gives:
```swift
// Add Database access
extension Author: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
extension Book: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
```
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`:
```swift
try dbQueue.write { db in
// Insert and set author's id
var author = Author(name: "Herman Melville", countryCode: "US")
try author.insert(db)
// Insert and set book's id
var book = Book(authorId: author.id!, title: "Moby-Dick")
try book.insert(db)
}
let books = try dbQueue.read { db in
try Book.fetchAll(db)
}
```
> Tip: When a column of a database table can't be NULL, define a non-optional property in the record type. On the other side, when the database may contain NULL, define an optional property. Compare:
>
> ```swift
> try db.create(table: "author") { t in
> t.autoIncrementedPrimaryKey("id")
> t.column("name", .text).notNull() // Can't be NULL
> t.column("countryCode", .text) // Can be NULL
> }
>
> struct Author: Codable, Identifiable {
> var id: Int64?
> var name: String // Not optional
> var countryCode: String? // Optional
> }
> ```
>
> There are exceptions to this rule.
>
> For example, the `id` column is never NULL in the database. And yet, `Author` as an optional `id` property. That is because we want to create instances of `Author` before they could be inserted in the database, and be assigned an auto-incremented id. If the `id` property was not optional, the `Author` type could not profit from auto-incremented ids!
>
> Another exception to this rule is described in <doc:RecordTimestamps>, where the creation date of a record is never NULL in the database, but optional in the Swift type.
> Tip: When the database table has a single-column primary key, have the record type adopt the standard [`Identifiable`] protocol. This allows GRDB to define extra methods based on record ids:
>
> ```swift
> let authorID: Int64 = 42
> let author: Author = try dbQueue.read { db in
> try Author.find(db, id: authorID)
> }
> ```
### Record Types Hide Intimate Database Details
In the previous sample codes, the `Book` and `Author` structs have one property per database column, and their types are natively supported by SQLite (`String`, `Int`, etc.)
But it happens that raw database column names, or raw column types, are not a very good fit for the application.
When this happens, it's time to **distinguish the Swift and database representations**. Record types are the dedicated place where raw database values can be transformed into Swift types that are well-suited for the rest of the application.
Let's look at three examples.
#### First Example: Enums
Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. We decide that a book kind is represented as a string ("novel", "essay", etc.) in the database:
```swift
try db.create(table: "book") { t in
...
t.column("kind", .text).notNull()
}
```
In Swift, it is not a good practice to use `String` for the type of the `kind` property. We prefer an enum instead:
```swift
struct Book: Codable {
enum Kind: String, Codable {
case essay, novel, poetry, theater
}
var id: Int64?
var authorId: Int64
var title: String
var kind: Kind
}
```
Thanks to its enum property, the `Book` record prevents invalid book kinds from being stored into the database.
In order to use `Book.Kind` in database requests for books (see <doc:RecordRecommendedPractices#Record-Requests> below), we add the ``DatabaseValueConvertible`` conformance to `Book.Kind`:
```swift
extension Book.Kind: DatabaseValueConvertible { }
// Fetch all novels
let novels = try dbQueue.read { db in
try Book.filter(Column("kind") == Book.Kind.novel).fetchAll(db)
}
```
#### Second Example: GPS Coordinates
GPS coordinates can be stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
When this happens, keep column properties private, and provide sensible accessors instead:
```swift
try db.create(table: "place") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("latitude", .double).notNull()
t.column("longitude", .double).notNull()
}
struct Place: Codable {
var id: Int64?
var name: String
private var latitude: CLLocationDegrees
private var longitude: CLLocationDegrees
var coordinate: CLLocationCoordinate2D {
get {
CLLocationCoordinate2D(
latitude: latitude,
longitude: longitude)
}
set {
latitude = newValue.latitude
longitude = newValue.longitude
}
}
}
```
Generally speaking, private properties make it possible to hide raw columns from the rest of the application. The next example shows another application of this technique.
#### Third Example: Money Amounts
Before storing money amounts in an SQLite database, take care that [floating-point numbers are never a good fit](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency).
SQLite only supports two kinds of numbers: integers and doubles, so we'll store amounts as integers. $12.00 will be represented by 1200, a quantity of cents. This allows SQLite to compute exact sums of price, for example.
On the other side, an amount of cents is not very practical for the rest of the Swift application. The [`Decimal`] type looks like a better fit.
That's why the `Product` record type has a `price: Decimal` property, backed by a `priceCents` integer column:
```swift
try db.create(table: "product") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("priceCents", .integer).notNull()
}
struct Product: Codable {
var id: Int64?
var name: String
private var priceCents: Int
var price: Decimal {
get {
Decimal(priceCents) / 100
}
set {
priceCents = Self.cents(for: newValue)
}
}
private static func cents(for value: Decimal) -> Int {
Int(Double(truncating: NSDecimalNumber(decimal: value * 100)))
}
}
```
## Record Requests
Once we have record types that are able to read and write in the database, we'd like to perform database requests of such records.
### Columns
Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum:
```swift
// HOW TO define columns for a Codable record
extension Author {
enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let countryCode = Column(CodingKeys.countryCode)
}
}
```
For other record types, declare a plain `String` enum that conforms to the ``ColumnExpression`` protocol:
```swift
// HOW TO define columns for a non-Codable record
extension Author {
enum Columns: String, ColumnExpression {
case id, name, countryCode
}
}
```
From those columns it is possible to define requests of type ``QueryInterfaceRequest``:
```swift
try dbQueue.read { db in
// Fetch all authors, ordered by name,
// in a localized case-insensitive fashion
let sortedAuthors: [Author] = try Author.all()
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
.fetchAll(db)
// Count French authors
let frenchAuthorCount: Int = try Author.all()
.filter(Author.Columns.countryCode == "FR")
.fetchCount(db)
}
```
### Turn Commonly-Used Requests into Methods
An application can define reusable request methods that extend the built-in GRDB apis. Those methods avoid code repetition, ease refactoring, and foster testability.
Define those methods in extensions of the ``DerivableRequest`` protocol, as below:
```swift
// Author requests
extension DerivableRequest<Author> {
/// Order authors by name, in a localized case-insensitive fashion
func orderByName() -> Self {
let name = Author.Columns.name
return order(name.collating(.localizedCaseInsensitiveCompare))
}
/// Filters authors from a country
func filter(countryCode: String) -> Self {
filter(Author.Columns.countryCode == countryCode)
}
}
// Book requests
extension DerivableRequest<Book> {
/// Order books by title, in a localized case-insensitive fashion
func orderByTitle() -> Self {
let title = Book.Columns.title
return order(title.collating(.localizedCaseInsensitiveCompare))
}
/// Filters books by kind
func filter(kind: Book.Kind) -> Self {
filter(Book.Columns.kind == kind)
}
}
```
Those methods define a fluent and legible api that encapsulates intimate database details:
```swift
try dbQueue.read { db in
let sortedSpanishAuthors: [Author] = try Author.all()
.filter(countryCode: "ES")
.orderByName()
.fetchAll(db)
let novelCount: Int = try Book.all()
.filter(kind: .novel)
.fetchCount(db)
}
```
Extensions to the `DerivableRequest` protocol can not change the type of requests. They remain requests of the base record. To define requests of another type, use an extension to ``QueryInterfaceRequest``, as in the example below:
```swift
extension QueryInterfaceRequest<Author> {
// Selects author ids
func selectId() -> QueryInterfaceRequest<Int64> {
selectPrimaryKey(as: Int64.self)
}
}
// The ids of Japanese authors
let ids: Set<Int64> = try Author.all()
.filter(countryCode: "JP")
.selectId()
.fetchSet(db)
```
## Associations
[Associations] help navigating from authors to their books and vice versa. Because the `book` table has an `authorId` column, we say that each book **belongs to** its author, and each author **has many** books:
```swift
extension Book {
static let author = belongsTo(Author.self)
}
extension Author {
static let books = hasMany(Book.self)
}
```
With associations, you can fetch a book's author, or an author's books:
```swift
// Fetch all novels from an author
try dbQueue.read { db in
let author: Author = ...
let novels: [Book] = try author.request(for: Author.books)
.filter(kind: .novel)
.orderByTitle()
.fetchAll(db)
}
```
Associations also make it possible to define more convenience request methods:
```swift
extension DerivableRequest<Book> {
/// Filters books from a country
func filter(authorCountryCode countryCode: String) -> Self {
// Books do not have any country column. But their author has one!
// Return books that can be joined to an author from this country:
joining(required: Book.author.filter(countryCode: countryCode))
}
}
// Fetch all Italian novels
try dbQueue.read { db in
let italianNovels: [Book] = try Book.all()
.filter(kind: .novel)
.filter(authorCountryCode: "IT")
.fetchAll(db)
}
```
With associations, you can also process graphs of authors and books, as described in the next section.
### How to Model Graphs of Objects
Since the beginning of this article, the `Book` and `Author` are independent structs that don't know each other. The only "meeting point" is the `Book.authorId` property.
Record types don't know each other on purpose: one does not need to know the author of a book when it's time to update the title of a book, for example.
When an application wants to process authors and books together, it defines dedicated types that model the desired view on the graph of related objects. For example:
```swift
// Fetch all authors along with their number of books
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookCount: Int
}
let authorInfos: [AuthorInfo] = try dbQueue.read { db in
try Author
.annotated(with: Author.books.count)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
}
```
```swift
// Fetch the literary careers of German authors, sorted by name
struct LiteraryCareer: Codable, FetchableRecord {
var author: Author
var books: [Book]
}
let careers: [LiteraryCareer] = try dbQueue.read { db in
try Author
.filter(countryCode: "DE")
.orderByName()
.including(all: Author.books)
.asRequest(of: LiteraryCareer.self)
.fetchAll(db)
}
```
```swift
// Fetch all Colombian books and their authors
struct Authorship: Decodable, FetchableRecord {
var book: Book
var author: Author
}
let authorships: [Authorship] = try dbQueue.read { db in
try Book.all()
.including(required: Book.author.filter(countryCode: "CO"))
.asRequest(of: Authorship.self)
.fetchAll(db)
// Equivalent alternative
try Book.all()
.filter(authorCountryCode: "CO")
.including(required: Book.author)
.asRequest(of: Authorship.self)
.fetchAll(db)
}
```
In the above sample codes, requests that fetch values from several tables are decoded into additional record types: `AuthorInfo`, `LiteraryCareer`, and `Authorship`.
Those record type conform to both [`Decodable`] and ``FetchableRecord``, so that they can feed from database rows. They do not provide any persistence methods, though. **All database writes are performed from persistable record instances** (of type `Author` or `Book`).
For more information about associations, see the [Associations] guide.
### Lazy and Eager Loading: Comparison with Other Database Libraries
The additional record types described in the previous section may look superfluous. Some other database libraries are able to navigate in graphs of records without additional types.
For example, [Core Data] and Ruby's [Active Record] use **lazy loading**. This means that relationships are lazily fetched on demand:
```ruby
# Lazy loading with Active Record
author = Author.first # Fetch first author
puts author.name
author.books.each do |book| # Lazily fetch books on demand
puts book.title
end
```
**GRDB does not perform lazy loading.** In a GUI application, lazy loading can not be achieved without record management (as in [Core Data]), which in turn comes with non-trivial pain points for developers regarding concurrency. Instead of lazy loading, the library provides the tooling needed to fetch data, even complex graphs, in an [isolated] fashion, so that fetched values accurately represent the database content, and all database invariants are preserved. See the <doc:Concurrency> guide for more information.
Vapor [Fluent] uses **eager loading**, which means that relationships are only fetched if explicitly requested:
```swift
// Eager loading with Fluent
let query = Author.query(on: db)
.with(\.$books) // <- Explicit request for books
.first()
// Fetch first author and its books in one stroke
if let author = query.get() {
print(author.name)
for book in author.books { print(book.title) }
}
```
One must take care of fetching relationships, though, or Fluent raises a fatal error:
```swift
// Oops, the books relation is not explicitly requested
let query = Author.query(on: db).first()
if let author = query.get() {
// fatal error: Children relation not eager loaded.
for book in author.books { print(book.title) }
}
```
**GRDB supports eager loading**. The difference with Fluent is that the relationships are modelled in a dedicated record type that provides runtime safety:
```swift
// Eager loading with GRDB
struct LiteraryCareer: Codable, FetchableRecord {
var author: Author
var books: [Book]
}
let request = Author.all()
.including(all: Author.books) // <- Explicit request for books
.asRequest(of: LiteraryCareer.self)
// Fetch first author and its books in one stroke
if let career = try request.fetchOne(db) {
print(career.author.name)
for book in career.books { print(book.title) }
}
```
[Active Record]: http://guides.rubyonrails.org/active_record_basics.html
[`Codable`]: https://developer.apple.com/documentation/swift/Codable
[Core Data]: https://developer.apple.com/documentation/coredata
[`Decimal`]: https://developer.apple.com/documentation/foundation/decimal
[`Decodable`]: https://developer.apple.com/documentation/swift/Decodable
[Django]: https://docs.djangoproject.com/en/4.2/topics/db/
[Fluent]: https://docs.vapor.codes/fluent/overview/
[`Identifiable`]: https://developer.apple.com/documentation/swift/identifiable
[isolated]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
[Associations]: https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

-1
View File
@@ -81,7 +81,6 @@ For a more detailed overview, see [SQLite API](https://github.com/groue/GRDB.swi
### Database Values
- ``DatabaseDateComponents``
- ``DatabaseValueConvertible``
- ``StatementColumnConvertible``
+3 -3
View File
@@ -61,7 +61,7 @@ extension Database {
///
/// class MyTokenizer : FTS5CustomTokenizer { ... }
/// db.add(tokenizer: MyTokenizer.self)
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
public func add(tokenizer: (some FTS5CustomTokenizer).Type) {
let api = FTS5.api(self)
// Swift won't let the @convention(c) xCreate() function below create
@@ -76,7 +76,7 @@ extension Database {
return SQLITE_ERROR
}
do {
let tokenizer = try Tokenizer(db: db, arguments: arguments)
let tokenizer = try tokenizer.init(db: db, arguments: arguments)
// Tokenizer must remain alive until xDeleteTokenizer()
// is called, as the xDelete member of xTokenizer
@@ -158,7 +158,7 @@ extension Database {
let code = withUnsafeMutablePointer(to: &xTokenizer) { xTokenizerPointer in
api.pointee.xCreateTokenizer(
UnsafeMutablePointer(mutating: api),
Tokenizer.name,
tokenizer.name,
constructorPointer,
xTokenizerPointer,
deleteConstructor)
+3 -1
View File
@@ -57,7 +57,7 @@ extension DatabaseCursor {
extension DatabaseMigrator {
@available(*, unavailable, message: "The completion function now accepts one Result<Database, Error> argument")
public func asyncMigrate(
_ writer: DatabaseWriter,
_ writer: any DatabaseWriter,
completion: @escaping (Database, Error?) -> Void)
{ preconditionFailure() }
}
@@ -167,3 +167,5 @@ extension ValueObservation {
where Reducer == ValueReducers.Fetch<Value>
{ preconditionFailure() }
}
// swiftlint:enable all
+7 -1
View File
@@ -457,7 +457,13 @@ public struct DatabaseMigrator {
}
}()
if try db.schema(.main) != tmpSchema {
// Only compare user objects
func isUserObject(_ object: SchemaObject) -> Bool {
!Database.isSQLiteInternalTable(object.name) && !Database.isGRDBInternalTable(object.name)
}
let tmpUserSchema = tmpSchema.filter(isUserObject)
let userSchema = try db.schema(.main).filter(isUserObject)
if userSchema != tmpUserSchema {
needsErase = true
return .commit
}
@@ -436,7 +436,7 @@ extension QueryInterfaceRequest: DerivableRequest {
}
}
public func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self {
public func with<T>(_ cte: CommonTableExpression<T>) -> Self {
with {
$0.relation.ctes[cte.tableName] = cte.cte
}
@@ -1279,6 +1279,90 @@ extension ColumnExpression {
public static func /= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
column.set(to: column / value)
}
/// Creates an assignment that applies a bitwise and.
///
/// For example:
///
/// ```swift
/// Column("mask") &= 2
/// Column("mask") &= Column("other")
/// ```
///
/// Usage:
///
/// ```swift
/// try dbQueue.write { db in
/// // UPDATE player SET score = score & 2
/// try Player.updateAll(db, Column("mask") &= 2)
/// }
/// ```
public static func &= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
column.set(to: column & value)
}
/// Creates an assignment that applies a bitwise or.
///
/// For example:
///
/// ```swift
/// Column("mask") |= 2
/// Column("mask") |= Column("other")
/// ```
///
/// Usage:
///
/// ```swift
/// try dbQueue.write { db in
/// // UPDATE player SET score = score | 2
/// try Player.updateAll(db, Column("mask") |= 2)
/// }
/// ```
public static func |= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
column.set(to: column | value)
}
/// Creates an assignment that applies a bitwise left shift.
///
/// For example:
///
/// ```swift
/// Column("mask") <<= 2
/// Column("mask") <<= Column("other")
/// ```
///
/// Usage:
///
/// ```swift
/// try dbQueue.write { db in
/// // UPDATE player SET score = score << 2
/// try Player.updateAll(db, Column("mask") <<= 2)
/// }
/// ```
public static func <<= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
column.set(to: column << value)
}
/// Creates an assignment that applies a bitwise right shift.
///
/// For example:
///
/// ```swift
/// Column("mask") >>= 2
/// Column("mask") >>= Column("other")
/// ```
///
/// Usage:
///
/// ```swift
/// try dbQueue.write { db in
/// // UPDATE player SET score = score >> 2
/// try Player.updateAll(db, Column("mask") >>= 2)
/// }
/// ```
public static func >>= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
column.set(to: column >> value)
}
}
// MARK: - Eager loading of hasMany associations
@@ -214,6 +214,7 @@ extension SelectionRequest {
///
/// ### The WHERE and JOIN ON Clauses
///
/// - ``all()``
/// - ``filter(_:)``
/// - ``filter(literal:)``
/// - ``filter(sql:arguments:)``
@@ -291,6 +292,13 @@ extension FilteredRequest {
public func none() -> Self {
filterWhenConnected { _ in false }
}
/// Returns `self`: a request that fetches all rows from this request.
///
/// This method, which does nothing, exists in order to match ``none()``.
public func all() -> Self {
self
}
}
// MARK: - TableRequest
@@ -1328,6 +1336,7 @@ extension JoinableRequest where Self: SelectionRequest {
///
/// ### The WHERE Clause
///
/// - ``FilteredRequest/all()``
/// - ``FilteredRequest/filter(_:)``
/// - ``TableRequest/filter(id:)``
/// - ``TableRequest/filter(ids:)``
+114 -35
View File
@@ -196,7 +196,7 @@ public struct SQLExpression {
/// An associative binary SQL operator, such as `+`, `*`, `AND`, etc.
///
/// Use it with the `joined(operator:)` method. For example:
/// Use an associative operator with the `joined(operator:)` method:
///
/// ```swift
/// // SELECT score + bonus + 1000 FROM player
@@ -206,6 +206,27 @@ public struct SQLExpression {
/// 1000.databaseValue]
/// let request = Player.select(values.joined(operator: .add))
/// ```
///
/// ## Topics
///
/// ### Arithmetic Operators
///
/// - ``add``
/// - ``multiply``
///
/// ### Logical Operators
///
/// - ``and``
/// - ``or``
///
/// ### String Operators
///
/// - ``concat``
///
/// ### Bitwise Operators
///
/// - ``bitwiseAnd``
/// - ``bitwiseOr``
public struct AssociativeBinaryOperator: Hashable {
/// The SQL operator
let sql: String
@@ -215,7 +236,7 @@ public struct SQLExpression {
/// If true, (a • b) • c is strictly equal to a • (b • c).
///
/// `AND`, `OR`, `||` (concat) are stricly associative.
/// `AND`, `OR`, `||` (concat), `&`, `|` are stricly associative.
///
/// `+` and `*` are not stricly associative when applied to floating
/// point values.
@@ -226,7 +247,7 @@ public struct SQLExpression {
///
/// `||` (concat) is bijective.
///
/// `AND`, `OR`, `+` and `*` are not.
/// `AND`, `OR`, `+` and `*`, `&`, `|` are not.
let isBijective: Bool
/// Creates a binary operator
@@ -237,7 +258,7 @@ public struct SQLExpression {
self.isBijective = bijective
}
/// The `+` binary SQL operator.
/// The arithmetic `+` binary SQL operator.
///
/// For example:
///
@@ -245,13 +266,19 @@ public struct SQLExpression {
/// // score + bonus
/// [Column("score"), Column("bonus")].joined(operator: .add)
/// ```
///
/// The neutral value of the `add` operator, used when joining an
/// empty sequence, is `0`.
///
/// The `add` operator performs a numeric addition. To concatenate
/// strings, use the ``concat`` operator instead.
public static let add = AssociativeBinaryOperator(
sql: "+",
neutralValue: 0.databaseValue,
strictlyAssociative: false,
bijective: false)
/// The `*` binary SQL operator.
/// The arithmetic `*` binary SQL operator.
///
/// For example:
///
@@ -259,13 +286,16 @@ public struct SQLExpression {
/// // score * factor
/// [Column("score"), Column("factor")].joined(operator: .multiply)
/// ```
///
/// The neutral value of the `multiply` operator, used when joining an
/// empty sequence, is `1`.
public static let multiply = AssociativeBinaryOperator(
sql: "*",
neutralValue: 1.databaseValue,
strictlyAssociative: false,
bijective: false)
/// The `AND` binary SQL operator.
/// The logical `AND` binary SQL operator.
///
/// For example:
///
@@ -273,13 +303,16 @@ public struct SQLExpression {
/// // isBlue AND isTall
/// [Column("isBlue"), Column("isTall")].joined(operator: .and)
/// ```
///
/// The neutral value of the `and` operator, used when joining an
/// empty sequence, is `true`.
public static let and = AssociativeBinaryOperator(
sql: "AND",
neutralValue: true.databaseValue,
strictlyAssociative: true,
bijective: false)
/// The `OR` binary SQL operator.
/// The logical `OR` binary SQL operator.
///
/// For example:
///
@@ -287,6 +320,9 @@ public struct SQLExpression {
/// // isBlue OR isTall
/// [Column("isBlue"), Column("isTall")].joined(operator: .or)
/// ```
///
/// The neutral value of the `or` operator, used when joining an
/// empty sequence, is `false`.
public static let or = AssociativeBinaryOperator(
sql: "OR",
neutralValue: false.databaseValue,
@@ -301,11 +337,49 @@ public struct SQLExpression {
/// // firstName || ' ' || lastName
/// [Column("firstName"), " ", Column("lastName")].joined(operator: .concat)
/// ```
///
/// The neutral value of the `concat` operator, used when joining an
/// empty sequence, is the empty string.
public static let concat = AssociativeBinaryOperator(
sql: "||",
neutralValue: "".databaseValue,
strictlyAssociative: true,
bijective: true)
/// The bitwise `&` SQL operator.
///
/// For example:
///
/// ```swift
/// // mask & 2
/// [Column("mask"), 2.databaseValue].joined(operator: .bitwiseAnd)
/// ```
///
/// The neutral value of the `bitwiseAnd` operator, used when
/// joining an empty sequence, is `-1` (the signed 64-bit integer
/// with all bits set).
public static let bitwiseAnd = AssociativeBinaryOperator(
sql: "&",
neutralValue: (-1).databaseValue,
strictlyAssociative: true,
bijective: false)
/// The bitwise `|` SQL operator.
///
/// For example:
///
/// ```swift
/// // mask | 2
/// [Column("mask"), 2.databaseValue].joined(operator: .bitwiseOr)
/// ```
///
/// The neutral value of the `bitwiseOr` operator, used when
/// joining an empty sequence, is `0`.
public static let bitwiseOr = AssociativeBinaryOperator(
sql: "|",
neutralValue: 0.databaseValue,
strictlyAssociative: true,
bijective: false)
}
/// `BinaryOperator` is an SQLite binary operator, such as `>`, `=`, etc.
@@ -343,6 +417,12 @@ public struct SQLExpression {
/// The `MATCH` binary operator
static let match = BinaryOperator("MATCH")
/// The `<<` bitwise left shift operator
static let leftShift = BinaryOperator("<<")
/// The `>>` bitwise right shift operator
static let rightShift = BinaryOperator(">>")
}
/// `EscapableBinaryOperator` is an SQLite binary operator that accepts an
@@ -399,19 +479,16 @@ public struct SQLExpression {
/// The SQL operator
let sql: String
/// If true GRDB puts a white space between the operator and the operand.
let needsRightSpace: Bool
/// Creates an unary operator
///
/// UnaryOperator("~", needsRightSpace: false)
init(_ sql: String, needsRightSpace: Bool) {
/// Creates an unary operator.
init(_ sql: String) {
self.sql = sql
self.needsRightSpace = needsRightSpace
}
/// The `-` unary operator
static let minus = UnaryOperator("-", needsRightSpace: false)
static let minus = UnaryOperator("-")
/// The `~` unary operator
static let bitwiseNot = UnaryOperator("~")
}
}
@@ -1021,9 +1098,7 @@ extension SQLExpression {
return resultSQL
case let .unary(op, expression):
var resultSQL = try op.sql
+ (op.needsRightSpace ? " " : "")
+ expression.sql(context, wrappedInParenthesis: true)
var resultSQL = try op.sql + expression.sql(context, wrappedInParenthesis: true)
if wrappedInParenthesis {
resultSQL = "(\(resultSQL))"
}
@@ -1757,6 +1832,20 @@ extension SQLExpressible where Self == Column {
/// - ``uppercased``
/// - ``SQLDateModifier``
///
/// ### Create SQL Expressions from Sequences
///
/// - ``Swift/Sequence/contains(_:)-9i0ld``
/// - ``Swift/Sequence/contains(_:)-o8ic``
/// - ``Swift/Sequence/joined(operator:)-33dy5``
/// - ``Swift/Sequence/joined(operator:)-4k88t``
///
/// ### Create SQL Expressions from Ranges
///
/// - ``Swift/ClosedRange/contains(_:)-64zwp``
/// - ``Swift/ClosedRange/contains(_:)-19a6d``
/// - ``Swift/Range/contains(_:)-11nr0``
/// - ``Swift/Range/contains(_:)-3v32b``
///
/// ### Creating Ordering Terms
///
/// - ``asc``
@@ -1824,13 +1913,8 @@ extension Sequence where Element: SQLSpecificExpressible {
/// ```
///
/// When the sequence is empty, `joined(operator:)` returns the neutral
/// value of the operator. It is:
///
/// - `0` for ``SQLExpression/AssociativeBinaryOperator/add``
/// - `1` for ``SQLExpression/AssociativeBinaryOperator/multiply``
/// - `false` for ``SQLExpression/AssociativeBinaryOperator/or``
/// - `true` for ``SQLExpression/AssociativeBinaryOperator/and``
/// - `""` for ``SQLExpression/AssociativeBinaryOperator/concat``
/// value of the operator. See
/// ``SQLExpression/AssociativeBinaryOperator`` for more information.
public func joined(operator: SQLExpression.AssociativeBinaryOperator) -> SQLExpression {
.associativeBinary(`operator`, map(\.sqlExpression))
}
@@ -1842,7 +1926,7 @@ extension Sequence where Element == any SQLSpecificExpressible {
///
/// For example:
///
/// ```
/// ```swift
/// // SELECT * FROM player
/// // WHERE (registered
/// // AND (score >= 1000)
@@ -1855,13 +1939,8 @@ extension Sequence where Element == any SQLSpecificExpressible {
/// ```
///
/// When the sequence is empty, `joined(operator:)` returns the neutral
/// value of the operator. It is:
///
/// - `0` for ``SQLExpression/AssociativeBinaryOperator/add``
/// - `1` for ``SQLExpression/AssociativeBinaryOperator/multiply``
/// - `false` for ``SQLExpression/AssociativeBinaryOperator/or``
/// - `true` for ``SQLExpression/AssociativeBinaryOperator/and``
/// - `""` for ``SQLExpression/AssociativeBinaryOperator/concat``
/// value of the operator. See
/// ``SQLExpression/AssociativeBinaryOperator`` for more information.
public func joined(operator: SQLExpression.AssociativeBinaryOperator) -> SQLExpression {
.associativeBinary(`operator`, map(\.sqlExpression))
}
@@ -1936,7 +2015,7 @@ extension SQLSpecificExpressible {
/// Returns an aliased column with the same name as the coding key.
///
/// See ``forKey(_:)-3xk0``.
/// See <doc:SQLSpecificExpressible/forKey(_:)-3xk0>.
public func forKey(_ key: some CodingKey) -> SQLSelection {
forKey(key.stringValue)
}
@@ -436,6 +436,75 @@ extension SQLSpecificExpressible {
}
}
// MARK: - Bitwise Operators (&, |, ~, <<, >>)
extension SQLSpecificExpressible {
/// The `&` SQL operator.
public static func & (lhs: Self, rhs: some SQLExpressible) -> SQLExpression {
.associativeBinary(.bitwiseAnd, [lhs.sqlExpression, rhs.sqlExpression])
}
/// The `&` SQL operator.
public static func & (lhs: some SQLExpressible, rhs: Self) -> SQLExpression {
.associativeBinary(.bitwiseAnd, [lhs.sqlExpression, rhs.sqlExpression])
}
/// The `&` SQL operator.
public static func & (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression {
.associativeBinary(.bitwiseAnd, [lhs.sqlExpression, rhs.sqlExpression])
}
/// The `|` SQL operator.
public static func | (lhs: Self, rhs: some SQLExpressible) -> SQLExpression {
.associativeBinary(.bitwiseOr, [lhs.sqlExpression, rhs.sqlExpression])
}
/// The `|` SQL operator.
public static func | (lhs: some SQLExpressible, rhs: Self) -> SQLExpression {
.associativeBinary(.bitwiseOr, [lhs.sqlExpression, rhs.sqlExpression])
}
/// The `|` SQL operator.
public static func | (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression {
.associativeBinary(.bitwiseOr, [lhs.sqlExpression, rhs.sqlExpression])
}
/// The `<<` SQL operator.
public static func << (lhs: Self, rhs: some SQLExpressible) -> SQLExpression {
.binary(.leftShift, lhs.sqlExpression, rhs.sqlExpression)
}
/// The `<<` SQL operator.
public static func << (lhs: some SQLExpressible, rhs: Self) -> SQLExpression {
.binary(.leftShift, lhs.sqlExpression, rhs.sqlExpression)
}
/// The `<<` SQL operator.
public static func << (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression {
.binary(.leftShift, lhs.sqlExpression, rhs.sqlExpression)
}
/// The `>>` SQL operator.
public static func >> (lhs: Self, rhs: some SQLExpressible) -> SQLExpression {
.binary(.rightShift, lhs.sqlExpression, rhs.sqlExpression)
}
/// The `>>` SQL operator.
public static func >> (lhs: some SQLExpressible, rhs: Self) -> SQLExpression {
.binary(.rightShift, lhs.sqlExpression, rhs.sqlExpression)
}
/// The `>>` SQL operator.
public static func >> (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression {
.binary(.rightShift, lhs.sqlExpression, rhs.sqlExpression)
}
/// The `~` SQL operator.
public static prefix func ~ (value: Self) -> SQLExpression {
.unary(.bitwiseNot, value.sqlExpression)
}
}
// MARK: - Like Operator
extension SQLSpecificExpressible {
+6 -1
View File
@@ -612,7 +612,12 @@ extension SQLRelation {
guard !isDistinct else {
return try fetchTrivialCount(db)
}
// <https://github.com/groue/GRDB.swift/issues/1357>
guard selection.allSatisfy(\.isTriviallyCountable) else {
return try fetchTrivialCount(db)
}
// SELECT expr1, expr2, ... FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
@@ -244,6 +244,18 @@ extension SQLSelection {
return .literal(sqlLiteral.qualified(with: alias))
}
}
/// Supports SQLRelation.fetchCount.
///
/// See <https://github.com/groue/GRDB.swift/issues/1357>
var isTriviallyCountable: Bool {
switch impl {
case .aliasedExpression, .literal:
return false
case .allColumns, .qualifiedAllColumns, .expression:
return true
}
}
}
extension [SQLSelection] {
+12 -12
View File
@@ -298,10 +298,10 @@ extension Table {
/// let maxScore: Int = row[1]
/// }
/// ```
public func select<RowDecoder>(
public func select<T>(
_ selection: [any SQLSelectable],
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
as type: T.Type = T.self)
-> QueryInterfaceRequest<T>
{
all().select(selection, as: type)
}
@@ -328,10 +328,10 @@ extension Table {
/// let maxScore: Int = row[1]
/// }
/// ```
public func select<RowDecoder>(
public func select<T>(
_ selection: any SQLSelectable...,
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
as type: T.Type = T.self)
-> QueryInterfaceRequest<T>
{
all().select(selection, as: type)
}
@@ -353,11 +353,11 @@ extension Table {
/// let request = playerTable.select(sql: "IFNULL(name, ?)", arguments: [defaultName], as: String.self)
/// let names = try request.fetchAll(db) // [String]
/// ```
public func select<RowDecoder>(
public func select<T>(
sql: String,
arguments: StatementArguments = StatementArguments(),
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
as type: T.Type = T.self)
-> QueryInterfaceRequest<T>
{
all().select(SQL(sql: sql, arguments: arguments), as: type)
}
@@ -376,10 +376,10 @@ extension Table {
/// let request = playerTable.select(literal: "IFNULL(name, \(defaultName))", as: String.self)
/// let names = try request.fetchAll(db) // [String]
/// ```
public func select<RowDecoder>(
public func select<T>(
literal sqlLiteral: SQL,
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
as type: T.Type = T.self)
-> QueryInterfaceRequest<T>
{
all().select(sqlLiteral, as: type)
}
@@ -2,7 +2,6 @@ extension Database {
// MARK: - Database Schema
// TODO: deprecate just before GRDB 6
/// Creates a database table.
///
/// For example:
@@ -211,7 +210,7 @@ extension Database {
/// t.column("score", .integer).indexed()
/// ```
///
/// For extra index options, see ``create(index:on:columns:options:condition:)``.
/// For extra index options, see ``create(indexOn:columns:options:condition:)``.
///
/// ### Generated columns
///
@@ -321,13 +320,13 @@ extension Database {
try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)")
}
// TODO: deprecate just before GRDB 6
/// Creates an index.
///
/// For example:
///
/// ```swift
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"])
/// // CREATE INDEX index_player_on_email ON player(email)
/// try db.create(index: "index_player_on_email", on: "player", columns: ["email"])
/// ```
///
/// SQLite can also index expressions (<https://www.sqlite.org/expridx.html>)
@@ -342,7 +341,7 @@ extension Database {
///
/// - warning: This is a legacy interface that is preserved for backwards
/// compatibility. Use of this interface is not recommended: prefer
/// ``create(index:on:columns:options:condition:)`` instead.
/// ``create(indexOn:columns:options:condition:)`` instead.
///
/// - parameters:
/// - name: The index name.
@@ -374,7 +373,15 @@ extension Database {
/// For example:
///
/// ```swift
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"])
/// // CREATE INDEX index_player_on_email ON player(email)
/// try db.create(index: "index_player_on_email", on: "player", columns: ["email"])
/// ```
///
/// To create a unique index, specify the `.unique` option:
///
/// ```swift
/// // CREATE UNIQUE INDEX index_player_on_email ON player(email)
/// try db.create(index: "index_player_on_email", on: "player", columns: ["email"], options: .unique)
/// ```
///
/// SQLite can also index expressions (<https://www.sqlite.org/expridx.html>)
@@ -413,15 +420,88 @@ extension Database {
try execute(sql: sql)
}
/// Creates an index on the specified table and columns.
///
/// The created index is named after the table and the column name(s):
///
/// ```swift
/// // CREATE INDEX index_player_on_email ON player(email)
/// try db.create(indexOn: "player", columns: ["email"])
/// ```
///
/// To create a unique index, specify the `.unique` option:
///
/// ```swift
/// // CREATE UNIQUE INDEX index_player_on_email ON player(email)
/// try db.create(indexOn: "player", columns: ["email"], options: .unique)
/// ```
///
/// In order to specify the index name, use
/// ``create(index:on:columns:options:condition:)`` instead.
///
/// SQLite can also index expressions (<https://www.sqlite.org/expridx.html>)
/// and use specific collations. To create such an index, use a raw SQL
/// query:
///
/// ```swift
/// try db.execute(sql: "CREATE INDEX ...")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createindex.html>
///
/// - parameters:
/// - table: The name of the indexed table.
/// - columns: The indexed columns.
/// - options: Index creation options.
/// - condition: If not nil, creates a partial index
/// (see <https://www.sqlite.org/partialindex.html>).
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create(
indexOn table: String,
columns: [String],
options: IndexOptions = [],
condition: (any SQLExpressible)? = nil)
throws
{
try create(
index: defaultIndexName(on: table, columns: columns),
on: table,
columns: columns,
options: options,
condition: condition)
}
private func defaultIndexName(on table: String, columns: [String]) -> String {
"index_\(table)_on_\(columns.joined(separator: "_"))"
}
/// Deletes a database index.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_dropindex.html>
///
/// - parameter name: The index name.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func drop(index name: String) throws {
try execute(sql: "DROP INDEX \(name.quotedDatabaseIdentifier)")
}
/// Deletes the database index on the specified table and columns
/// if exactly one such index exists.
///
/// - parameters:
/// - table: The name of the indexed table.
/// - columns: The indexed columns.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func drop(indexOn table: String, columns: [String]) throws {
let lowercasedColumns = columns.map { $0.lowercased() }
let indexes = try indexes(on: table).filter { index in
index.columns.map({ $0.lowercased() }) == lowercasedColumns
}
if let index = indexes.first, indexes.count == 1 {
try drop(index: index.name)
}
}
/// Deletes and recreates from scratch all indices that use this collation.
///
/// This method is useful when the definition of a collation sequence
@@ -512,7 +592,8 @@ public struct TableOptions: OptionSet {
///
/// ### Define Others Constraints
///
/// - ``check(_:)``
/// - ``check(_:)-6u1za``
/// - ``check(_:)-jpcg``
/// - ``check(sql:)``
/// - ``constraint(literal:)``
/// - ``constraint(sql:)``
@@ -910,10 +991,49 @@ public final class TableDefinition {
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#ckconst>
///
/// - parameter condition: The checked condition.
@available(*, deprecated)
public func check(_ condition: some SQLExpressible) {
checkConstraints.append(condition.sqlExpression)
}
/// Adds a check constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player (
/// // personalPhone TEXT,
/// // workPhone TEXT,
/// // CHECK personalPhone IS NOT NULL OR workPhone IS NOT NULL
/// // )
/// try db.create(table: "player") { t in
/// t.column("personalPhone", .text)
/// t.column("workPhone", .text)
/// let personalPhone = Column("personalPhone")
/// let workPhone = Column("workPhone")
/// t.check(personalPhone != nil || workPhone != nil)
/// }
/// ```
///
/// When defining a check constraint on a single column, you can use the
/// ``ColumnDefinition/check(_:)`` shortcut:
///
/// ```swift
/// // CREATE TABLE player(
/// // name TEXT CHECK (LENGTH(name) > 0)
/// // )
/// try db.create(table: "player") { t in
/// t.column("name", .text).check { length($0) > 0 }
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#ckconst>
///
/// - parameter condition: The checked condition.
public func check(_ condition: some SQLSpecificExpressible) {
checkConstraints.append(condition.sqlExpression)
}
/// Adds a check constraint.
///
/// For example:
+61 -6
View File
@@ -3,16 +3,71 @@ import Foundation
extension FetchableRecord where Self: Decodable {
/// Creates a record from `row`, using the `Decodable` conformance.
public init(row: Row) throws {
self = try RowDecoder().decode(from: row)
self = try FetchableRecordDecoder().decode(Self.self, from: row)
}
}
// For testability. Not intended to become public as long as FetchableRecord has
// a non-throwing row initializer, since this would open an undesired door.
class RowDecoder {
init() { }
/// An object that decodes fetchable records from database rows.
///
/// The example below shows how to decode an instance of a simple `Player`
/// type, that conforms to both ``FetchableRecord`` and `Decodable`, from a
/// database row.
///
/// ```swift
/// struct Player: FetchableRecord, Decodable {
/// var id: Int64
/// var name: String
/// var score: Int
/// }
///
/// try dbQueue.read { db in
/// if let row = try Row.fetchOne(db, sql: "SELECT * FROM player WHERE id = 42") {
/// let decoder = FetchableRecordDecoder()
/// let player = try decoder.decode(Player.self, from: row)
/// print(player.name)
/// }
/// }
/// ```
///
/// You will generally not need to create an instance of
/// `FetchableRecordDecoder`. The above sample code is correct, but you will
/// generally write instead:
///
/// ```swift
/// try dbQueue.read { db in
/// // Prefer the init(row:) initializer:
/// if let row = try Row.fetchOne(db, sql: "SELECT * FROM player WHERE id = 42") {
/// let player = try Player(row: row)
/// print(player.name)
/// }
///
/// // OR just directly fetch a player:
/// if let player = try Player.fetchOne(db, sql: "SELECT * FROM player WHERE id = 42") {
/// print(player.name)
/// }
/// }
/// ```
///
/// The behavior of the decoder depends on the decoded type. See:
///
/// - ``FetchableRecord/databaseColumnDecodingStrategy-6uefz``
/// - ``FetchableRecord/databaseDateDecodingStrategy-78y03``
/// - ``FetchableRecord/databaseDecodingUserInfo-77jim``
/// - ``FetchableRecord/databaseJSONDecoder(for:)-7lmxd``
public class FetchableRecordDecoder {
/// Creates a decoder for fetchable records.
public init() { }
func decode<T: FetchableRecord & Decodable>(_ type: T.Type = T.self, from row: Row) throws -> T {
/// Returns a record of the type you specify, decoded from a
/// database row.
///
/// - Parameters:
/// - type: The type of the record to decode from the supplied
/// database row.
/// - row: The database row to decode.
/// - Returns: An instance of the specified record type, if the decoder
/// can parse the database row.
public func decode<T: FetchableRecord & Decodable>(_ type: T.Type, from row: Row) throws -> T {
let decoder = _RowDecoder<T>(row: row, codingPath: [], columnDecodingStrategy: T.databaseColumnDecodingStrategy)
return try T(from: decoder)
}
+4 -1
View File
@@ -98,6 +98,7 @@ import Foundation
/// ### Supporting Types
///
/// - ``RecordCursor``
/// - ``FetchableRecordDecoder``
public protocol FetchableRecord {
// MARK: - Row Decoding
@@ -803,9 +804,11 @@ public final class RecordCursor<Record: FetchableRecord>: DatabaseCursor {
let _row: Row // Instantiated once, reused for performance
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
let statement = try statement.databaseCursorStatement(with: arguments)
self._statement = statement
_row = try Row(statement: statement).adapted(with: adapter, layout: statement)
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
@@ -434,6 +434,15 @@ extension MutablePersistableRecord {
// Rowid is the last column
let rowid: Int64 = row[row.count - 1]
let returned = try decode(row)
// Now that we have fetched the values we need, we could stop
// there. But let's make sure we fully consume the cursor
// anyway, until SQLITE_DONE. This is necessary, for example,
// for upserts in tables that are synchronized with an
// FTS5 table.
// See <https://github.com/groue/GRDB.swift/issues/1390>
while try cursor.next() != nil { }
return (rowid, returned)
}
+1 -1
View File
@@ -163,7 +163,7 @@ final class Pool<T> {
/// Blocks until no element is used, and runs the `barrier` function before
/// any other element is dequeued.
func barrier<T>(execute barrier: () throws -> T) rethrows -> T {
func barrier<R>(execute barrier: () throws -> R) rethrows -> R {
try barrierQueue.sync(flags: [.barrier]) {
itemsGroup.wait()
return try barrier()
@@ -101,6 +101,19 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
}
}
/// The fetching state for observation of constant regions.
enum FetchingState {
/// No need to fetch.
case idle
/// Waiting for a fetched value.
case fetching
/// Waiting for a fetched value, and for a subsequent fetch after
/// that, because a change has been detected as we were fetching.
case fetchingAndNeedsFetch
}
/// Ability to notify observation events
private struct NotificationCallbacks {
let events: ValueObservationEvents
@@ -132,6 +145,9 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
/// Ability to notify observation events, protected by `lock`.
private var notificationCallbacks: NotificationCallbacks?
/// The fetching state for observation of constant regions.
@LockedBox private var fetchingState = FetchingState.idle
/// Support for `TransactionObserver`, protected by the serialized writer
/// dispatch queue.
private var observationState = ObservationState.notObserving
@@ -272,8 +288,18 @@ extension ValueConcurrentObserver {
// We perform the initial read from a long-lived WAL snapshot
// transaction, because it is a handy way to keep a read transaction
// open until we grab a write access, and compare the database versions.
let walSnapshotTransaction = try databaseAccess.dbPool.walSnapshotTransaction()
let (fetchedValue, initialRegion) = try walSnapshotTransaction.read { db -> (Reducer.Fetched, DatabaseRegion) in
let initialFetchTransaction: WALSnapshotTransaction
do {
initialFetchTransaction = try databaseAccess.dbPool.walSnapshotTransaction()
} catch DatabaseError.SQLITE_ERROR {
// We can't create a WAL snapshot. The WAL file is probably
// missing, or is truncated. Let's degrade the observation
// by not using any snapshot.
// For more information, see <https://github.com/groue/GRDB.swift/issues/1383>
return try syncStartWithoutWALSnapshot(from: databaseAccess)
}
let (fetchedValue, initialRegion): (Reducer.Fetched, DatabaseRegion) = try initialFetchTransaction.read { db in
switch trackingMode {
case let .constantRegion(regions):
let fetchedValue = try databaseAccess.fetch(db)
@@ -299,7 +325,7 @@ extension ValueConcurrentObserver {
// Start observation
asyncStartObservation(
from: databaseAccess,
walSnapshotTransaction: walSnapshotTransaction,
initialFetchTransaction: initialFetchTransaction,
initialRegion: initialRegion)
return initialValue
@@ -318,15 +344,16 @@ extension ValueConcurrentObserver {
// transaction, because it is a handy way to keep a read transaction
// open until we grab a write access, and compare the database versions.
databaseAccess.dbPool.asyncWALSnapshotTransaction { result in
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
let (isNotifying, databaseAccess) = self.lock.synchronized {
(self.notificationCallbacks != nil, self.databaseAccess)
}
guard isNotifying, let databaseAccess else { return /* Cancelled */ }
do {
// Fetch
let walSnapshotTransaction = try result.get()
let initialFetchTransaction = try result.get()
// Second async jump because that's how
// `DatabasePool.asyncWALSnapshotTransaction` has to be used.
walSnapshotTransaction.asyncRead { db in
initialFetchTransaction.asyncRead { db in
do {
let fetchedValue: Reducer.Fetched
let initialRegion: DatabaseRegion
@@ -369,12 +396,18 @@ extension ValueConcurrentObserver {
// Start observation
self.asyncStartObservation(
from: databaseAccess,
walSnapshotTransaction: walSnapshotTransaction,
initialFetchTransaction: initialFetchTransaction,
initialRegion: initialRegion)
} catch {
self.notifyError(error)
}
}
} catch DatabaseError.SQLITE_ERROR {
// We can't create a WAL snapshot. The WAL file is probably
// missing, or is truncated. Let's degrade the observation
// by not using any snapshot.
// For more information, see <https://github.com/groue/GRDB.swift/issues/1383>
self.asyncStartWithoutWALSnapshot(from: databaseAccess)
} catch {
self.notifyError(error)
}
@@ -383,9 +416,26 @@ extension ValueConcurrentObserver {
private func asyncStartObservation(
from databaseAccess: DatabaseAccess,
walSnapshotTransaction: WALSnapshotTransaction,
initialFetchTransaction: WALSnapshotTransaction,
initialRegion: DatabaseRegion)
{
// We'll start the observation when we can access the writer
// connection. Until then, maybe the database has been modified
// since the initial fetch: we'll then need to notify a fresh value.
//
// To know if the database has been modified between the initial
// fetch and the writer access, we'll compare WAL snapshots.
//
// WAL snapshots can only be compared if the database is not
// checkpointed. That's why we'll keep `initialFetchTransaction`
// alive until the comparison is done.
//
// However, we want to release `initialFetchTransaction` as soon as
// possible, so that the reader connection it holds becomes
// available for other reads. It will be released when this optional
// is set to nil:
var initialFetchTransaction: WALSnapshotTransaction? = initialFetchTransaction
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
let events = self.lock.synchronized { self.notificationCallbacks?.events }
guard let events else { return /* Cancelled */ }
@@ -393,21 +443,22 @@ extension ValueConcurrentObserver {
do {
var observedRegion = initialRegion
// Transaction is needed for comparing version snapshots
try writerDB.isolated(readOnly: true) {
// Keep walSnapshotTransaction alive until we have
// compared database versions. `WALSnapshot` alone is
// not able to prevent database checkpointing, and keep
// snapshots comparable.
let isModified = withExtendedLifetime(walSnapshotTransaction) {
guard let currentWALSnapshot = try? WALSnapshot(writerDB) else {
return true
}
let ordering = walSnapshotTransaction.walSnapshot.compare(currentWALSnapshot)
// Was the database modified since the initial fetch?
let isModified: Bool
if let currentWALSnapshot = try? WALSnapshot(writerDB) {
let ordering = initialFetchTransaction!.walSnapshot.compare(currentWALSnapshot)
assert(ordering <= 0, "Unexpected snapshot ordering")
return ordering < 0
isModified = ordering < 0
} else {
// Can't compare: assume the database was modified.
isModified = true
}
// Comparison done: end the WAL snapshot transaction
// and release its reader connection.
initialFetchTransaction = nil
if isModified {
events.databaseDidChange?()
@@ -469,11 +520,22 @@ extension ValueConcurrentObserver {
}
}
#else
extension ValueConcurrentObserver {
private func syncStart(from databaseAccess: DatabaseAccess) throws -> Reducer.Value {
try syncStartWithoutWALSnapshot(from: databaseAccess)
}
private func asyncStart(from databaseAccess: DatabaseAccess) {
asyncStartWithoutWALSnapshot(from: databaseAccess)
}
}
#endif
extension ValueConcurrentObserver {
/// Synchronously starts the observation, and returns the initial value.
///
/// Unlike `asyncStart()`, this method does not notify the initial value or error.
private func syncStart(from databaseAccess: DatabaseAccess) throws -> Reducer.Value {
/// Unlike `asyncStartWithoutWALSnapshot()`, this method does not notify the initial value or error.
private func syncStartWithoutWALSnapshot(from databaseAccess: DatabaseAccess) throws -> Reducer.Value {
// Start from a read access. The whole point of using a DatabasePool
// for observing the database is to be able to fetch the initial value
// without having to wait for an eventual long-running write
@@ -502,7 +564,7 @@ extension ValueConcurrentObserver {
}
// Start observation
asyncStartObservation(
asyncStartObservationWithoutWALSnapshot(
from: databaseAccess,
initialRegion: initialRegion)
@@ -511,8 +573,8 @@ extension ValueConcurrentObserver {
/// Asynchronously starts the observation
///
/// Unlike `syncStart()`, this method does notify the initial value or error.
private func asyncStart(from databaseAccess: DatabaseAccess) {
/// Unlike `syncStartWithoutWALSnapshot()`, this method does notify the initial value or error.
private func asyncStartWithoutWALSnapshot(from databaseAccess: DatabaseAccess) {
// Start from a read access. The whole point of using a DatabasePool
// for observing the database is to be able to fetch the initial value
// without having to wait for an eventual long-running write
@@ -562,7 +624,7 @@ extension ValueConcurrentObserver {
}
// Start observation
self.asyncStartObservation(
self.asyncStartObservationWithoutWALSnapshot(
from: databaseAccess,
initialRegion: initialRegion)
} catch {
@@ -571,7 +633,7 @@ extension ValueConcurrentObserver {
}
}
private func asyncStartObservation(
private func asyncStartObservationWithoutWALSnapshot(
from databaseAccess: DatabaseAccess,
initialRegion: DatabaseRegion)
{
@@ -636,7 +698,6 @@ extension ValueConcurrentObserver {
}
}
}
#endif
// MARK: - Observing Database Transactions
@@ -675,13 +736,10 @@ extension ValueConcurrentObserver: TransactionObserver {
events.databaseDidChange?()
// Fetch
let future: DatabaseFuture<Reducer.Fetched>
switch trackingMode {
case .constantRegion, .constantRegionRecordedFromSelection:
future = databaseAccess.dbPool.concurrentRead { db in
try databaseAccess.fetch(db)
}
setNeedsFetching(databaseAccess: databaseAccess)
case .nonConstantRegionRecordedFromSelection:
// When the tracked region is not constant, we can't perform
// concurrent fetches of observed values.
@@ -706,26 +764,63 @@ extension ValueConcurrentObserver: TransactionObserver {
}
observationState.region = observedRegion
future = DatabaseFuture(.success(fetchedValue))
reduce(.success(fetchedValue))
} catch {
stopDatabaseObservation(writerDB)
notifyError(error)
return
}
}
// Reduce
//
// Reducing is performed asynchronously, so that we do not lock
// the writer dispatch queue longer than necessary.
//
// Important: reduceQueue.async guarantees the same ordering between
// transactions and notifications!
}
private func setNeedsFetching(databaseAccess: DatabaseAccess) {
$fetchingState.update { state in
switch state {
case .idle:
state = .fetching
asyncFetch(databaseAccess: databaseAccess)
case .fetching:
state = .fetchingAndNeedsFetch
case .fetchingAndNeedsFetch:
break
}
}
}
private func asyncFetch(databaseAccess: DatabaseAccess) {
databaseAccess.dbPool.asyncRead { [self] dbResult in
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
let fetchResult = dbResult.flatMap { db in
Result { try databaseAccess.fetch(db) }
}
self.reduce(fetchResult)
$fetchingState.update { state in
switch state {
case .idle:
// GRDB bug
preconditionFailure()
case .fetching:
state = .idle
case .fetchingAndNeedsFetch:
state = .fetching
asyncFetch(databaseAccess: databaseAccess)
}
}
}
}
private func reduce(_ fetchResult: Result<Reducer.Fetched, Error>) {
reduceQueue.async {
do {
// Wait until fetch has completed
// TODO: find a way to guarantee correct ordering without waiting for a semaphore and blocking a thread.
let fetchedValue = try future.wait()
let fetchedValue = try fetchResult.get()
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
+20 -17
View File
@@ -722,50 +722,53 @@ extension ValueObservation {
///
/// ```swift
/// // Tracks the full database
/// let observation = ValueObservation.tracking
/// let observation = ValueObservation.tracking(
/// region: .fullDatabase,
/// fetch: { db in ... })
///
/// // Tracks the full 'player' table
/// let observation = ValueObservation.tracking
/// let observation = ValueObservation.tracking(
/// region: Player.all(),
/// fetch: { db in ... })
///
/// // Tracks the full 'player' table
/// let observation = ValueObservation.tracking
/// let observation = ValueObservation.tracking(
/// region: Table("player"),
/// fetch: { db in ... })
///
/// // Tracks the row with id 42 in the 'player' table
/// let observation = ValueObservation.tracking
/// let observation = ValueObservation.tracking(
/// region: Player.filter(id: 42),
/// fetch: { db in ... })
///
/// // Tracks the 'score' column in the 'player' table
/// let observation = ValueObservation.tracking
/// let observation = ValueObservation.tracking(
/// region: Player.select(Column("score"),
/// fetch: { db in ... })
///
/// // Tracks the 'score' column in the 'player' table
/// let observation = ValueObservation.tracking
/// let observation = ValueObservation.tracking(
/// region: SQLRequest("SELECT score FROM player"),
/// fetch: { db in ... })
///
/// // Tracks both the 'player' and 'team' tables
/// let observation = ValueObservation.tracking
/// let observation = ValueObservation.tracking(
/// region: Player.all(), Team.all(),
/// fetch: { db in ... })
/// ```
///
/// - parameter region: A list of observed regions.
/// - parameter region: A region to observe.
/// - parameter otherRegions: A list of supplementary regions
/// to observe.
/// - parameter fetch: The closure that fetches the observed value.
public static func tracking<Value>(
region: any DatabaseRegionConvertible...,
region: any DatabaseRegionConvertible,
_ otherRegions: any DatabaseRegionConvertible...,
fetch: @escaping (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
tracking(regions: region, fetch: fetch)
tracking(regions: [region] + otherRegions, fetch: fetch)
}
/// Creates a `ValueObservation` that notifies the fetched value whenever
@@ -778,37 +781,37 @@ extension ValueObservation {
///
/// ```swift
/// // Tracks the full database
/// let observation = ValueObservation.tracking
/// let observation = ValueObservation.tracking(
/// regions: [.fullDatabase],
/// fetch: { db in ... })
///
/// // Tracks the full 'player' table
/// let observation = ValueObservation.tracking
/// let observation = ValueObservation.tracking(
/// regions: [Player.all()],
/// fetch: { db in ... })
///
/// // Tracks the full 'player' table
/// let observation = ValueObservation.tracking
/// let observation = ValueObservation.tracking(
/// regions: [Table("player")],
/// fetch: { db in ... })
///
/// // Tracks the row with id 42 in the 'player' table
/// let observation = ValueObservation.tracking
/// let observation = ValueObservation.tracking(
/// regions: [Player.filter(id: 42)],
/// fetch: { db in ... })
///
/// // Tracks the 'score' column in the 'player' table
/// let observation = ValueObservation.tracking
/// let observation = ValueObservation.tracking(
/// regions: [Player.select(Column("score")],
/// fetch: { db in ... })
///
/// // Tracks the 'score' column in the 'player' table
/// let observation = ValueObservation.tracking
/// let observation = ValueObservation.tracking(
/// regions: [SQLRequest("SELECT score FROM player")],
/// fetch: { db in ... })
///
/// // Tracks both the 'player' and 'team' tables
/// let observation = ValueObservation.tracking
/// let observation = ValueObservation.tracking(
/// regions: [Player.all(), Team.all()],
/// fetch: { db in ... })
/// ```
+4 -2
View File
@@ -50,6 +50,7 @@
562393751DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; };
56256EDE25D1BC07008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256EDD25D1BC07008C2BDD /* ForeignKey.swift */; };
562756461E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
562B58CE2A29BC0700E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */; };
562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
563082EA2430B6CD00C14A05 /* DatabaseCancellable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563082E82430B6CD00C14A05 /* DatabaseCancellable.swift */; };
@@ -470,6 +471,7 @@
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
56256EDD25D1BC07008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
@@ -522,7 +524,6 @@
56419A7F24A51614004967E1 /* Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = "<group>"; };
56419A8024A51614004967E1 /* Inverted.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inverted.swift; sourceTree = "<group>"; };
56419A8124A51614004967E1 /* PublisherExpectation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PublisherExpectation.swift; sourceTree = "<group>"; };
5643676E272EDF3700C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = "<group>"; };
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
@@ -1058,6 +1059,7 @@
563B06DB2185E04E00B38F35 /* ValueObservation */ = {
isa = PBXGroup;
children = (
562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */,
560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */,
563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */,
563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */,
@@ -1584,7 +1586,6 @@
DC37742D19C8CC90004FCF85 /* GRDB */,
F3BA7FED1CFB21F8003DC1BA /* GRDBCustomSQLite */,
DC10500F19C904DD00D8CA30 /* Tests */,
5643676E272EDF3700C718C7 /* Scripts */,
DC3773F419C8CBB3004FCF85 /* Products */,
);
indentWidth = 4;
@@ -1795,6 +1796,7 @@
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
562B58CE2A29BC0700E8C75D /* Issue1383.sqlite in Resources */,
569BBA43229066CB00478429 /* InflectionsTests.json in Resources */,
F3BA80CD1CFB2FDD003DC1BA /* Betty.jpeg in Resources */,
);
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

+16 -5
View File
@@ -52,11 +52,17 @@ MAX_IOS_DESTINATION := $(shell xcrun simctl list -j devices available | Scripts/
MIN_TVOS_DESTINATION := $(shell xcrun simctl list -j devices available | Scripts/destination.rb | grep tvOS | sort -n | head -1 | cut -wf 3 | sed 's/\(.*\)/"platform=tvOS Simulator,id=\1"/')
MAX_TVOS_DESTINATION := $(shell xcrun simctl list -j devices available | Scripts/destination.rb | grep tvOS | sort -rn | head -1 | cut -wf 3 | sed 's/\(.*\)/"platform=tvOS Simulator,id=\1"/')
# If xcpretty is available, use it for xcodebuild output
XCPRETTY =
XCPRETTY_PATH := $(shell command -v xcpretty 2> /dev/null)
ifdef XCPRETTY_PATH
XCPRETTY = | xcpretty -c
# If xcbeautify or xcpretty is available, use it for xcodebuild output, except in CI.
XCPRETTY =
ifeq ($(CI),true)
else
XCBEAUTIFY_PATH := $(shell command -v xcbeautify 2> /dev/null)
XCPRETTY_PATH := $(shell command -v xcpretty 2> /dev/null)
ifdef XCBEAUTIFY_PATH
XCPRETTY = | xcbeautify
else ifdef XCPRETTY_PATH
XCPRETTY = | xcpretty -c
endif
endif
# =====
@@ -128,6 +134,7 @@ test_framework_GRDBCustomSQLiteOSX: SQLiteCustom
$(XCODEBUILD) \
-project GRDBCustom.xcodeproj \
-scheme GRDBCustom \
-destination "platform=macOS" \
$(TEST_ACTIONS) \
$(XCPRETTY)
@@ -249,6 +256,7 @@ test_install_SPM_Project:
$(XCODEBUILD) \
-project Tests/SPM/PlainProject/Plain.xcodeproj \
-scheme Plain \
-destination "platform=macOS" \
-configuration Release \
clean build \
$(XCPRETTY)
@@ -266,6 +274,7 @@ test_install_SPM_macos_release:
$(XCODEBUILD) \
-project Tests/SPM/macos/macos.xcodeproj \
-scheme macos \
-destination "platform=macOS" \
-configuration Release \
clean build \
$(XCPRETTY)
@@ -283,6 +292,7 @@ test_install_customSQLite: SQLiteCustom
$(XCODEBUILD) \
-project Tests/CustomSQLite/CustomSQLite.xcodeproj \
-scheme CustomSQLite \
-destination "platform=macOS" \
-configuration Release \
clean build \
$(XCPRETTY)
@@ -357,6 +367,7 @@ test_performance:
$(XCODEBUILD) \
-project Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj \
-scheme GRDBOSXPerformanceComparisonTests \
-destination "platform=macOS" \
build-for-testing test-without-building
# Target that setups SQLite custom builds with extra compilation options.
+4
View File
@@ -10,6 +10,9 @@ var swiftSettings: [SwiftSetting] = [
var cSettings: [CSetting] = []
var dependencies: [PackageDescription.Package.Dependency] = []
// For Swift 5.8+
//swiftSettings.append(.enableUpcomingFeature("ExistentialAny"))
// Don't rely on those environment variables. They are ONLY testing conveniences:
// $ SQLITE_ENABLE_PREUPDATE_HOOK=1 make test_SPM
if ProcessInfo.processInfo.environment["SQLITE_ENABLE_PREUPDATE_HOOK"] == "1" {
@@ -70,6 +73,7 @@ let package = Package(
resources: [
.copy("GRDBTests/Betty.jpeg"),
.copy("GRDBTests/InflectionsTests.json"),
.copy("GRDBTests/Issue1383.sqlite"),
],
cSettings: cSettings,
swiftSettings: swiftSettings)
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff. Show more