mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-05 05:18:44 +00:00
Compare commits
32
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
639fa9168d | ||
|
|
1c5017a108 | ||
|
|
9ca1f6644c | ||
|
|
3f3cfa5381 | ||
|
|
bde61b26ab | ||
|
|
0a5bef4c0e | ||
|
|
218774d39a | ||
|
|
a0a9cfca65 | ||
|
|
c8bb0a4799 | ||
|
|
f1ff7f2a2a | ||
|
|
725cccccab | ||
|
|
1525075cce | ||
|
|
7110a1fab3 | ||
|
|
de382d30b8 | ||
|
|
3521030e13 | ||
|
|
eeacf93772 | ||
|
|
000aaa8698 | ||
|
|
77b85bed25 | ||
|
|
bb8323b91d | ||
|
|
d804b5ed9c | ||
|
|
2af60cb324 | ||
|
|
0434567f30 | ||
|
|
155a16bef8 | ||
|
|
2ad1f37d2b | ||
|
|
32642d566b | ||
|
|
1f4d5ac61a | ||
|
|
87fdd9a66f | ||
|
|
79d82337b2 | ||
|
|
fab4638fc9 | ||
|
|
a49fd85627 | ||
|
|
ac8c4aea63 | ||
|
|
5413dcfeeb |
No files matched your search
+15
-1
@@ -7,6 +7,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 6.x Releases
|
||||
|
||||
- `6.27.x` Releases - [6.27.0](#6270)
|
||||
- `6.26.x` Releases - [6.26.0](#6260)
|
||||
- `6.25.x` Releases - [6.25.0](#6250)
|
||||
- `6.24.x` Releases - [6.24.0](#6240) - [6.24.1](#6241) - [6.24.2](#6242)
|
||||
- `6.23.x` Releases - [6.23.0](#6230)
|
||||
@@ -123,12 +125,24 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## Next Release
|
||||
## 6.27.0
|
||||
|
||||
Released April 21, 2024
|
||||
|
||||
- **Fixed**: [#1533](https://github.com/groue/GRDB.swift/pull/1533) by [@groue](https://github.com/groue): Fix a bug in Decodable support
|
||||
- **Documentation Update**: [#1534](https://github.com/groue/GRDB.swift/pull/1534) The [Single-Row Tables](Documentation/SingleRowTables.md) guide was updated with guidance about default configuration values.
|
||||
- **Documentation Update**: [#1535](https://github.com/groue/GRDB.swift/pull/1535) The [ValueObservation Scheduling](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Scheduling) documentation chapter explains the default behavior of `ValueObservation` fetches, and explains how to make sure they are never performed on the main thread.
|
||||
|
||||
## 6.26.0
|
||||
|
||||
Released March 23, 2024
|
||||
|
||||
- **New**: [#1503](https://github.com/groue/GRDB.swift/pull/1503) by [@simba909](https://github.com/simba909): Conform Database.ColumnType to Sendable
|
||||
- **New**: [#1510](https://github.com/groue/GRDB.swift/pull/1510) by [@groue](https://github.com/groue): Add Sendable conformances and unavailabilities
|
||||
- **New**: [#1511](https://github.com/groue/GRDB.swift/pull/1511) by [@groue](https://github.com/groue): Database schema dump
|
||||
- **New**: [#1515](https://github.com/groue/GRDB.swift/pull/1515) by [@groue](https://github.com/groue): Support for the CAST SQLite function
|
||||
- **Fixed**: [#1508](https://github.com/groue/GRDB.swift/pull/1508) by [@groue](https://github.com/groue): Fix ValueObservation mishandling of database schema modification
|
||||
- **Fixed**: [#1512](https://github.com/groue/GRDB.swift/issues/1512): Decoding errors are now correctly reported when decoding NULL into a non-optional property of type `Data` or `Date`.
|
||||
|
||||
## 6.25.0
|
||||
|
||||
|
||||
@@ -2661,7 +2661,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0)
|
||||
```
|
||||
|
||||
- SQL functions `ABS` and `LENGTH` are available as the `abs` and `length` Swift functions:
|
||||
- SQL functions `ABS`, `CAST`, and `LENGTH` are available as the `abs`, `cast`, and `length` Swift functions:
|
||||
|
||||
<details>
|
||||
<summary>SQL</summary>
|
||||
|
||||
@@ -13,8 +13,9 @@ 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 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 [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
- How to perform `async` database accesses.
|
||||
- How to feed SwiftUI previews with a transient database.
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '6.25.0'
|
||||
s.version = '6.27.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -276,6 +276,7 @@
|
||||
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */; };
|
||||
56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */; };
|
||||
56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; };
|
||||
56B6AB062BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6AB052BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift */; };
|
||||
56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; };
|
||||
56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
|
||||
56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
|
||||
@@ -770,6 +771,7 @@
|
||||
56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionDateTests.swift; sourceTree = "<group>"; };
|
||||
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = "<group>"; };
|
||||
56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = "<group>"; };
|
||||
56B6AB052BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SingletonUserDefaultsTest.swift; sourceTree = "<group>"; };
|
||||
56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = "<group>"; };
|
||||
56B7EE822863781300C0525F /* WALSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshot.swift; sourceTree = "<group>"; };
|
||||
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1552,6 +1554,7 @@
|
||||
children = (
|
||||
564E73DE203D50B9000C443C /* JoinSupportTests.swift */,
|
||||
5616B4FA28B5F5220052017E /* SingletonRecordTest.swift */,
|
||||
56B6AB052BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift */,
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */,
|
||||
560B3FA41C19DFF800C58EC7 /* PersistableRecord */,
|
||||
56176C9E1EACEDF9000F3F2B /* Record */,
|
||||
@@ -2086,6 +2089,7 @@
|
||||
562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */,
|
||||
56677C0D241CD0D00050755D /* ValueObservationRecorder.swift in Sources */,
|
||||
5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
|
||||
56B6AB062BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift in Sources */,
|
||||
563B5336267E2F90009549B5 /* TableTests.swift in Sources */,
|
||||
56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */,
|
||||
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
|
||||
@@ -115,6 +115,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``trace(options:_:)``
|
||||
/// - ``CheckpointMode``
|
||||
/// - ``DatabaseBackupProgress``
|
||||
/// - ``StorageClass``
|
||||
/// - ``TraceEvent``
|
||||
/// - ``TracingOptions``
|
||||
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
@@ -819,6 +820,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Reports the database region to ``ValueObservation``.
|
||||
///
|
||||
/// Calling this method does not fetch any database values. It just
|
||||
/// helps optimizing `ValueObservation`. See
|
||||
/// ``ValueObservation/trackingConstantRegion(_:)`` for more
|
||||
/// information, and some examples of usage.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -830,12 +836,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See ``ValueObservation/trackingConstantRegion(_:)`` for some examples
|
||||
/// of region reporting.
|
||||
///
|
||||
/// This method has no effect on a ``ValueObservation`` created with an
|
||||
/// explicit list of tracked regions. In the example below, only the
|
||||
/// `player` table is tracked:
|
||||
/// This method has no effect on a `ValueObservation` created with
|
||||
/// ``ValueObservation/tracking(regions:fetch:)``. In the example below,
|
||||
/// only the `player` table is tracked:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Observes the 'player' table only
|
||||
@@ -2005,6 +2008,32 @@ extension Database {
|
||||
/// An error log function that takes an error code and message.
|
||||
public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void
|
||||
|
||||
/// An SQLite storage class.
|
||||
///
|
||||
/// For more information, see
|
||||
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
|
||||
public struct StorageClass: RawRepresentable, Hashable, Sendable {
|
||||
/// The SQL for the storage class (`"INTEGER"`, `"REAL"`, etc.)
|
||||
public let rawValue: String
|
||||
|
||||
/// Creates an SQL storage class.
|
||||
public init(rawValue: String) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// The `INTEGER` storage class.
|
||||
public static let integer = StorageClass(rawValue: "INTEGER")
|
||||
|
||||
/// The `REAL` storage class.
|
||||
public static let real = StorageClass(rawValue: "REAL")
|
||||
|
||||
/// The `TEXT` storage class.
|
||||
public static let text = StorageClass(rawValue: "TEXT")
|
||||
|
||||
/// The `BLOB` storage class.
|
||||
public static let blob = StorageClass(rawValue: "BLOB")
|
||||
}
|
||||
|
||||
/// An option for the SQLite tracing feature.
|
||||
///
|
||||
/// You use `TracingOptions` with the `Database`
|
||||
|
||||
@@ -80,6 +80,8 @@ By default, `ValueObservation` notifies a fresh value whenever any component of
|
||||
|
||||
By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main dispatch queue, asynchronously. This can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
|
||||
|
||||
By default, `ValueObservation` fetches a fresh value immediately after a change is committed in the database. In particular, modifying the database on the main thread triggers a fetch on the main thread as well. This behavior can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
|
||||
|
||||
`ValueObservation` may coalesce subsequent changes into a single notification.
|
||||
|
||||
`ValueObservation` may notify consecutive identical values. You can filter out the undesired duplicates with the ``removeDuplicates()`` method.
|
||||
@@ -117,16 +119,45 @@ It is very useful in graphic applications, because you can configure views right
|
||||
The `immediate` scheduling requires that the observation starts from the main dispatch queue (a fatal error is raised otherwise):
|
||||
|
||||
```swift
|
||||
let cancellable = observation.start(in: dbQueue, scheduling: .immediate) { error in
|
||||
// Called on the main dispatch queue
|
||||
} onChange: { value in
|
||||
// Called on the main dispatch queue
|
||||
print("Fresh value", value)
|
||||
}
|
||||
// Immediate scheduling notifies
|
||||
// the initial value right on subscription.
|
||||
let cancellable = observation
|
||||
.start(in: dbQueue, scheduling: .immediate) { error in
|
||||
// Called on the main dispatch queue
|
||||
} onChange: { value in
|
||||
// Called on the main dispatch queue
|
||||
print("Fresh value", value)
|
||||
}
|
||||
// <- Here "Fresh value" has already been printed.
|
||||
```
|
||||
|
||||
The other built-in scheduler ``ValueObservationScheduler/async(onQueue:)`` asynchronously schedules values and errors on the dispatch queue of your choice.
|
||||
The other built-in scheduler ``ValueObservationScheduler/async(onQueue:)`` asynchronously schedules values and errors on the dispatch queue of your choice. Make sure you provide a serial queue, because a concurrent one such as `DispachQueue.global(qos: .default)` would mess with the ordering of fresh value notifications:
|
||||
|
||||
```swift
|
||||
// Async scheduling notifies all values
|
||||
// on the specified dispatch queue.
|
||||
let myQueue: DispatchQueue
|
||||
let cancellable = observation
|
||||
.start(in: dbQueue, scheduling: .async(myQueue)) { error in
|
||||
// Called asynchronously on myQueue
|
||||
} onChange: { value in
|
||||
// Called asynchronously on myQueue
|
||||
print("Fresh value", value)
|
||||
}
|
||||
```
|
||||
|
||||
As described above, the `scheduling` argument controls the execution of the change and error callbacks. You also have some control on the execution of the database fetch:
|
||||
|
||||
- With the `.immediate` scheduling, the initial fetch is always performed synchronously, on the main thread, when the observation starts, so that the initial value can be notified immediately.
|
||||
|
||||
- With the default `.async` scheduling, the initial fetch is always performed asynchronouly. It never blocks the main thread.
|
||||
|
||||
- By default, fresh values are fetched immediately after the database was changed. In particular, modifying the database on the main thread triggers a fetch on the main thread as well.
|
||||
|
||||
To change this behavior, and guarantee that fresh values are never fetched from the main thread, you need a ``DatabasePool`` and an optimized observation created with the ``tracking(regions:fetch:)`` or ``trackingConstantRegion(_:)`` methods. Make sure you read the documentation of those methods, or you might write an observation that misses some database changes.
|
||||
|
||||
It is possible to use a ``DatabasePool`` in the application, and an in-memory ``DatabaseQueue`` in tests and Xcode previews, with the common protocol ``DatabaseWriter``.
|
||||
|
||||
|
||||
## ValueObservation Sharing
|
||||
|
||||
@@ -237,7 +268,7 @@ When needed, you can help GRDB optimize observations and reduce database content
|
||||
>
|
||||
> The `map` operator performs its job without blocking database accesses, and without blocking the main thread.
|
||||
|
||||
> 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.
|
||||
> Tip: When the observation tracks a constant database region, create an optimized observation with the ``tracking(regions:fetch:)`` or ``trackingConstantRegion(_:)`` methods. Make sure you read the documentation of those methods, or you might write an observation that misses some database changes.
|
||||
|
||||
**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).
|
||||
|
||||
|
||||
@@ -147,5 +147,4 @@ The `->` and `->>` SQL operators are available on the ``SQLJSONExpressible`` pro
|
||||
|
||||
### Validate JSON values at the SQL level
|
||||
|
||||
- ``Database/jsonErrorPosition(_:)``
|
||||
- ``Database/jsonIsValid(_:)``
|
||||
@@ -8,9 +8,11 @@ Database tables that contain a single row can store configuration values, user p
|
||||
|
||||
They are a suitable alternative to `UserDefaults` in some applications, especially when configuration refers to values found in other database tables, and database integrity is a concern.
|
||||
|
||||
An alternative way to store such configuration is a table of key-value pairs: two columns, and one row for each configuration value. This technique works, but it has a few drawbacks: you will have to deal with the various types of configuration values (strings, integers, dates, etc), and you won't be able to define foreign keys. This is why we won't explore key-value tables.
|
||||
A possible way to store such configuration is a table of key-value pairs: two columns, and one row for each configuration value. This technique works, but it has a few drawbacks: one has to deal with the various types of configuration values (strings, integers, dates, etc), and it is not possible to define foreign keys. This is why we won't explore key-value tables.
|
||||
|
||||
This guide helps implementing a single-row table with GRDB, with recommendations on the database schema, migrations, and the design of a matching record type.
|
||||
In this guide, we'll implement a single-row table, with recommendations on the database schema, migrations, and the design of a Swift API for accessing the configuration values. The schema will define one column for each configuration value, because we aim at being able to deal with foreign keys and references to other tables. You may prefer storing configuration values in a single JSON column. In this case, take inspiration from this guide, as well as <doc:JSON>.
|
||||
|
||||
We will also aim at providing a default value for a given configuration, even when it is not stored on disk yet. This is a feature similar to [`UserDefaults.register(defaults:)`](https://developer.apple.com/documentation/foundation/userdefaults/1417065-register).
|
||||
|
||||
## The Single-Row Table
|
||||
|
||||
@@ -20,67 +22,47 @@ We want to instruct SQLite that our table must never contain more than one row.
|
||||
|
||||
SQLite is not able to guarantee that the table is never empty, so we have to deal with two cases: either the table is empty, or it contains one row.
|
||||
|
||||
Those two cases can create a nagging question for the application. By default, inserts fail when the row already exists, and updates fail when the table is empty. In order to avoid those errors, we will have the app deal with updates in the <doc:SingleRowTables#The-Single-Row-Record> section below. Right now, we instruct SQLite to just replace the eventual existing row in case of conflicting inserts:
|
||||
Those two cases can create a nagging question for the application. By default, inserts fail when the row already exists, and updates fail when the table is empty. In order to avoid those errors, we will have the app deal with updates in the <doc:SingleRowTables#The-Single-Row-Record> section below. Right now, we instruct SQLite to just replace the eventual existing row in case of conflicting inserts.
|
||||
|
||||
```swift
|
||||
// CREATE TABLE appConfiguration (
|
||||
// id INTEGER PRIMARY KEY ON CONFLICT REPLACE CHECK (id = 1),
|
||||
// flag BOOLEAN NOT NULL,
|
||||
// ...)
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee: have inserts replace the existing row
|
||||
t.primaryKey("id", .integer, onConflict: .replace)
|
||||
// Make sure the id column is always 1
|
||||
.check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
```
|
||||
|
||||
When you use <doc:Migrations>, you may wonder if it is a good idea or not to perform an initial insert just after the table is created. Well, this is not recommended:
|
||||
|
||||
```swift
|
||||
// NOT RECOMMENDED
|
||||
migrator.registerMigration("appConfiguration") { db in
|
||||
// CREATE TABLE appConfiguration (
|
||||
// id INTEGER PRIMARY KEY ON CONFLICT REPLACE CHECK (id = 1),
|
||||
// storedFlag BOOLEAN,
|
||||
// ...)
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// The single row guarantee
|
||||
t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// Define sensible defaults for each column
|
||||
t.column("flag", .boolean).notNull()
|
||||
.defaults(to: false)
|
||||
// ... other columns
|
||||
}
|
||||
|
||||
// Populate the table
|
||||
try db.execute(sql: "INSERT INTO appConfiguration DEFAULT VALUES")
|
||||
}
|
||||
```
|
||||
|
||||
It is not a good idea to populate the table in a migration, for two reasons:
|
||||
|
||||
1. This migration is not a hard guarantee that the table will never be empty. As a consequence, this won't prevent the application code from dealing with the possibility of a missing row. On top of that, this application code may not use the same default values as the SQLite schema, with unclear consequences.
|
||||
|
||||
2. Migrations that have been deployed on the users' devices should never change (see <doc:Migrations#Good-Practices-for-Defining-Migrations>). Inserting an initial row in a migration makes it difficult for the application to adjust the sensible default values in a future version.
|
||||
|
||||
The recommended migration creates the table, nothing more:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
migrator.registerMigration("appConfiguration") { db in
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// The single row guarantee
|
||||
t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 }
|
||||
// Single row guarantee: have inserts replace the existing row,
|
||||
// and make sure the id column is always 1.
|
||||
t.primaryKey("id", .integer, onConflict: .replace)
|
||||
.check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
t.column("storedFlag", .boolean)
|
||||
// ... other columns
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note how the database table is defined in a migration. That's because most apps evolve, and need to add other configuration columns eventually. See <doc:Migrations> for more information.
|
||||
|
||||
We have defined a `storedFlag` column that can be NULL. That may be surprising, because optional booleans are usually a bad idea! But we can deal with this NULL at runtime, and nullable columns have a few advantages:
|
||||
|
||||
- NULL means that the application user had not made a choice yet. When `storedFlag` is NULL, the app can use a default value, such as `true`.
|
||||
- As application evolves, application will need to add new configuration columns. It is not always possible to provide a sensible default value for these new columns, at the moment the table is modified. On the other side, it is generally possible to deal with those NULL values at runtime.
|
||||
|
||||
Despite those arguments, some apps absolutely require a value. In this case, don't weaken the application logic and make sure the database can't store a NULL value:
|
||||
|
||||
```swift
|
||||
// DO NOT hesitate requiring NOT NULL columns when the app requires it.
|
||||
migrator.registerMigration("appConfiguration") { db in
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
t.column("flag", .boolean).notNull() // required
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## The Single-Row Record
|
||||
|
||||
@@ -91,7 +73,37 @@ struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// The configuration properties
|
||||
// The stored properties
|
||||
private var storedFlag: Bool?
|
||||
// ... other properties
|
||||
}
|
||||
```
|
||||
|
||||
The `storedFlag` property is private, because we want to expose a nice `flag` property that has a default value when `storedFlag` is nil:
|
||||
|
||||
```swift
|
||||
// Support for default values
|
||||
extension AppConfiguration {
|
||||
var flag: Bool {
|
||||
get { storedFlag ?? true /* the default value */ }
|
||||
set { storedFlag = newValue }
|
||||
}
|
||||
|
||||
mutating func resetFlag() {
|
||||
storedFlag = nil
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This ceremony is not needed when the column can not be null:
|
||||
|
||||
```swift
|
||||
// The simplified setup for non-nullable columns
|
||||
struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// The stored properties
|
||||
var flag: Bool
|
||||
// ... other properties
|
||||
}
|
||||
@@ -102,7 +114,7 @@ In case the database table would be empty, we need a default configuration:
|
||||
```swift
|
||||
extension AppConfiguration {
|
||||
/// The default configuration
|
||||
static let `default` = AppConfiguration(flag: false)
|
||||
static let `default` = AppConfiguration(flag: nil)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -129,7 +141,7 @@ The standard GRDB method ``FetchableRecord/fetchOne(_:)`` returns an optional wh
|
||||
```swift
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func fetch(_ db: Database) throws -> AppConfiguration {
|
||||
static func find(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
@@ -140,7 +152,7 @@ And that's it! Now we can use our singleton record:
|
||||
```swift
|
||||
// READ
|
||||
let config = try dbQueue.read { db in
|
||||
try AppConfiguration.fetch(db)
|
||||
try AppConfiguration.find(db)
|
||||
}
|
||||
if config.flag {
|
||||
// ...
|
||||
@@ -148,17 +160,19 @@ if config.flag {
|
||||
|
||||
// WRITE
|
||||
try dbQueue.write { db in
|
||||
// Saves a new config in the database
|
||||
var config = try AppConfiguration.fetch(db)
|
||||
// Update the config in the database
|
||||
var config = try AppConfiguration.find(db)
|
||||
try config.updateChanges(db) {
|
||||
$0.flag = true
|
||||
}
|
||||
|
||||
// Other possible ways to save the config:
|
||||
try config.save(db)
|
||||
try config.update(db)
|
||||
try config.insert(db)
|
||||
try config.upsert(db)
|
||||
var config = try AppConfiguration.find(db)
|
||||
config.flag = true
|
||||
try config.save(db) // all the same
|
||||
try config.update(db) // all the same
|
||||
try config.insert(db) // all the same
|
||||
try config.upsert(db) // all the same
|
||||
}
|
||||
```
|
||||
|
||||
@@ -172,11 +186,13 @@ We all love to copy and paste, don't we? Just customize the template code below:
|
||||
```swift
|
||||
// Table creation
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// The single row guarantee
|
||||
t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 }
|
||||
// Single row guarantee: have inserts replace the existing row,
|
||||
// and make sure the id column is always 1.
|
||||
t.primaryKey("id", .integer, onConflict: .replace)
|
||||
.check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
t.column("storedFlag", .boolean)
|
||||
// ... other columns
|
||||
}
|
||||
```
|
||||
@@ -192,14 +208,26 @@ struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// The configuration properties
|
||||
var flag: Bool
|
||||
// The stored properties
|
||||
private var storedFlag: Bool?
|
||||
// ... other properties
|
||||
}
|
||||
|
||||
// Support for default values
|
||||
extension AppConfiguration {
|
||||
var flag: Bool {
|
||||
get { storedFlag ?? true /* the default value */ }
|
||||
set { storedFlag = newValue }
|
||||
}
|
||||
|
||||
mutating func resetFlag() {
|
||||
storedFlag = nil
|
||||
}
|
||||
}
|
||||
|
||||
extension AppConfiguration {
|
||||
/// The default configuration
|
||||
static let `default` = AppConfiguration(flag: false, ...)
|
||||
static let `default` = AppConfiguration(storedFlag: nil)
|
||||
}
|
||||
|
||||
// Database Access
|
||||
@@ -214,7 +242,7 @@ extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func fetch(_ db: Database) throws -> AppConfiguration {
|
||||
static func find(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
|
||||
@@ -521,21 +521,6 @@ extension Database {
|
||||
.function("JSON_ARRAY_LENGTH", [value.sqlExpression, path.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_ERROR_POSITION` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_ERROR_POSITION(info)
|
||||
/// Database.jsonErrorPosition(Column("info"))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jerr>
|
||||
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
public static func jsonErrorPosition(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_ERROR_POSITION", [value.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_EXTRACT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -835,7 +835,7 @@ extension AssociationAggregate {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - IFNULL(...)
|
||||
// MARK: - Functions
|
||||
|
||||
extension AssociationAggregate {
|
||||
/// The `IFNULL` SQL function.
|
||||
@@ -854,8 +854,6 @@ extension AssociationAggregate {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ABS(...)
|
||||
|
||||
/// The `ABS` SQL function.
|
||||
public func abs<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
@@ -863,7 +861,18 @@ public func abs<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
|
||||
aggregate.map(abs)
|
||||
}
|
||||
|
||||
// MARK: - LENGTH(...)
|
||||
/// The `CAST` SQL function.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html#castexpr>
|
||||
public func cast<RowDecoder>(
|
||||
_ aggregate: AssociationAggregate<RowDecoder>,
|
||||
as storageClass: Database.StorageClass)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
aggregate
|
||||
.map { cast($0, as: storageClass) }
|
||||
.with { $0.key = aggregate.key } // Preserve key
|
||||
}
|
||||
|
||||
/// The `LENGTH` SQL function.
|
||||
public func length<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
|
||||
|
||||
@@ -90,6 +90,11 @@ public struct SQLExpression {
|
||||
/// A literal SQL expression
|
||||
case literal(SQL)
|
||||
|
||||
/// The `CAST(expr AS storage-class)` expression.
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_expr.html#castexpr>.
|
||||
indirect case cast(SQLExpression, Database.StorageClass)
|
||||
|
||||
/// The `BETWEEN` and `NOT BETWEEN` operators.
|
||||
///
|
||||
/// <expression> BETWEEN <lowerBound> AND <upperBound>
|
||||
@@ -224,6 +229,9 @@ public struct SQLExpression {
|
||||
case let .literal(sqlLiteral):
|
||||
return .literal(sqlLiteral.qualified(with: alias))
|
||||
|
||||
case let .cast(expression, storageClass):
|
||||
return .cast(expression.qualified(with: alias), storageClass)
|
||||
|
||||
case let .between(
|
||||
expression: expression,
|
||||
lowerBound: lowerBound,
|
||||
@@ -1092,6 +1100,13 @@ extension SQLExpression {
|
||||
self.init(impl: .isEmpty(expression, isNegated: isNegated))
|
||||
}
|
||||
|
||||
/// The `CAST(expr AS storage-class)` expression.
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_expr.html#castexpr>.
|
||||
static func cast(_ expression: SQLExpression, as storageClass: Database.StorageClass) -> Self {
|
||||
self.init(impl: .cast(expression, storageClass))
|
||||
}
|
||||
|
||||
// MARK: Deferred
|
||||
|
||||
// TODO: replace with something that can work for WITHOUT ROWID table with a multi-columns primary key.
|
||||
@@ -1269,6 +1284,9 @@ extension SQLExpression {
|
||||
}
|
||||
return resultSQL
|
||||
|
||||
case let .cast(expression, storageClass):
|
||||
return try "CAST(\(expression.sql(context, wrappedInParenthesis: false)) AS \(storageClass.rawValue))"
|
||||
|
||||
case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: isNegated):
|
||||
var resultSQL = try """
|
||||
\(expression.sql(context, wrappedInParenthesis: true)) \
|
||||
@@ -1822,6 +1840,9 @@ extension SQLExpression {
|
||||
let .associativeBinary(_, expressions):
|
||||
return expressions.allSatisfy(\.isConstantInRequest)
|
||||
|
||||
case let .cast(expression, _):
|
||||
return expression.isConstantInRequest
|
||||
|
||||
case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: _):
|
||||
return expression.isConstantInRequest
|
||||
&& lowerBound.isConstantInRequest
|
||||
|
||||
@@ -57,6 +57,20 @@ public func average(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
}
|
||||
#endif
|
||||
|
||||
/// The `CAST` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CAST(value AS REAL)
|
||||
/// cast(Column("value"), as: .real)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html#castexpr>
|
||||
public func cast(_ expression: some SQLSpecificExpressible, as storageClass: Database.StorageClass) -> SQLExpression {
|
||||
.cast(expression.sqlExpression, as: storageClass)
|
||||
}
|
||||
|
||||
/// The `COUNT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -147,6 +147,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
|
||||
lazy var allKeys: [Key] = {
|
||||
let row = decoder.row
|
||||
// TODO: test when _columnForKey is not nil
|
||||
var keys = _columnForKey.map { Set($0.keys) } ?? Set(row.columnNames)
|
||||
keys.formUnion(row.scopesTree.names)
|
||||
keys.formUnion(row.prefetchedRows.keys)
|
||||
@@ -174,15 +175,25 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
|
||||
func decodeNil(forKey key: Key) throws -> Bool {
|
||||
let row = decoder.row
|
||||
if let column = try? decodeColumn(forKey: key), row[column] != nil {
|
||||
return false
|
||||
|
||||
// Column?
|
||||
if let column = try? decodeColumn(forKey: key),
|
||||
let index = row.index(forColumn: column)
|
||||
{
|
||||
return row.hasNull(atIndex: index)
|
||||
}
|
||||
if row.scopesTree[key.stringValue] != nil {
|
||||
return false
|
||||
|
||||
// Scope?
|
||||
if let scopedRow = row.scopesTree[key.stringValue] {
|
||||
return scopedRow.containsNonNullValue == false
|
||||
}
|
||||
|
||||
// Prefetched Rows?
|
||||
if row.prefetchedRows[key.stringValue] != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// Unknown key
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -376,7 +387,35 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key)
|
||||
throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey
|
||||
{
|
||||
fatalError("not implemented")
|
||||
let row = decoder.row
|
||||
|
||||
// Column?
|
||||
if let column = try? decodeColumn(forKey: key),
|
||||
row.index(forColumn: column) != nil
|
||||
{
|
||||
// We need a JSON container, but how do we create one?
|
||||
throw DecodingError.typeMismatch(
|
||||
KeyedDecodingContainer<NestedKey>.self,
|
||||
DecodingError.Context(
|
||||
codingPath: codingPath,
|
||||
debugDescription: "not implemented: building a nested JSON container for the column '\(column)'"))
|
||||
}
|
||||
|
||||
// Scope?
|
||||
if let scopedRow = row.scopesTree[key.stringValue] {
|
||||
return KeyedDecodingContainer(KeyedContainer<NestedKey>(decoder: _RowDecoder(
|
||||
row: scopedRow,
|
||||
codingPath: codingPath + [key],
|
||||
columnDecodingStrategy: decoder.columnDecodingStrategy)))
|
||||
}
|
||||
|
||||
// Don't look for prefetched rows: those need a unkeyed container.
|
||||
|
||||
throw DecodingError.typeMismatch(
|
||||
KeyedDecodingContainer<NestedKey>.self,
|
||||
DecodingError.Context(
|
||||
codingPath: codingPath,
|
||||
debugDescription: "No keyed container found for key '\(key)'"))
|
||||
}
|
||||
|
||||
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
|
||||
@@ -591,9 +630,19 @@ extension DatabaseDataDecodingStrategy {
|
||||
|
||||
fileprivate func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Data {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
let statementIndex = CInt(index)
|
||||
|
||||
if sqlite3_column_type(sqliteStatement, statementIndex) == SQLITE_NULL {
|
||||
throw RowDecodingError.valueMismatch(
|
||||
Data.self,
|
||||
sqliteStatement: sqliteStatement,
|
||||
index: statementIndex,
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
return try decode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: CInt(index),
|
||||
atUncheckedIndex: statementIndex,
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
} else {
|
||||
return try decode(
|
||||
@@ -690,6 +739,16 @@ extension DatabaseDateDecodingStrategy {
|
||||
|
||||
fileprivate func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Date {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
let statementIndex = CInt(index)
|
||||
|
||||
if sqlite3_column_type(sqliteStatement, statementIndex) == SQLITE_NULL {
|
||||
throw RowDecodingError.valueMismatch(
|
||||
Date.self,
|
||||
sqliteStatement: sqliteStatement,
|
||||
index: statementIndex,
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
return try decode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: CInt(index),
|
||||
|
||||
@@ -595,12 +595,18 @@ extension ValueObservation {
|
||||
/// Creates an optimized `ValueObservation` that notifies the fetched value
|
||||
/// whenever it changes.
|
||||
///
|
||||
/// The optimization reduces database contention by not blocking database
|
||||
/// writes when the fresh value is fetched.
|
||||
/// Unlike observations created with ``tracking(_:)``, the returned
|
||||
/// observation can reduce database contention, by not blocking
|
||||
/// database writes when fresh values are fetched. It can also avoid
|
||||
/// fetching fresh values from the main thread, after the database was
|
||||
/// modified on the main thread.
|
||||
///
|
||||
/// The optimization is only applied when the observation is started from a
|
||||
/// ``DatabasePool``. You can start such an observation from a
|
||||
/// ``DatabaseQueue``, but the optimization will not be applied.
|
||||
/// Those scheduling optimizations are only applied when the observation
|
||||
/// is started from a ``DatabasePool``. You can start such an
|
||||
/// observation from a ``DatabaseQueue``, but the optimizations will not
|
||||
/// be applied. The notified values will be the same, though. This makes
|
||||
/// it possible to use a pool in the main application, and an in-memory
|
||||
/// queue in tests and Xcode previews.
|
||||
///
|
||||
/// **Precondition**: The `fetch` function must perform requests that fetch
|
||||
/// from a single and constant database region. This region is made of
|
||||
@@ -623,7 +629,7 @@ extension ValueObservation {
|
||||
///
|
||||
/// // Tracks the 'score' column in the 'player' table
|
||||
/// let observation = ValueObservation.trackingConstantRegion { db -> Int? in
|
||||
/// try Player.select(max(Column("score"))).fetchOne(db)
|
||||
/// try Int.fetchOne(db, sql: "SELECT MAX(score) FROM player")
|
||||
/// }
|
||||
///
|
||||
/// // Tracks both the 'player' and 'team' tables
|
||||
@@ -634,73 +640,93 @@ extension ValueObservation {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Observations that do not track a constant region must not use this
|
||||
/// method. Use ``tracking(_:)`` instead, or else some changes will not
|
||||
/// be notified.
|
||||
/// **Observations that do not track a constant database region must not
|
||||
/// use this method, because some changes may not be notified to
|
||||
/// the application.**
|
||||
///
|
||||
/// For example, the observations below do not track a constant region, and
|
||||
/// must not be optimized:
|
||||
/// For example, the observations below do not track a constant region.
|
||||
/// They are correctly defined with ``tracking(_:)``, since
|
||||
/// `trackingConstantRegion(_:)` is unsuited:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Does not always track the same row in the player table.
|
||||
/// let observation = ValueObservation.tracking { db -> Player? in
|
||||
/// let pref = try Preference.fetchOne(db) ?? .default
|
||||
/// return try Player.fetchOne(db, id: pref.favoritePlayerId)
|
||||
/// // Does not always track the same row in the 'player' table:
|
||||
/// let observation = ValueObservation.tracking { db -> Player in
|
||||
/// let config = try AppConfiguration.find(db)
|
||||
/// let playerId: Int64 = config.favoritePlayerId
|
||||
/// return try Player.find(db, id: playerId)
|
||||
/// }
|
||||
///
|
||||
/// // Does not always track the 'user' table.
|
||||
/// let observation = ValueObservation.tracking { db -> [User] in
|
||||
/// let pref = try Preference.fetchOne(db) ?? .default
|
||||
/// let playerIds: [Int64] = pref.favoritePlayerIds // may be empty
|
||||
/// // Does not always track the 'player' table, or not always the same
|
||||
/// // rows in the 'player' table:
|
||||
/// let observation = ValueObservation.tracking { db -> [Player] in
|
||||
/// let config = try AppConfiguration.find(db)
|
||||
/// let playerIds: [Int64] = config.favoritePlayerIds
|
||||
/// // Not only playerIds can change, but when it is empty,
|
||||
/// // the player table is not tracked at all.
|
||||
/// return try Player.fetchAll(db, ids: playerIds)
|
||||
/// }
|
||||
///
|
||||
/// // Sometimes tracks the 'food' table, and sometimes the 'beverage' table.
|
||||
/// let observation = ValueObservation.tracking { db -> Int in
|
||||
/// let pref = try Preference.fetchOne(db) ?? .default
|
||||
/// switch pref.selection {
|
||||
/// case .food: return try Food.fetchCount(db)
|
||||
/// case .beverage: return try Beverage.fetchCount(db)
|
||||
/// let config = try AppConfiguration.find(db)
|
||||
/// switch config.selection {
|
||||
/// case .food:
|
||||
/// return try Food.fetchCount(db)
|
||||
/// case .beverage:
|
||||
/// return try Beverage.fetchCount(db)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You can turn them into optimized observations of a constant region with
|
||||
/// the ``Database/registerAccess(to:)`` method:
|
||||
/// Since only observations of a constant region can achieve important
|
||||
/// scheduling optimizations (such as the guarantee that fresh values
|
||||
/// are never fetched from the main thread –
|
||||
/// see <doc:ValueObservation#ValueObservation-Scheduling>), you can
|
||||
/// always create one:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observation = ValueObservation.trackingConstantRegion { db -> Player? in
|
||||
/// // Track all players so that the observed region does not depend on
|
||||
/// // the rowid of the favorite player.
|
||||
/// try db.registerAccess(to: Player.all())
|
||||
/// - With ``tracking(regions:fetch:)``, you provide all tracked
|
||||
/// region(s) when the observation is created:
|
||||
///
|
||||
/// let pref = try Preference.fetchOne(db) ?? .default
|
||||
/// return try Player.fetchOne(db, id: pref.favoritePlayerId)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// // Optimized observation that explicitly tracks the
|
||||
/// // 'appConfiguration', 'food', and 'beverage' tables:
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// regions: [
|
||||
/// AppConfiguration.all(),
|
||||
/// Food.all(),
|
||||
/// Beverage.all(),
|
||||
/// ],
|
||||
/// fetch: { db -> Int in
|
||||
/// let config = try AppConfiguration.find(db)
|
||||
/// switch config.selection {
|
||||
/// case .food:
|
||||
/// return try Food.fetchCount(db)
|
||||
/// case .beverage:
|
||||
/// return try Beverage.fetchCount(db)
|
||||
/// }
|
||||
/// })
|
||||
/// ```
|
||||
///
|
||||
/// let observation = ValueObservation.trackingConstantRegion { db -> [User] in
|
||||
/// // Track all players so that the observed region does not change
|
||||
/// // even if there is no favorite player at all.
|
||||
/// try db.registerAccess(to: Player.all())
|
||||
/// - With ``Database/registerAccess(to:)``, you extend the list of
|
||||
/// tracked region(s) from the fetching closure:
|
||||
///
|
||||
/// let pref = try Preference.fetchOne(db) ?? .default
|
||||
/// let playerIds: [Int64] = pref.favoritePlayerIds // may be empty
|
||||
/// return try Player.fetchAll(db, ids: playerIds)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// // Optimized observation that implicitly tracks the
|
||||
/// // 'appConfiguration' table, and explicitly tracks 'food'
|
||||
/// // and 'beverage':
|
||||
/// let observation = ValueObservation.trackingConstantRegion { db -> Int in
|
||||
/// try db.registerAccess(to: Food.all())
|
||||
/// try db.registerAccess(to: Beverage.all())
|
||||
///
|
||||
/// let observation = ValueObservation.trackingConstantRegion { db -> Int in
|
||||
/// // Track foods and beverages so that the observed region does not
|
||||
/// // depend on preferences.
|
||||
/// try db.registerAccess(to: Food.all())
|
||||
/// try db.registerAccess(to: Beverage.all())
|
||||
///
|
||||
/// let pref = try Preference.fetchOne(db) ?? .default
|
||||
/// switch pref.selection {
|
||||
/// case .food: return try Food.fetchCount(db)
|
||||
/// case .beverage: return try Beverage.fetchCount(db)
|
||||
/// let config = try AppConfiguration.find(db)
|
||||
/// switch config.selection {
|
||||
/// case .food:
|
||||
/// return try Food.fetchCount(db)
|
||||
/// case .beverage:
|
||||
/// return try Beverage.fetchCount(db)
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
/// ```
|
||||
///
|
||||
/// - parameter fetch: The closure that fetches the observed value.
|
||||
public static func trackingConstantRegion<Value>(
|
||||
@@ -758,6 +784,19 @@ extension ValueObservation {
|
||||
/// fetch: { db in ... })
|
||||
/// ```
|
||||
///
|
||||
/// Unlike observations created with ``tracking(_:)``, the returned
|
||||
/// observation can reduce database contention, by not blocking
|
||||
/// database writes when fresh values are fetched. It can also avoid
|
||||
/// fetching fresh values from the main thread, after the database was
|
||||
/// modified on the main thread.
|
||||
///
|
||||
/// Those scheduling optimizations are only applied when the observation
|
||||
/// is started from a ``DatabasePool``. You can start such an
|
||||
/// observation from a ``DatabaseQueue``, but the optimizations will not
|
||||
/// be applied. The notified values will be the same, though. This makes
|
||||
/// it possible to use a pool in the main application, and an in-memory
|
||||
/// queue in tests and Xcode previews.
|
||||
///
|
||||
/// - parameter region: A region to observe.
|
||||
/// - parameter otherRegions: A list of supplementary regions
|
||||
/// to observe.
|
||||
@@ -817,6 +856,19 @@ extension ValueObservation {
|
||||
/// fetch: { db in ... })
|
||||
/// ```
|
||||
///
|
||||
/// Unlike observations created with ``tracking(_:)``, the returned
|
||||
/// observation can reduce database contention, by not blocking
|
||||
/// database writes when fresh values are fetched. It can also avoid
|
||||
/// fetching fresh values from the main thread, after the database was
|
||||
/// modified on the main thread.
|
||||
///
|
||||
/// Those scheduling optimizations are only applied when the observation
|
||||
/// is started from a ``DatabasePool``. You can start such an
|
||||
/// observation from a ``DatabaseQueue``, but the optimizations will not
|
||||
/// be applied. The notified values will be the same, though. This makes
|
||||
/// it possible to use a pool in the main application, and an in-memory
|
||||
/// queue in tests and Xcode previews.
|
||||
///
|
||||
/// - parameter regions: An array of observed regions.
|
||||
/// - parameter fetch: The closure that fetches the observed value.
|
||||
public static func tracking<Value>(
|
||||
|
||||
@@ -66,6 +66,10 @@ extension ValueObservationScheduler where Self == AsyncValueObservationScheduler
|
||||
/// print("fresh players: \(players)")
|
||||
/// })
|
||||
/// ```
|
||||
///
|
||||
/// - warning: Make sure you provide a serial queue, because a
|
||||
/// concurrent one such as `DispachQueue.global(qos: .default)` would
|
||||
/// mess with the ordering of fresh value notifications.
|
||||
public static func async(onQueue queue: DispatchQueue) -> AsyncValueObservationScheduler {
|
||||
AsyncValueObservationScheduler(queue: queue)
|
||||
}
|
||||
|
||||
@@ -267,6 +267,7 @@
|
||||
56AFEF3A2996B9EE00CA1E51 /* TransactionDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF382996B9EE00CA1E51 /* TransactionDateTests.swift */; };
|
||||
56B021CC1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; };
|
||||
56B14E821D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; };
|
||||
56B6AB092BD3DCE0009A0B71 /* SingletonUserDefaultsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6AB072BD3DCE0009A0B71 /* SingletonUserDefaultsTest.swift */; };
|
||||
56B6EF60208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */; };
|
||||
56B86E70220FF4C900524C16 /* SQLLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B86E6E220FF4C800524C16 /* SQLLiteralTests.swift */; };
|
||||
56B9649F1DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; };
|
||||
@@ -783,6 +784,7 @@
|
||||
56AFEF382996B9EE00CA1E51 /* TransactionDateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionDateTests.swift; sourceTree = "<group>"; };
|
||||
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = "<group>"; };
|
||||
56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = "<group>"; };
|
||||
56B6AB072BD3DCE0009A0B71 /* SingletonUserDefaultsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SingletonUserDefaultsTest.swift; sourceTree = "<group>"; };
|
||||
56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = "<group>"; };
|
||||
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
|
||||
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
|
||||
@@ -1558,6 +1560,7 @@
|
||||
children = (
|
||||
564E73E7203DA278000C443C /* JoinSupportTests.swift */,
|
||||
5616B4FE28B5F5490052017E /* SingletonRecordTest.swift */,
|
||||
56B6AB072BD3DCE0009A0B71 /* SingletonUserDefaultsTest.swift */,
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */,
|
||||
560B3FA41C19DFF800C58EC7 /* PersistableRecord */,
|
||||
56176C9E1EACEDF9000F3F2B /* Record */,
|
||||
@@ -2330,6 +2333,7 @@
|
||||
5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */,
|
||||
563B533B267E2FA4009549B5 /* TableTests.swift in Sources */,
|
||||
5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
|
||||
56B6AB092BD3DCE0009A0B71 /* SingletonUserDefaultsTest.swift in Sources */,
|
||||
561F38F62AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */,
|
||||
564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */,
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
|
||||
</p>
|
||||
|
||||
**Latest release**: February 25, 2024 • [version 6.25.0](https://github.com/groue/GRDB.swift/tree/v6.25.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
|
||||
**Latest release**: April 21, 2024 • [version 6.27.0](https://github.com/groue/GRDB.swift/tree/v6.27.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
|
||||
|
||||
**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+
|
||||
|
||||
@@ -4291,6 +4291,17 @@ GRDB comes with a Swift version of many SQLite [built-in functions](https://sqli
|
||||
|
||||
For more information about the functions `dateTime` and `julianDay`, see [Date And Time Functions](https://www.sqlite.org/lang_datefunc.html).
|
||||
|
||||
- `CAST`
|
||||
|
||||
Use the `cast` Swift function:
|
||||
|
||||
```swift
|
||||
// SELECT (CAST(wins AS REAL) / games) AS successRate FROM player
|
||||
Player.select((cast(winsColumn, as: .real) / gamesColumn).forKey("successRate"))
|
||||
```
|
||||
|
||||
See [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr) for more information about SQLite conversions.
|
||||
|
||||
- `IFNULL`
|
||||
|
||||
Use the Swift `??` operator:
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>6.25.0</string>
|
||||
<string>6.27.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
/* Begin PBXBuildFile section */
|
||||
5603CECF2AC8636E00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CECE2AC8636E00CF097D /* JSONExpressionsTests.swift */; };
|
||||
5603CED02AC8636E00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CECE2AC8636E00CF097D /* JSONExpressionsTests.swift */; };
|
||||
56071DE52BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56071DE42BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift */; };
|
||||
56071DE62BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56071DE42BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift */; };
|
||||
561F38DD2AC891710051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DC2AC891710051EEE9 /* JSONColumnTests.swift */; };
|
||||
561F38DE2AC891710051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DC2AC891710051EEE9 /* JSONColumnTests.swift */; };
|
||||
561F38F92AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; };
|
||||
@@ -502,6 +504,7 @@
|
||||
04298D834C818285823558AB /* Pods-GRDBTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.release.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.release.xcconfig"; sourceTree = "<group>"; };
|
||||
47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = "<group>"; };
|
||||
5603CECE2AC8636E00CF097D /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = "<group>"; };
|
||||
56071DE42BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SingletonUserDefaultsTest.swift; sourceTree = "<group>"; };
|
||||
561F38DC2AC891710051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
|
||||
561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
561F38F82AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1034,6 +1037,7 @@
|
||||
56419CFA24A5405A004967E1 /* SelectStatementTests.swift */,
|
||||
567B5C282AD32A2D00629622 /* SharedValueObservationTests.swift */,
|
||||
567B5C1E2AD32A2D00629622 /* SingletonRecordTest.swift */,
|
||||
56071DE42BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift */,
|
||||
567B5C232AD32A2D00629622 /* SQLExpressionIsConstantTests.swift */,
|
||||
56419CCA24A54056004967E1 /* SQLExpressionLiteralTests.swift */,
|
||||
567B5C1D2AD32A2D00629622 /* SQLIdentifyingColumnsTests.swift */,
|
||||
@@ -1459,6 +1463,7 @@
|
||||
56419E0324A54062004967E1 /* SchedulingWatchdogTests.swift in Sources */,
|
||||
56419E7D24A54063004967E1 /* DropWhileCursorTests.swift in Sources */,
|
||||
56419EBD24A54063004967E1 /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */,
|
||||
56071DE52BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift in Sources */,
|
||||
56419E8F24A54063004967E1 /* AssociationHasManySQLTests.swift in Sources */,
|
||||
5641A1A424A540D6004967E1 /* Support.swift in Sources */,
|
||||
5641A1BC24A540D6004967E1 /* PublisherExpectation.swift in Sources */,
|
||||
@@ -1706,6 +1711,7 @@
|
||||
56419E0424A54062004967E1 /* SchedulingWatchdogTests.swift in Sources */,
|
||||
56419E7E24A54063004967E1 /* DropWhileCursorTests.swift in Sources */,
|
||||
56419EBE24A54063004967E1 /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */,
|
||||
56071DE62BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift in Sources */,
|
||||
56419E9024A54063004967E1 /* AssociationHasManySQLTests.swift in Sources */,
|
||||
5641A1A524A540D6004967E1 /* Support.swift in Sources */,
|
||||
5641A1BD24A540D6004967E1 /* PublisherExpectation.swift in Sources */,
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
56071DE22BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56071DE12BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift */; };
|
||||
56071DE32BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56071DE12BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift */; };
|
||||
561F38E12AC891890051EEE9 /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DF2AC891890051EEE9 /* JSONExpressionsTests.swift */; };
|
||||
561F38E22AC891890051EEE9 /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DF2AC891890051EEE9 /* JSONExpressionsTests.swift */; };
|
||||
561F38E32AC891890051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38E02AC891890051EEE9 /* JSONColumnTests.swift */; };
|
||||
@@ -503,6 +505,7 @@
|
||||
/* Begin PBXFileReference section */
|
||||
04298D834C818285823558AB /* Pods-GRDBTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.release.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.release.xcconfig"; sourceTree = "<group>"; };
|
||||
47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = "<group>"; };
|
||||
56071DE12BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SingletonUserDefaultsTest.swift; sourceTree = "<group>"; };
|
||||
561F38DF2AC891890051EEE9 /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = "<group>"; };
|
||||
561F38E02AC891890051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
|
||||
561F38FD2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1038,6 +1041,7 @@
|
||||
56419F5B24A54098004967E1 /* SelectStatementTests.swift */,
|
||||
567B5C0B2AD32A0000629622 /* SharedValueObservationTests.swift */,
|
||||
567B5C0A2AD32A0000629622 /* SingletonRecordTest.swift */,
|
||||
56071DE12BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift */,
|
||||
567B5C0C2AD32A0000629622 /* SQLExpressionIsConstantTests.swift */,
|
||||
56419F1C24A54094004967E1 /* SQLExpressionLiteralTests.swift */,
|
||||
567B5C0D2AD32A0000629622 /* SQLIdentifyingColumnsTests.swift */,
|
||||
@@ -1465,6 +1469,7 @@
|
||||
5641A04424A540A1004967E1 /* FTS3TokenizerTests.swift in Sources */,
|
||||
5641A14024A540A2004967E1 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
|
||||
561F38FF2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */,
|
||||
56071DE22BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift in Sources */,
|
||||
5641A08A24A540A1004967E1 /* EncryptionTests.swift in Sources */,
|
||||
5641A11E24A540A1004967E1 /* IndexInfoTests.swift in Sources */,
|
||||
56419FEC24A540A1004967E1 /* FTS4TableBuilderTests.swift in Sources */,
|
||||
@@ -1712,6 +1717,7 @@
|
||||
5641A04524A540A1004967E1 /* FTS3TokenizerTests.swift in Sources */,
|
||||
5641A14124A540A2004967E1 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
|
||||
561F39002AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */,
|
||||
56071DE32BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift in Sources */,
|
||||
5641A08B24A540A1004967E1 /* EncryptionTests.swift in Sources */,
|
||||
5641A11F24A540A1004967E1 /* IndexInfoTests.swift in Sources */,
|
||||
56419FED24A540A1004967E1 /* FTS4TableBuilderTests.swift in Sources */,
|
||||
|
||||
@@ -1511,6 +1511,30 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testCast() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
do {
|
||||
let request = Team.annotated(with: cast(Team.players.count, as: .real))
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "team".*, CAST(COUNT(DISTINCT "player"."id") AS REAL) AS "playerCount" \
|
||||
FROM "team" \
|
||||
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
|
||||
GROUP BY "team"."id"
|
||||
""")
|
||||
}
|
||||
do {
|
||||
let request = Team.annotated(with: cast(Team.players.count, as: .real).forKey("foo"))
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "team".*, CAST(COUNT(DISTINCT "player"."id") AS REAL) AS "foo" \
|
||||
FROM "team" \
|
||||
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
|
||||
GROUP BY "team"."id"
|
||||
""")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testLength() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
|
||||
@@ -637,6 +637,26 @@ class EncryptionTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// Test for the use case described in <https://github.com/groue/GRDB.swift/discussions/1517>
|
||||
func testEncryptedDatabaseCanBeAttached() throws {
|
||||
// Create encrypted db
|
||||
var config = Configuration()
|
||||
config.prepareDatabase { db in
|
||||
try db.usePassphrase("secret")
|
||||
}
|
||||
let encryptedDBQueue = try makeDatabaseQueue(filename: "encrypted.sqlite", configuration: config)
|
||||
try encryptedDBQueue.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
}
|
||||
|
||||
let attachingDBQueue = try makeDatabaseQueue()
|
||||
try attachingDBQueue.inDatabase { db in
|
||||
try db.execute(sql: "ATTACH DATABASE ? AS encrypted KEY ?", arguments: [encryptedDBQueue.path, "secret"])
|
||||
let count = try Table("t").fetchCount(db)
|
||||
XCTAssertEqual(count, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func testExportPlainTextDatabaseToEncryptedDatabase() throws {
|
||||
// See https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/868?source_topic_id=939
|
||||
do {
|
||||
|
||||
@@ -263,14 +263,130 @@ extension FetchableRecordDecodableTests {
|
||||
|
||||
extension FetchableRecordDecodableTests {
|
||||
|
||||
func testStructWithData() throws {
|
||||
struct StructWithData : FetchableRecord, Decodable {
|
||||
let data: Data
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
do {
|
||||
let data = "foo".data(using: .utf8)
|
||||
|
||||
do {
|
||||
let value = try StructWithData(row: ["data": data])
|
||||
XCTAssertEqual(value.data, data)
|
||||
}
|
||||
|
||||
do {
|
||||
let value = try dbQueue.read {
|
||||
try StructWithData.fetchOne($0, sql: "SELECT ? AS data", arguments: [data])!
|
||||
}
|
||||
XCTAssertEqual(value.data, data)
|
||||
}
|
||||
}
|
||||
do {
|
||||
do {
|
||||
_ = try StructWithData(row: ["data": nil])
|
||||
XCTFail("Expected Error")
|
||||
} catch let error as RowDecodingError {
|
||||
switch error {
|
||||
case .valueMismatch:
|
||||
XCTAssertEqual(error.description, """
|
||||
could not decode Data from database value NULL - \
|
||||
column: "data", \
|
||||
column index: 0, \
|
||||
row: [data:NULL]
|
||||
""")
|
||||
default:
|
||||
XCTFail("Unexpected Error")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try dbQueue.read {
|
||||
_ = try StructWithData.fetchOne($0, sql: "SELECT NULL AS data")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch let error as RowDecodingError {
|
||||
switch error {
|
||||
case .valueMismatch:
|
||||
XCTAssertEqual(error.description, """
|
||||
could not decode Data from database value NULL - \
|
||||
column: "data", \
|
||||
column index: 0, \
|
||||
row: [data:NULL], \
|
||||
sql: `SELECT NULL AS data`, \
|
||||
arguments: []
|
||||
""")
|
||||
default:
|
||||
XCTFail("Unexpected Error")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testStructWithDate() throws {
|
||||
struct StructWithDate : FetchableRecord, Decodable {
|
||||
let date: Date
|
||||
}
|
||||
|
||||
let date = Date()
|
||||
let value = try StructWithDate(row: ["date": date])
|
||||
XCTAssert(abs(value.date.timeIntervalSince(date)) < 0.001)
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
do {
|
||||
let date = Date()
|
||||
|
||||
do {
|
||||
let value = try StructWithDate(row: ["date": date])
|
||||
XCTAssert(abs(value.date.timeIntervalSince(date)) < 0.001)
|
||||
}
|
||||
|
||||
do {
|
||||
let value = try dbQueue.read {
|
||||
try StructWithDate.fetchOne($0, sql: "SELECT ? AS date", arguments: [date])!
|
||||
}
|
||||
XCTAssert(abs(value.date.timeIntervalSince(date)) < 0.001)
|
||||
}
|
||||
}
|
||||
do {
|
||||
do {
|
||||
_ = try StructWithDate(row: ["date": nil])
|
||||
XCTFail("Expected Error")
|
||||
} catch let error as RowDecodingError {
|
||||
switch error {
|
||||
case .valueMismatch:
|
||||
XCTAssertEqual(error.description, """
|
||||
could not decode Date from database value NULL - \
|
||||
column: "date", \
|
||||
column index: 0, \
|
||||
row: [date:NULL]
|
||||
""")
|
||||
default:
|
||||
XCTFail("Unexpected Error")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try dbQueue.read {
|
||||
_ = try StructWithDate.fetchOne($0, sql: "SELECT NULL AS date")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch let error as RowDecodingError {
|
||||
switch error {
|
||||
case .valueMismatch:
|
||||
XCTAssertEqual(error.description, """
|
||||
could not decode Date from database value NULL - \
|
||||
column: "date", \
|
||||
column index: 0, \
|
||||
row: [date:NULL], \
|
||||
sql: `SELECT NULL AS date`, \
|
||||
arguments: []
|
||||
""")
|
||||
default:
|
||||
XCTFail("Unexpected Error")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testStructWithURL() throws {
|
||||
@@ -1536,3 +1652,265 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - KeyedContainer tests
|
||||
|
||||
extension FetchableRecordDecodableTests {
|
||||
struct AnyCodingKey: CodingKey {
|
||||
var stringValue: String
|
||||
var intValue: Int? { nil }
|
||||
|
||||
init(_ key: String) {
|
||||
self.stringValue = key
|
||||
}
|
||||
|
||||
init(stringValue: String) {
|
||||
self.stringValue = stringValue
|
||||
}
|
||||
|
||||
init?(intValue: Int) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func test_allKeys_and_containsKey() throws {
|
||||
struct Witness: Decodable, FetchableRecord {
|
||||
init(from decoder: any Decoder) throws {
|
||||
// Top
|
||||
let container = try decoder.container(keyedBy: AnyCodingKey.self)
|
||||
do {
|
||||
// Test allKeys
|
||||
let allKeys = container.allKeys
|
||||
XCTAssertEqual(Set(allKeys.map(\.stringValue)), [
|
||||
"a",
|
||||
"topLevelScope1",
|
||||
"topLevelScope2",
|
||||
"nestedScope1",
|
||||
"nestedScope2",
|
||||
"prefetchedRows1",
|
||||
"prefetchedRows2"])
|
||||
|
||||
// Test contains(_:)
|
||||
for key in allKeys {
|
||||
XCTAssertTrue(container.contains(key))
|
||||
}
|
||||
XCTAssertFalse(container.contains(AnyCodingKey("b")))
|
||||
XCTAssertFalse(container.contains(AnyCodingKey("c")))
|
||||
}
|
||||
|
||||
// topLevelScope1
|
||||
let topLevelScope1Container = try container.nestedContainer(
|
||||
keyedBy: AnyCodingKey.self,
|
||||
forKey: AnyCodingKey("topLevelScope1"))
|
||||
do {
|
||||
// Test allKeys
|
||||
let allKeys = topLevelScope1Container.allKeys
|
||||
XCTAssertEqual(Set(allKeys.map(\.stringValue)), [
|
||||
"c",
|
||||
])
|
||||
|
||||
// Test contains(_:)
|
||||
for key in allKeys {
|
||||
XCTAssertTrue(topLevelScope1Container.contains(key))
|
||||
}
|
||||
}
|
||||
|
||||
// topLevelScope2
|
||||
let topLevelScope2Container = try container.nestedContainer(
|
||||
keyedBy: AnyCodingKey.self,
|
||||
forKey: AnyCodingKey("topLevelScope2"))
|
||||
do {
|
||||
// Test allKeys
|
||||
let allKeys = topLevelScope2Container.allKeys
|
||||
XCTAssertEqual(Set(allKeys.map(\.stringValue)), [
|
||||
"nestedScope2",
|
||||
"nestedScope1",
|
||||
"prefetchedRows2",
|
||||
])
|
||||
|
||||
// Test contains(_:)
|
||||
for key in allKeys {
|
||||
XCTAssertTrue(topLevelScope2Container.contains(key))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().read { db in
|
||||
let row = try Row.fetchOne(
|
||||
db, sql: """
|
||||
SELECT 1 AS a, -- main row
|
||||
2 AS b, -- not exposed
|
||||
3 AS c, -- scope topLevelScope1
|
||||
4 AS d, -- scope topLevelScope2.nestedScope1
|
||||
5 AS e -- scope topLevelScope2.nestedScope2
|
||||
""",
|
||||
adapter: RangeRowAdapter(0..<1)
|
||||
.addingScopes([
|
||||
"topLevelScope1": RangeRowAdapter(2..<3),
|
||||
"topLevelScope2": EmptyRowAdapter().addingScopes([
|
||||
"nestedScope1": RangeRowAdapter(3..<4),
|
||||
"nestedScope2": RangeRowAdapter(4..<5),
|
||||
]),
|
||||
]))!
|
||||
|
||||
row.prefetchedRows.setRows([], forKeyPath: ["prefetchedRows1"])
|
||||
row.prefetchedRows.setRows([Row()], forKeyPath: ["topLevelScope2", "prefetchedRows2"])
|
||||
// Check test setup
|
||||
XCTAssertEqual(row.debugDescription, """
|
||||
▿ [a:1]
|
||||
unadapted: [a:1 b:2 c:3 d:4 e:5]
|
||||
- topLevelScope1: [c:3]
|
||||
- topLevelScope2: []
|
||||
- nestedScope1: [d:4]
|
||||
- nestedScope2: [e:5]
|
||||
+ prefetchedRows2: 1 row
|
||||
+ prefetchedRows1: 0 row
|
||||
+ prefetchedRows2: 1 row
|
||||
""")
|
||||
|
||||
// Test keyed container
|
||||
_ = try FetchableRecordDecoder().decode(Witness.self, from: row)
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1531>
|
||||
func test_decodeNil_and_containsKey() throws {
|
||||
struct Witness: Decodable, FetchableRecord {
|
||||
struct NestedRecord: Decodable, FetchableRecord { }
|
||||
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: AnyCodingKey.self)
|
||||
|
||||
// column
|
||||
do {
|
||||
let key = AnyCodingKey("a")
|
||||
let nilDecoded = try container.decodeNil(forKey: key)
|
||||
let value = try container.decodeIfPresent(Int.self, forKey: key)
|
||||
XCTAssertTrue(nilDecoded == (value == nil))
|
||||
XCTAssertTrue(container.contains(key))
|
||||
}
|
||||
|
||||
// scope
|
||||
do {
|
||||
let key = AnyCodingKey("nested")
|
||||
let nilDecoded = try container.decodeNil(forKey: key)
|
||||
let value = try container.decodeIfPresent(NestedRecord.self, forKey: key)
|
||||
XCTAssertTrue(nilDecoded == (value == nil))
|
||||
XCTAssertTrue(container.contains(key))
|
||||
}
|
||||
|
||||
// missing key
|
||||
do {
|
||||
let key = AnyCodingKey("missing")
|
||||
try XCTAssertTrue(container.decodeNil(forKey: key))
|
||||
try XCTAssertNil(container.decodeIfPresent(Int.self, forKey: key))
|
||||
try XCTAssertNil(container.decodeIfPresent(NestedRecord.self, forKey: key))
|
||||
XCTAssertFalse(container.contains(key))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().read { db in
|
||||
do {
|
||||
let row = try Row.fetchOne(
|
||||
db, sql: """
|
||||
SELECT 1 AS a, 2 AS b
|
||||
""",
|
||||
adapter: ScopeAdapter([
|
||||
"nested": RangeRowAdapter(1..<2),
|
||||
]))!
|
||||
|
||||
// Check test setup
|
||||
XCTAssertEqual(row.debugDescription, """
|
||||
▿ [a:1 b:2]
|
||||
unadapted: [a:1 b:2]
|
||||
- nested: [b:2]
|
||||
""")
|
||||
|
||||
// Test keyed container
|
||||
_ = try FetchableRecordDecoder().decode(Witness.self, from: row)
|
||||
}
|
||||
|
||||
do {
|
||||
let row = try Row.fetchOne(
|
||||
db, sql: """
|
||||
SELECT NULL AS a, NULL AS b
|
||||
""",
|
||||
adapter: ScopeAdapter([
|
||||
"nested": RangeRowAdapter(1..<2),
|
||||
]))!
|
||||
|
||||
// Check test setup
|
||||
XCTAssertEqual(row.debugDescription, """
|
||||
▿ [a:NULL b:NULL]
|
||||
unadapted: [a:NULL b:NULL]
|
||||
- nested: [b:NULL]
|
||||
""")
|
||||
|
||||
// Test keyed container
|
||||
_ = try FetchableRecordDecoder().decode(Witness.self, from: row)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1531>
|
||||
func test_decodeNil_when_scope_and_column_have_the_same_name() throws {
|
||||
struct Witness: Decodable, FetchableRecord {
|
||||
struct NestedRecord: Decodable, FetchableRecord { }
|
||||
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: AnyCodingKey.self)
|
||||
|
||||
let key = AnyCodingKey("a")
|
||||
let nilDecoded = try container.decodeNil(forKey: key)
|
||||
let intValue = try container.decodeIfPresent(Int.self, forKey: key)
|
||||
let recordValue = try container.decodeIfPresent(NestedRecord.self, forKey: key)
|
||||
XCTAssertTrue(nilDecoded == (intValue == nil))
|
||||
XCTAssertTrue(nilDecoded == (recordValue == nil))
|
||||
}
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().read { db in
|
||||
do {
|
||||
let row = try Row.fetchOne(
|
||||
db, sql: """
|
||||
SELECT 1 AS a
|
||||
""",
|
||||
adapter: ScopeAdapter([
|
||||
"a": SuffixRowAdapter(fromIndex: 0),
|
||||
]))!
|
||||
|
||||
// Check test setup
|
||||
XCTAssertEqual(row.debugDescription, """
|
||||
▿ [a:1]
|
||||
unadapted: [a:1]
|
||||
- a: [a:1]
|
||||
""")
|
||||
|
||||
// Test keyed container
|
||||
_ = try FetchableRecordDecoder().decode(Witness.self, from: row)
|
||||
}
|
||||
|
||||
do {
|
||||
let row = try Row.fetchOne(
|
||||
db, sql: """
|
||||
SELECT NULL AS a
|
||||
""",
|
||||
adapter: ScopeAdapter([
|
||||
"a": SuffixRowAdapter(fromIndex: 0),
|
||||
]))!
|
||||
|
||||
// Check test setup
|
||||
XCTAssertEqual(row.debugDescription, """
|
||||
▿ [a:NULL]
|
||||
unadapted: [a:NULL]
|
||||
- a: [a:NULL]
|
||||
""")
|
||||
|
||||
// Test keyed container
|
||||
_ = try FetchableRecordDecoder().decode(Witness.self, from: row)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -358,11 +358,6 @@ final class JSONExpressionsTests: GRDBTestCase {
|
||||
guard sqlite3_libversion_number() >= 3042000 else {
|
||||
throw XCTSkip("JSON_ERROR_JSON is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) else {
|
||||
throw XCTSkip("JSON_ERROR_JSON is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
try makeDatabaseQueue().inDatabase { db in
|
||||
try db.create(table: "player") { t in
|
||||
@@ -385,6 +380,9 @@ final class JSONExpressionsTests: GRDBTestCase {
|
||||
SELECT JSON_ERROR_POSITION("info") FROM "player"
|
||||
""")
|
||||
}
|
||||
#else
|
||||
throw XCTSkip("JSON_ERROR_JSON is not available")
|
||||
#endif
|
||||
}
|
||||
|
||||
func test_Database_jsonExtract_atPath() throws {
|
||||
|
||||
@@ -1526,7 +1526,15 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
sql(dbQueue, tableRequest.select(average(Col.age / 2, filter: Col.age > 0))),
|
||||
"SELECT AVG(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
}
|
||||
|
||||
|
||||
func testCastExpression() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(cast(Col.name, as: .blob))),
|
||||
"SELECT CAST(\"name\" AS BLOB) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testLengthExpression() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
private func cast<T: SQLExpressible>(_ value: T, as type: Database.ColumnType) -> SQLExpression {
|
||||
private func myCast<T: SQLExpressible>(_ value: T, as type: Database.ColumnType) -> SQLExpression {
|
||||
SQL("CAST(\(value) AS \(sql: type.rawValue))").sqlExpression
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase {
|
||||
try db.execute(sql: "INSERT INTO records (text) VALUES (?)", arguments: ["foo"])
|
||||
|
||||
do {
|
||||
let request = Record.select(cast(Column("text"), as: .blob))
|
||||
let request = Record.select(myCast(Column("text"), as: .blob))
|
||||
let dbValue = try DatabaseValue.fetchOne(db, request)!
|
||||
switch dbValue.storage {
|
||||
case .blob:
|
||||
@@ -30,7 +30,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase {
|
||||
XCTAssertEqual(self.lastSQLQuery, "SELECT CAST(\"text\" AS BLOB) FROM \"records\" LIMIT 1")
|
||||
}
|
||||
do {
|
||||
let request = Record.select(cast(Column("text"), as: .blob) && true)
|
||||
let request = Record.select(myCast(Column("text"), as: .blob) && true)
|
||||
_ = try DatabaseValue.fetchOne(db, request)!
|
||||
XCTAssertEqual(self.lastSQLQuery, "SELECT (CAST(\"text\" AS BLOB)) AND 1 FROM \"records\" LIMIT 1")
|
||||
}
|
||||
|
||||
@@ -274,6 +274,10 @@ class SQLExpressionIsConstantTests: GRDBTestCase {
|
||||
XCTAssertFalse((Column("a") - 2.databaseValue).isConstantInRequest)
|
||||
XCTAssertFalse((1.databaseValue - Column("a")).isConstantInRequest)
|
||||
|
||||
// CAST
|
||||
XCTAssertTrue(cast(1.databaseValue, as: .real).isConstantInRequest)
|
||||
XCTAssertFalse(cast(Column("a"), as: .real).isConstantInRequest)
|
||||
|
||||
// SQLExpressionCollate
|
||||
XCTAssertTrue("foo".databaseValue.collating(.binary).isConstantInRequest)
|
||||
XCTAssertFalse(Column("a").collating(.binary).isConstantInRequest)
|
||||
|
||||
@@ -31,7 +31,7 @@ extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func fetch(_ db: Database) throws -> AppConfiguration {
|
||||
static func find(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
// When
|
||||
let config = try AppConfiguration.fetch(db)
|
||||
let config = try AppConfiguration.find(db)
|
||||
// Then
|
||||
XCTAssertEqual(config.text, "default")
|
||||
}
|
||||
@@ -66,7 +66,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
try AppConfiguration(text: "initial").insert(db)
|
||||
// When
|
||||
let config = try AppConfiguration.fetch(db)
|
||||
let config = try AppConfiguration.find(db)
|
||||
// Then
|
||||
XCTAssertEqual(config.text, "initial")
|
||||
}
|
||||
@@ -79,7 +79,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").insert(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -93,7 +93,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").insert(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -106,7 +106,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").update(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -120,7 +120,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").update(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -131,12 +131,12 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
// When
|
||||
var config = try AppConfiguration.fetch(db)
|
||||
var config = try AppConfiguration.find(db)
|
||||
try config.updateChanges(db) {
|
||||
$0.text = "test"
|
||||
}
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -148,12 +148,12 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
try AppConfiguration(text: "initial").insert(db)
|
||||
// When
|
||||
var config = try AppConfiguration.fetch(db)
|
||||
var config = try AppConfiguration.find(db)
|
||||
try config.updateChanges(db) {
|
||||
$0.text = "test"
|
||||
}
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -166,7 +166,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").save(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -180,7 +180,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").save(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -203,7 +203,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").upsert(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -227,7 +227,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").upsert(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
private struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// The stored properties
|
||||
private var storedText: String?
|
||||
// ... other properties
|
||||
|
||||
// The public properties
|
||||
var text: String {
|
||||
get { storedText ?? "default" }
|
||||
set { storedText = newValue }
|
||||
}
|
||||
|
||||
mutating func resetText() {
|
||||
storedText = nil
|
||||
}
|
||||
}
|
||||
|
||||
extension AppConfiguration {
|
||||
/// The default configuration
|
||||
static let `default` = AppConfiguration()
|
||||
}
|
||||
|
||||
// Database Access
|
||||
extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
// Customize the default PersistableRecord behavior
|
||||
func willUpdate(_ db: Database, columns: Set<String>) throws {
|
||||
// Insert the default configuration if it does not exist yet.
|
||||
if try !exists(db) {
|
||||
try AppConfiguration.default.insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func find(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
|
||||
class SingletonUserDefaultsTest: GRDBTestCase {
|
||||
private func createEmptyAppConfigurationTable(_ db: Database) throws {
|
||||
// Table creation
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("storedText", .text)
|
||||
// ... other columns
|
||||
}
|
||||
}
|
||||
|
||||
func test_find_in_empty_database() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
// When
|
||||
let config = try AppConfiguration.find(db)
|
||||
// Then
|
||||
XCTAssertEqual(config.text, "default")
|
||||
}
|
||||
}
|
||||
|
||||
func test_find_in_populated_database_null() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
try AppConfiguration().insert(db)
|
||||
// When
|
||||
let config = try AppConfiguration.find(db)
|
||||
// Then
|
||||
XCTAssertEqual(config.text, "default")
|
||||
}
|
||||
}
|
||||
|
||||
func test_find_from_populated_database_not_null() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
try db.execute(sql: "INSERT INTO appConfiguration(storedText) VALUES ('initial')")
|
||||
// When
|
||||
let config = try AppConfiguration.find(db)
|
||||
// Then
|
||||
XCTAssertEqual(config.text, "initial")
|
||||
}
|
||||
}
|
||||
|
||||
func test_save_in_empty_database() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
// When
|
||||
var appConfiguration = try AppConfiguration.find(db)
|
||||
appConfiguration.text = "test"
|
||||
try appConfiguration.save(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "storedText": "test"])
|
||||
}
|
||||
}
|
||||
|
||||
func test_save_in_populated_database() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
try db.execute(sql: "INSERT INTO appConfiguration(storedText) VALUES ('initial')")
|
||||
// When
|
||||
var appConfiguration = try AppConfiguration.find(db)
|
||||
appConfiguration.text = "test"
|
||||
try appConfiguration.save(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "storedText": "test"])
|
||||
}
|
||||
}
|
||||
|
||||
func test_reset_and_save_in_populated_database() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
try db.execute(sql: "INSERT INTO appConfiguration(storedText) VALUES ('initial')")
|
||||
// When
|
||||
var appConfiguration = try AppConfiguration.find(db)
|
||||
appConfiguration.resetText()
|
||||
try appConfiguration.save(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "default")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "storedText": nil])
|
||||
}
|
||||
}
|
||||
|
||||
func test_update_changes_in_empty_database() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
// When
|
||||
var config = try AppConfiguration.find(db)
|
||||
try config.updateChanges(db) {
|
||||
$0.text = "test"
|
||||
}
|
||||
// Then
|
||||
XCTAssertEqual(config.text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "storedText": "test"])
|
||||
}
|
||||
}
|
||||
|
||||
func test_update_changes_in_populated_database() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
try db.execute(sql: "INSERT INTO appConfiguration(storedText) VALUES ('initial')")
|
||||
// When
|
||||
var config = try AppConfiguration.find(db)
|
||||
try config.updateChanges(db) {
|
||||
$0.text = "test"
|
||||
}
|
||||
// Then
|
||||
XCTAssertEqual(config.text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "storedText": "test"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 52;
|
||||
objectVersion = 54;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
|
||||
+10
-9
@@ -1,12 +1,13 @@
|
||||
{
|
||||
"originHash" : "8d182a38fc35b0d50c198e0cbd39dc7fa5922eae5336ff3b0c73c2d51bcba752",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "fmdb",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/ccgus/fmdb.git",
|
||||
"state" : {
|
||||
"revision" : "61e51fde7f7aab6554f30ab061cc588b28a97d04",
|
||||
"version" : "2.7.7"
|
||||
"revision" : "47a2fa12a242b5a2fe13b916c22f2212e426055c",
|
||||
"version" : "2.7.9"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -14,8 +15,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/realm/realm-core.git",
|
||||
"state" : {
|
||||
"revision" : "f0045b71f9d3e9a6d82c711828f14222811fa6e9",
|
||||
"version" : "13.9.4"
|
||||
"revision" : "374dd672af357732dccc135fecc905406fec3223",
|
||||
"version" : "14.4.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -23,8 +24,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/realm/realm-swift.git",
|
||||
"state" : {
|
||||
"revision" : "00e098a61acdf5e8cee4e2a6292c9ec6762ba1b4",
|
||||
"version" : "10.38.3"
|
||||
"revision" : "e0c2fbb442979fbf1e4be80e01d142f310a9c762",
|
||||
"version" : "10.49.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -32,10 +33,10 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/stephencelis/SQLite.swift.git",
|
||||
"state" : {
|
||||
"revision" : "7a2e3cd27de56f6d396e84f63beefd0267b55ccb",
|
||||
"version" : "0.14.1"
|
||||
"revision" : "e78ae0220e17525a15ac68c697a155eb7a672a8e",
|
||||
"version" : "0.15.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
"version" : 3
|
||||
}
|
||||
Reference in new issue
Block a user