mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-03 04:58:44 +00:00
Compare commits
114
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c541a99b5 | ||
|
|
2cf6c756e1 | ||
|
|
d56223cba1 | ||
|
|
bc4fd8ff58 | ||
|
|
cdb181d9ca | ||
|
|
f4b4035704 | ||
|
|
57a4587b5b | ||
|
|
ae837a3a44 | ||
|
|
c64bc11627 | ||
|
|
de96d5f6f0 | ||
|
|
d3d2a9c4f7 | ||
|
|
f10c74c374 | ||
|
|
fcfdab2f11 | ||
|
|
f441341543 | ||
|
|
dd6b98ce04 | ||
|
|
5b73581126 | ||
|
|
9a896650ff | ||
|
|
344878cdb2 | ||
|
|
20ffddd572 | ||
|
|
4ddb6b89ce | ||
|
|
9da1a83cca | ||
|
|
8205f02672 | ||
|
|
78377d5cc0 | ||
|
|
04543755d8 | ||
|
|
cdc0131369 | ||
|
|
1cd6c7cbff | ||
|
|
bbbe0d899d | ||
|
|
9f16865ff1 | ||
|
|
14d2b931a4 | ||
|
|
802b4ca78a | ||
|
|
1c60e5ef42 | ||
|
|
9f41e56c32 | ||
|
|
0ae3f32f7f | ||
|
|
c977cb8226 | ||
|
|
78448cf8f4 | ||
|
|
30de9853d6 | ||
|
|
7a1196263d | ||
|
|
3043d7dca5 | ||
|
|
d2dd757d0c | ||
|
|
764ad4bf72 | ||
|
|
e6d4223b14 | ||
|
|
ba3c938eb9 | ||
|
|
5999227c01 | ||
|
|
78545f2c8c | ||
|
|
263a549c21 | ||
|
|
6689470457 | ||
|
|
bbbd6bba90 | ||
|
|
bb789e3dee | ||
|
|
b312d4cf5a | ||
|
|
f335123c2b | ||
|
|
34d87c0e85 | ||
|
|
0f2e993790 | ||
|
|
1831017d64 | ||
|
|
4b934fda75 | ||
|
|
53c40fd80f | ||
|
|
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 | ||
|
|
4e0ab25106 | ||
|
|
c52db6095a | ||
|
|
1464940eeb | ||
|
|
f274e464cd | ||
|
|
c3e7736534 | ||
|
|
9b95dd5be1 | ||
|
|
77da5f4a30 | ||
|
|
43ced9b2f0 | ||
|
|
4ffad63f1b | ||
|
|
62e7ea1ef2 | ||
|
|
91492b849d | ||
|
|
d54d0abc07 | ||
|
|
3b096b38e7 | ||
|
|
9593297cf0 | ||
|
|
8ac5591189 | ||
|
|
4232fa687d | ||
|
|
bd9aea303d | ||
|
|
5abc737bf0 | ||
|
|
d4d14e3dd7 | ||
|
|
660d2b1fe7 | ||
|
|
bb44f48414 | ||
|
|
bbe7d2f1ca | ||
|
|
45e0de9960 | ||
|
|
1920482158 | ||
|
|
0437c0fed6 | ||
|
|
d08d2f52fb | ||
|
|
d1ff0912f1 |
No files matched your search
@@ -7,6 +7,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 6.x Releases
|
||||
|
||||
- `6.29.x` Releases - [6.29.0](#6290) - [6.29.1](#6291) - [6.29.2](#6292) - [6.29.3](#6293)
|
||||
- `6.28.x` Releases - [6.28.0](#6280)
|
||||
- `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)
|
||||
- `6.22.x` Releases - [6.22.0](#6220)
|
||||
@@ -122,6 +127,69 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 6.29.3
|
||||
|
||||
Released September 7, 2024
|
||||
|
||||
- **Fixed**: [#1613](https://github.com/groue/GRDB.swift/pull/1613) by [@groue](https://github.com/groue): Avoid SQLite misuse when releasing memory on a closed database connection
|
||||
|
||||
## 6.29.2
|
||||
|
||||
Released August 24, 2024
|
||||
|
||||
- **New**: [#1593](https://github.com/groue/GRDB.swift/pull/1593) by [@mingchen](https://github.com/mingchen): Fix sample code in README
|
||||
|
||||
## 6.29.1
|
||||
|
||||
Released August 7, 2024
|
||||
|
||||
- **New**: [#1579](https://github.com/groue/GRDB.swift/pull/1579) by [@groue](https://github.com/groue): Modernize the demo apps
|
||||
- **New**: [#1584](https://github.com/groue/GRDB.swift/pull/1584) by [@SagarSDagdu](https://github.com/SagarSDagdu): Update README to highlight deployment issue with CocoaPods
|
||||
- **New**: [#1589](https://github.com/groue/GRDB.swift/pull/1589) by [@groue](https://github.com/groue): Fix compilation issue with Xcode 16 beta 5 due to a missing import
|
||||
|
||||
## 6.29.0
|
||||
|
||||
Released July 20, 2024
|
||||
|
||||
- **New**: [#1574](https://github.com/groue/GRDB.swift/pull/1574) by [@sroebert](https://github.com/sroebert): Support for single value decoding (the complement of [#1570](https://github.com/groue/GRDB.swift/pull/1570) shipped in 6.28.0)
|
||||
- **New**: [#1575](https://github.com/groue/GRDB.swift/pull/1575) by [@Jason-Abbott](https://github.com/Jason-Abbott): Show comments when tracing expanded statements
|
||||
|
||||
## 6.28.0
|
||||
|
||||
Released July 11, 2024
|
||||
|
||||
- **New**: [#1570](https://github.com/groue/GRDB.swift/pull/1570) by [@groue](https://github.com/groue): Support single-value encoding
|
||||
- **New**: Added `QueryInterfaceRequest.deleteAndFetchIds(_:)` which returns the set of deleted ids.
|
||||
- **New**: Added `Set` methods `union`, `formUnion`, `intersection` and `formIntersection` that accept a cursor.
|
||||
- **New**: `DatabaseUUIDEncodingStrategy` is Sendable.
|
||||
|
||||
## 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](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) 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
|
||||
|
||||
Released February 25, 2024
|
||||
|
||||
- **New**: [#1496](https://github.com/groue/GRDB.swift/pull/1496) by [@danielepantaleone](https://github.com/danielepantaleone): Add privacy manifest file.
|
||||
|
||||
A `PrivacyInfo.xcprivacy` resource was added to the GRDB SPM package and Xcode projects. It declares that GRDB does not collect anything.
|
||||
|
||||
## 6.24.2
|
||||
|
||||
Released January 21, 2024
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -251,7 +251,7 @@ let rightCTE = ...
|
||||
let association = LeftRecord.association(
|
||||
to: rightCTE,
|
||||
on: { left, right in
|
||||
left[Column("x")] = right[Column("y")]
|
||||
left[Column("x")] == right[Column("y")]
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
@@ -354,6 +354,7 @@
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
INFOPLIST_FILE = GRDBAsyncDemoTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -373,6 +374,7 @@
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
INFOPLIST_FILE = GRDBAsyncDemoTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -512,7 +514,7 @@
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBAsyncDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -534,7 +536,7 @@
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBAsyncDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
|
||||
+2
-2
@@ -5,8 +5,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/groue/GRDBQuery",
|
||||
"state" : {
|
||||
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
|
||||
"version" : "0.6.0"
|
||||
"revision" : "a6c46dd38ecf11a5c37732870dc03a384d582fba",
|
||||
"version" : "0.9.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
@@ -5,17 +5,12 @@ import SwiftUI
|
||||
struct GRDBAsyncDemoApp: App {
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
AppView().environment(\.appDatabase, .shared)
|
||||
AppView().appDatabase(.shared)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Give SwiftUI access to the database
|
||||
//
|
||||
// Define a new environment key that grants access to an AppDatabase.
|
||||
//
|
||||
// The technique is documented at
|
||||
// <https://developer.apple.com/documentation/swiftui/environmentkey>.
|
||||
|
||||
private struct AppDatabaseKey: EnvironmentKey {
|
||||
static var defaultValue: AppDatabase { .empty() }
|
||||
@@ -28,13 +23,10 @@ extension EnvironmentValues {
|
||||
}
|
||||
}
|
||||
|
||||
// In this demo app, views observe the database with the @Query property
|
||||
// wrapper, defined in the GRDBQuery package. Its documentation recommends to
|
||||
// define a dedicated initializer for `appDatabase` access, so we comply:
|
||||
|
||||
extension Query where Request.DatabaseContext == AppDatabase {
|
||||
/// Convenience initializer for requests that feed from `AppDatabase`.
|
||||
init(_ request: Request) {
|
||||
self.init(request, in: \.appDatabase)
|
||||
extension View {
|
||||
func appDatabase(_ appDatabase: AppDatabase) -> some View {
|
||||
self
|
||||
.environment(\.appDatabase, appDatabase)
|
||||
.databaseContext(.readOnly { appDatabase.reader })
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import Combine
|
||||
import GRDB
|
||||
import GRDBQuery
|
||||
|
||||
@@ -14,37 +13,18 @@ import GRDBQuery
|
||||
/// List(players) { player in ... )
|
||||
/// }
|
||||
/// }
|
||||
struct PlayerRequest: Queryable {
|
||||
struct PlayerRequest: ValueObservationQueryable {
|
||||
enum Ordering {
|
||||
case byScore
|
||||
case byName
|
||||
}
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
/// The ordering used by the player request.
|
||||
var ordering: Ordering
|
||||
|
||||
// MARK: - Queryable Implementation
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
|
||||
// Build the publisher from the general-purpose read-only access
|
||||
// granted by `appDatabase.reader`.
|
||||
// Some apps will prefer to call a dedicated method of `appDatabase`.
|
||||
ValueObservation
|
||||
.tracking(fetchValue(_:))
|
||||
.publisher(
|
||||
in: appDatabase.reader,
|
||||
// The `.immediate` scheduling feeds the view right on
|
||||
// subscription, and avoids an undesired animation when the
|
||||
// application starts.
|
||||
scheduling: .immediate)
|
||||
.eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
// This method is not required by Queryable, but it makes it easier
|
||||
// to test PlayerRequest.
|
||||
func fetchValue(_ db: Database) throws -> [Player] {
|
||||
func fetch(_ db: Database) throws -> [Player] {
|
||||
switch ordering {
|
||||
case .byScore:
|
||||
return try Player.all().orderedByScore().fetchAll(db)
|
||||
|
||||
@@ -43,7 +43,7 @@ struct AppView: View {
|
||||
stopEditing()
|
||||
}))
|
||||
.toolbar { toolbarContent }
|
||||
.onChange(of: players) { players in
|
||||
.onChange(of: players) {
|
||||
if players.isEmpty {
|
||||
stopEditing()
|
||||
}
|
||||
@@ -141,14 +141,14 @@ private struct ToggleOrderingButton: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct AppView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
// Preview the default, empty database
|
||||
AppView()
|
||||
|
||||
// Preview a database of random players
|
||||
AppView().environment(\.appDatabase, .random())
|
||||
}
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview("Empty") {
|
||||
// Preview the default, empty database
|
||||
AppView()
|
||||
}
|
||||
|
||||
#Preview("Populated") {
|
||||
// Preview a database of random players
|
||||
AppView().appDatabase(.random())
|
||||
}
|
||||
@@ -43,8 +43,8 @@ struct PlayerCreationView: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerCreationSheet_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
PlayerCreationView()
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
PlayerCreationView()
|
||||
}
|
||||
@@ -15,7 +15,7 @@ struct PlayerEditionView: View {
|
||||
|
||||
var body: some View {
|
||||
PlayerFormView(form: $form)
|
||||
.onChange(of: isPresented) { isPresented in
|
||||
.onChange(of: isPresented) {
|
||||
// Save when back button is pressed
|
||||
if !isPresented {
|
||||
Task {
|
||||
@@ -30,11 +30,11 @@ struct PlayerEditionView: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerEditionView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.makeRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.makeRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
}
|
||||
}
|
||||
@@ -33,15 +33,16 @@ extension PlayerForm {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerFormView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: "",
|
||||
score: "")))
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: Player.randomName(),
|
||||
score: "\(Player.randomScore())")))
|
||||
}
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview("Empty") {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: "",
|
||||
score: "")))
|
||||
}
|
||||
|
||||
#Preview("Prefilled") {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: Player.randomName(),
|
||||
score: "\(Player.randomScore())")))
|
||||
}
|
||||
@@ -46,14 +46,14 @@ private struct PlayerRow: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerList_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
PlayerList(players: [
|
||||
Player(id: 1, name: "Arthur", score: 100),
|
||||
Player(id: 2, name: "Barbara", score: 1000),
|
||||
])
|
||||
.navigationTitle("Preview")
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
NavigationView {
|
||||
PlayerList(players: [
|
||||
Player(id: 1, name: "Arthur", score: 100),
|
||||
Player(id: 2, name: "Barbara", score: 1000),
|
||||
])
|
||||
.navigationTitle("Preview")
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ class PlayerRequestTests: XCTestCase {
|
||||
|
||||
// When we fetch players ordered by name
|
||||
let playerRequest = PlayerRequest(ordering: .byName)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
let players = try dbQueue.read(playerRequest.fetch)
|
||||
|
||||
// Then the players are the two players ordered by name
|
||||
XCTAssertEqual(players, [player1, player2])
|
||||
@@ -35,7 +35,7 @@ class PlayerRequestTests: XCTestCase {
|
||||
|
||||
// When we fetch players ordered by score
|
||||
let playerRequest = PlayerRequest(ordering: .byScore)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
let players = try dbQueue.read(playerRequest.fetch)
|
||||
|
||||
// Then the players are the two players ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player1])
|
||||
|
||||
@@ -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:**
|
||||
|
||||
@@ -354,6 +354,7 @@
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -373,6 +374,7 @@
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -512,6 +514,7 @@
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -533,6 +536,7 @@
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
|
||||
+2
-2
@@ -5,8 +5,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/groue/GRDBQuery",
|
||||
"state" : {
|
||||
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
|
||||
"version" : "0.6.0"
|
||||
"revision" : "a6c46dd38ecf11a5c37732870dc03a384d582fba",
|
||||
"version" : "0.9.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
@@ -5,17 +5,12 @@ import SwiftUI
|
||||
struct GRDBCombineDemoApp: App {
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
AppView().environment(\.appDatabase, .shared)
|
||||
AppView().appDatabase(.shared)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Give SwiftUI access to the database
|
||||
//
|
||||
// Define a new environment key that grants access to an AppDatabase.
|
||||
//
|
||||
// The technique is documented at
|
||||
// <https://developer.apple.com/documentation/swiftui/environmentkey>.
|
||||
|
||||
private struct AppDatabaseKey: EnvironmentKey {
|
||||
static var defaultValue: AppDatabase { .empty() }
|
||||
@@ -28,13 +23,10 @@ extension EnvironmentValues {
|
||||
}
|
||||
}
|
||||
|
||||
// In this demo app, views observe the database with the @Query property
|
||||
// wrapper, defined in the GRDBQuery package. Its documentation recommends to
|
||||
// define a dedicated initializer for `appDatabase` access, so we comply:
|
||||
|
||||
extension Query where Request.DatabaseContext == AppDatabase {
|
||||
/// Convenience initializer for requests that feed from `AppDatabase`.
|
||||
init(_ request: Request) {
|
||||
self.init(request, in: \.appDatabase)
|
||||
extension View {
|
||||
func appDatabase(_ appDatabase: AppDatabase) -> some View {
|
||||
self
|
||||
.environment(\.appDatabase, appDatabase)
|
||||
.databaseContext(.readOnly { appDatabase.reader })
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import Combine
|
||||
import GRDB
|
||||
import GRDBQuery
|
||||
|
||||
@@ -14,37 +13,18 @@ import GRDBQuery
|
||||
/// List(players) { player in ... )
|
||||
/// }
|
||||
/// }
|
||||
struct PlayerRequest: Queryable {
|
||||
struct PlayerRequest: ValueObservationQueryable {
|
||||
enum Ordering {
|
||||
case byScore
|
||||
case byName
|
||||
}
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
/// The ordering used by the player request.
|
||||
var ordering: Ordering
|
||||
|
||||
// MARK: - Queryable Implementation
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
|
||||
// Build the publisher from the general-purpose read-only access
|
||||
// granted by `appDatabase.reader`.
|
||||
// Some apps will prefer to call a dedicated method of `appDatabase`.
|
||||
ValueObservation
|
||||
.tracking(fetchValue(_:))
|
||||
.publisher(
|
||||
in: appDatabase.reader,
|
||||
// The `.immediate` scheduling feeds the view right on
|
||||
// subscription, and avoids an undesired animation when the
|
||||
// application starts.
|
||||
scheduling: .immediate)
|
||||
.eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
// This method is not required by Queryable, but it makes it easier
|
||||
// to test PlayerRequest.
|
||||
func fetchValue(_ db: Database) throws -> [Player] {
|
||||
func fetch(_ db: Database) throws -> [Player] {
|
||||
switch ordering {
|
||||
case .byScore:
|
||||
return try Player.all().orderedByScore().fetchAll(db)
|
||||
|
||||
@@ -43,7 +43,7 @@ struct AppView: View {
|
||||
stopEditing()
|
||||
}))
|
||||
.toolbar { toolbarContent }
|
||||
.onChange(of: players) { players in
|
||||
.onChange(of: players) {
|
||||
if players.isEmpty {
|
||||
stopEditing()
|
||||
}
|
||||
@@ -132,14 +132,14 @@ private struct ToggleOrderingButton: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct AppView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
// Preview the default, empty database
|
||||
AppView()
|
||||
|
||||
// Preview a database of random players
|
||||
AppView().environment(\.appDatabase, .random())
|
||||
}
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview("Empty") {
|
||||
// Preview the default, empty database
|
||||
AppView()
|
||||
}
|
||||
|
||||
#Preview("Populated") {
|
||||
// Preview a database of random players
|
||||
AppView().appDatabase(.random())
|
||||
}
|
||||
+4
-4
@@ -43,8 +43,8 @@ struct PlayerCreationView: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerCreationSheet_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
PlayerCreationView()
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
PlayerCreationView()
|
||||
}
|
||||
+7
-7
@@ -15,7 +15,7 @@ struct PlayerEditionView: View {
|
||||
|
||||
var body: some View {
|
||||
PlayerFormView(form: $form)
|
||||
.onChange(of: isPresented) { isPresented in
|
||||
.onChange(of: isPresented) {
|
||||
// Save when back button is pressed
|
||||
if !isPresented {
|
||||
var savedPlayer = player
|
||||
@@ -28,11 +28,11 @@ struct PlayerEditionView: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerEditionView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.makeRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.makeRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
}
|
||||
}
|
||||
@@ -33,15 +33,16 @@ extension PlayerForm {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerFormView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: "",
|
||||
score: "")))
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: Player.randomName(),
|
||||
score: "\(Player.randomScore())")))
|
||||
}
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview("Empty") {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: "",
|
||||
score: "")))
|
||||
}
|
||||
|
||||
#Preview("Prefilled") {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: Player.randomName(),
|
||||
score: "\(Player.randomScore())")))
|
||||
}
|
||||
@@ -44,14 +44,14 @@ private struct PlayerRow: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerList_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
PlayerList(players: [
|
||||
Player(id: 1, name: "Arthur", score: 100),
|
||||
Player(id: 2, name: "Barbara", score: 1000),
|
||||
])
|
||||
.navigationTitle("Preview")
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
NavigationView {
|
||||
PlayerList(players: [
|
||||
Player(id: 1, name: "Arthur", score: 100),
|
||||
Player(id: 2, name: "Barbara", score: 1000),
|
||||
])
|
||||
.navigationTitle("Preview")
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -16,7 +16,7 @@ class PlayerRequestTests: XCTestCase {
|
||||
|
||||
// When we fetch players ordered by name
|
||||
let playerRequest = PlayerRequest(ordering: .byName)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
let players = try dbQueue.read(playerRequest.fetch)
|
||||
|
||||
// Then the players are the two players ordered by name
|
||||
XCTAssertEqual(players, [player1, player2])
|
||||
@@ -35,7 +35,7 @@ class PlayerRequestTests: XCTestCase {
|
||||
|
||||
// When we fetch players ordered by score
|
||||
let playerRequest = PlayerRequest(ordering: .byScore)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
let players = try dbQueue.read(playerRequest.fetch)
|
||||
|
||||
// Then the players are the two players ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player1])
|
||||
|
||||
@@ -588,6 +588,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -614,6 +615,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -828,6 +830,7 @@
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -845,6 +848,7 @@
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
|
||||
@@ -18,8 +18,10 @@ To release a new GRDB version:
|
||||
- README.md
|
||||
- Support/Info.plist
|
||||
- Commit and tag
|
||||
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the master & development branch
|
||||
- Look for undesired tags: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the `master` branch
|
||||
- Push to the `development` branch
|
||||
- Push to the `GRDB6` branch
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '6.24.2'
|
||||
s.version = '6.29.3'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -157,6 +157,7 @@
|
||||
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; };
|
||||
5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; };
|
||||
5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; };
|
||||
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */; };
|
||||
5656A7FF22946B34001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A7F822946B33001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; };
|
||||
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A81D2295B12F001FF3FF /* SQLAssociation.swift */; };
|
||||
5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A92295BFD5001FF3FF /* TableRecord+Association.swift */; };
|
||||
@@ -275,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 */; };
|
||||
@@ -769,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>"; };
|
||||
@@ -852,6 +855,7 @@
|
||||
56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = "<group>"; };
|
||||
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
|
||||
6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = "<group>"; };
|
||||
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
|
||||
C96C0F242084A442006B2981 /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = "<group>"; };
|
||||
D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseColumnEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = "<group>"; };
|
||||
@@ -1550,6 +1554,7 @@
|
||||
children = (
|
||||
564E73DE203D50B9000C443C /* JoinSupportTests.swift */,
|
||||
5616B4FA28B5F5220052017E /* SingletonRecordTest.swift */,
|
||||
56B6AB052BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift */,
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */,
|
||||
560B3FA41C19DFF800C58EC7 /* PersistableRecord */,
|
||||
56176C9E1EACEDF9000F3F2B /* Record */,
|
||||
@@ -1737,6 +1742,7 @@
|
||||
children = (
|
||||
56A2FA3524424D2A00E97D23 /* Export.swift */,
|
||||
566DDE0C288D763C0000DCFB /* Fixits.swift */,
|
||||
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */,
|
||||
56A2386F1B9C75030082EB20 /* Core */,
|
||||
567B5BDF2AD3284100629622 /* Dump */,
|
||||
5698AC291D9E5A480056AF8C /* FTS */,
|
||||
@@ -1873,6 +1879,7 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -2082,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 */,
|
||||
|
||||
@@ -294,7 +294,7 @@ public struct Configuration {
|
||||
/// connection is opened.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
|
||||
public enum JournalModeConfiguration {
|
||||
public enum JournalModeConfiguration: Sendable {
|
||||
/// The default setup has ``DatabaseQueue`` perform no specific
|
||||
/// configuration of the journal mode, and ``DatabasePool``
|
||||
/// configure the database for the WAL mode (just like the
|
||||
|
||||
@@ -195,6 +195,56 @@ extension Set {
|
||||
// database cursors.
|
||||
try cursor.forEach { insert($0) }
|
||||
}
|
||||
|
||||
/// Returns a new set with the elements of both this set and the
|
||||
/// given cursor.
|
||||
///
|
||||
/// If the set already contains one or more elements that are also in
|
||||
/// the cursor, the existing members are kept. If the cursor contains
|
||||
/// multiple instances of equivalent elements, only the first instance
|
||||
/// is kept.
|
||||
///
|
||||
/// - parameter cursor: A cursor of elements.
|
||||
/// - returns: A new set with the unique elements of this set
|
||||
/// and `cursor`.
|
||||
public func union(_ cursor: some Cursor<Element>) throws -> Set<Element> {
|
||||
var result = self
|
||||
try result.formUnion(cursor)
|
||||
return result
|
||||
}
|
||||
|
||||
/// Inserts the elements of the given cursor into the set.
|
||||
///
|
||||
/// If the set already contains one or more elements that are also in
|
||||
/// the cursor, the existing members are kept. If the cursor contains
|
||||
/// multiple instances of equivalent elements, only the first instance
|
||||
/// is kept.
|
||||
///
|
||||
/// - parameter cursor: A cursor of elements.
|
||||
public mutating func formUnion(_ cursor: some Cursor<Element>) throws {
|
||||
while let element = try cursor.next() {
|
||||
insert(element)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a new set with the elements that are common to both this set
|
||||
/// and the given cursor.
|
||||
///
|
||||
/// - parameter cursor: A cursor of elements.
|
||||
/// - returns: A new set.
|
||||
public func intersection(_ cursor: some Cursor<Element>) throws -> Set<Element> {
|
||||
var result = self
|
||||
try result.formIntersection(cursor)
|
||||
return result
|
||||
}
|
||||
|
||||
/// Removes the elements of the set that aren’t also in the
|
||||
/// given cursor.
|
||||
///
|
||||
/// - parameter cursor: A cursor of elements.
|
||||
public mutating func formIntersection(_ cursor: some Cursor<Element>) throws {
|
||||
try formIntersection(Set(cursor))
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
@@ -733,6 +783,11 @@ public final class AnyCursor<Element>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: a type-erased cursor can't be more
|
||||
// sendable than non-sendable cursors (such as `DatabaseCursor`).
|
||||
@available(*, unavailable)
|
||||
extension AnyCursor: Sendable { }
|
||||
|
||||
/// A `Cursor` that consumes and drops n elements from an underlying `Base`
|
||||
/// cursor before possibly returning the first available element.
|
||||
public final class DropFirstCursor<Base: Cursor> {
|
||||
@@ -747,6 +802,11 @@ public final class DropFirstCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `DropFirstCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension DropFirstCursor: Sendable { }
|
||||
|
||||
extension DropFirstCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
while dropped < limit {
|
||||
@@ -773,6 +833,11 @@ public final class DropWhileCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `DropWhileCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension DropWhileCursor: Sendable { }
|
||||
|
||||
extension DropWhileCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if predicateHasFailed {
|
||||
@@ -818,6 +883,11 @@ public final class EnumeratedCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `EnumeratedCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension EnumeratedCursor: Sendable { }
|
||||
|
||||
extension EnumeratedCursor: Cursor {
|
||||
public func next() throws -> (Int, Base.Element)? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
@@ -875,6 +945,11 @@ public final class FlattenCursor<Base: Cursor> where Base.Element: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `EnumeratedCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension FlattenCursor: Sendable { }
|
||||
|
||||
extension FlattenCursor: Cursor {
|
||||
public func next() throws -> Base.Element.Element? {
|
||||
while true {
|
||||
@@ -901,6 +976,11 @@ public final class MapCursor<Base: Cursor, Element> {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: There is no known reason for making
|
||||
// it thread-safe (`transform` a Sendable closure).
|
||||
@available(*, unavailable)
|
||||
extension MapCursor: Sendable { }
|
||||
|
||||
extension MapCursor: Cursor {
|
||||
public func next() throws -> Element? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
@@ -927,6 +1007,11 @@ public final class PrefixCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `PrefixCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension PrefixCursor: Sendable { }
|
||||
|
||||
extension PrefixCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if taken >= maxLength { return nil }
|
||||
@@ -954,6 +1039,11 @@ public final class PrefixWhileCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `PrefixCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension PrefixWhileCursor: Sendable { }
|
||||
|
||||
extension PrefixWhileCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if !predicateHasFailed, let nextElement = try base.next() {
|
||||
|
||||
@@ -997,7 +997,7 @@ extension Database {
|
||||
///
|
||||
/// - [pragma `table_info`](https://www.sqlite.org/pragma.html#pragma_table_info)
|
||||
/// - [pragma `table_xinfo`](https://www.sqlite.org/pragma.html#pragma_table_xinfo)
|
||||
public struct ColumnInfo: FetchableRecord {
|
||||
public struct ColumnInfo: FetchableRecord, Sendable {
|
||||
let cid: Int
|
||||
let hidden: Int?
|
||||
|
||||
@@ -1083,9 +1083,9 @@ public struct ColumnInfo: FetchableRecord {
|
||||
///
|
||||
/// - [pragma `index_list`](https://www.sqlite.org/pragma.html#pragma_index_list)
|
||||
/// - [pragma `index_info`](https://www.sqlite.org/pragma.html#pragma_index_info)
|
||||
public struct IndexInfo {
|
||||
public struct IndexInfo: Sendable{
|
||||
/// The origin of an index.
|
||||
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible {
|
||||
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible, Sendable {
|
||||
public var rawValue: String
|
||||
|
||||
public init(rawValue: String) {
|
||||
@@ -1158,7 +1158,7 @@ public struct IndexInfo {
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_foreign_key_check>
|
||||
public struct ForeignKeyViolation {
|
||||
public struct ForeignKeyViolation: Sendable {
|
||||
/// The name of the table that contains the foreign key.
|
||||
public var originTable: String
|
||||
|
||||
@@ -1307,7 +1307,7 @@ extension ForeignKeyViolation: CustomStringConvertible {
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
/// ```
|
||||
public struct PrimaryKeyInfo {
|
||||
public struct PrimaryKeyInfo: Sendable {
|
||||
private enum Impl {
|
||||
/// The hidden rowID.
|
||||
case hiddenRowID
|
||||
@@ -1433,7 +1433,7 @@ public struct PrimaryKeyInfo {
|
||||
/// `Database` method.
|
||||
///
|
||||
/// Related SQLite documentation: [pragma `foreign_key_list`](https://www.sqlite.org/pragma.html#pragma_foreign_key_list).
|
||||
public struct ForeignKeyInfo {
|
||||
public struct ForeignKeyInfo: Sendable {
|
||||
/// The first column in the output of the `foreign_key_list` pragma.
|
||||
public var id: Int
|
||||
|
||||
|
||||
@@ -361,6 +361,11 @@ public class SQLStatementCursor {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: database cursors must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension SQLStatementCursor: Sendable { }
|
||||
|
||||
extension SQLStatementCursor: Cursor {
|
||||
public func next() throws -> Statement? {
|
||||
guard offset < cString.count - 1 /* trailing \0 */ else {
|
||||
|
||||
+68
-19
@@ -70,6 +70,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
///
|
||||
/// - ``dumpContent(format:to:)``
|
||||
/// - ``dumpRequest(_:format:to:)``
|
||||
/// - ``dumpSchema(to:)``
|
||||
/// - ``dumpSQL(_:format:to:)``
|
||||
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
|
||||
/// - ``DumpFormat``
|
||||
@@ -114,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 {
|
||||
@@ -122,8 +124,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - SQLite C API
|
||||
|
||||
// TODO: make it non optional, since one can't get a `Database` instance
|
||||
// after `close()`.
|
||||
/// The raw SQLite connection, suitable for the SQLite C API.
|
||||
///
|
||||
/// The result is nil after the database has been successfully closed with
|
||||
@@ -818,6 +818,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
|
||||
@@ -829,12 +834,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
|
||||
@@ -1573,7 +1575,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// Frees as much memory as possible.
|
||||
public func releaseMemory() {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
sqlite3_db_release_memory(sqliteConnection)
|
||||
if let sqliteConnection {
|
||||
sqlite3_db_release_memory(sqliteConnection)
|
||||
}
|
||||
schemaCache.clear()
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
@@ -1729,6 +1733,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `Database` must be used from a
|
||||
// serialized database access dispatch queue (see `SerializedDatabase`).
|
||||
@available(*, unavailable)
|
||||
extension Database: Sendable { }
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension Database {
|
||||
|
||||
@@ -1854,7 +1863,7 @@ extension Database {
|
||||
/// The available checkpoint modes.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/wal_checkpoint_v2.html>
|
||||
public enum CheckpointMode: CInt {
|
||||
public enum CheckpointMode: CInt, Sendable {
|
||||
/// The `SQLITE_CHECKPOINT_PASSIVE` mode.
|
||||
case passive = 0
|
||||
|
||||
@@ -1873,7 +1882,7 @@ extension Database {
|
||||
/// Related SQLite documentation:
|
||||
/// - <https://www.sqlite.org/datatype3.html#collating_sequences>
|
||||
/// - <https://www.sqlite.org/datatype3.html#collation>
|
||||
public struct CollationName: RawRepresentable, Hashable {
|
||||
public struct CollationName: RawRepresentable, Hashable, Sendable {
|
||||
public let rawValue: String
|
||||
|
||||
/// Creates a collation name.
|
||||
@@ -1910,11 +1919,10 @@ extension Database {
|
||||
///
|
||||
/// For more information, see
|
||||
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
|
||||
public struct ColumnType: RawRepresentable, Hashable {
|
||||
public struct ColumnType: RawRepresentable, Hashable, Sendable {
|
||||
/// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.)
|
||||
public let rawValue: String
|
||||
|
||||
// TODO: GRDB7 make it an failable initializer that returns nil when rawValue is empty (or blank).
|
||||
/// Creates an SQL column type.
|
||||
public init(rawValue: String) {
|
||||
self.rawValue = rawValue
|
||||
@@ -1962,7 +1970,7 @@ extension Database {
|
||||
/// An SQLite conflict resolution.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
|
||||
public enum ConflictResolution: String {
|
||||
public enum ConflictResolution: String, Sendable {
|
||||
/// The `ROLLBACK` conflict resolution.
|
||||
case rollback = "ROLLBACK"
|
||||
|
||||
@@ -1982,7 +1990,7 @@ extension Database {
|
||||
/// A foreign key action.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>
|
||||
public enum ForeignKeyAction: String {
|
||||
public enum ForeignKeyAction: String, Sendable {
|
||||
/// The `CASCADE` foreign key action.
|
||||
case cascade = "CASCADE"
|
||||
|
||||
@@ -1999,13 +2007,39 @@ 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`
|
||||
/// ``Database/trace(options:_:)`` method.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/c_trace.html>
|
||||
public struct TracingOptions: OptionSet {
|
||||
public struct TracingOptions: OptionSet, Sendable {
|
||||
/// The raw trace event code.
|
||||
public let rawValue: CInt
|
||||
|
||||
@@ -2048,7 +2082,8 @@ extension Database {
|
||||
/// ```
|
||||
public var sql: String {
|
||||
if let unexpandedSQL {
|
||||
return String(cString: unexpandedSQL).trimmedSQLStatement
|
||||
let sql = String(cString: unexpandedSQL)
|
||||
return sql.hasPrefix("--") ? sql : sql.trimmedSQLStatement
|
||||
} else {
|
||||
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
}
|
||||
@@ -2066,6 +2101,10 @@ extension Database {
|
||||
/// information from leaking in unexpected locations, so use this
|
||||
/// property with care.
|
||||
public var expandedSQL: String {
|
||||
if let unexpandedSQL {
|
||||
let sql = String(cString: unexpandedSQL)
|
||||
if sql.hasPrefix("--") { return sql }
|
||||
}
|
||||
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
|
||||
return ""
|
||||
}
|
||||
@@ -2138,7 +2177,7 @@ extension Database {
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
|
||||
@frozen
|
||||
public enum TransactionCompletion {
|
||||
public enum TransactionCompletion: Sendable {
|
||||
case commit
|
||||
case rollback
|
||||
}
|
||||
@@ -2146,7 +2185,7 @@ extension Database {
|
||||
/// A transaction kind.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
|
||||
public enum TransactionKind: String {
|
||||
public enum TransactionKind: String, Sendable {
|
||||
/// The `DEFERRED` transaction kind.
|
||||
case deferred = "DEFERRED"
|
||||
|
||||
@@ -2179,3 +2218,13 @@ extension Database {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: a trace event contains transient
|
||||
// information.
|
||||
@available(*, unavailable)
|
||||
extension Database.TraceEvent: Sendable { }
|
||||
|
||||
// Explicit non-conformance to Sendable: a trace event contains transient
|
||||
// information.
|
||||
@available(*, unavailable)
|
||||
extension Database.TraceEvent.Statement: Sendable { }
|
||||
@@ -1,7 +1,7 @@
|
||||
/// Describe the progress of a database backup.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
|
||||
public struct DatabaseBackupProgress {
|
||||
public struct DatabaseBackupProgress: Sendable {
|
||||
/// The number of pages still to be backed up.
|
||||
///
|
||||
/// It is the result of the `sqlite3_backup_remaining` function.
|
||||
|
||||
@@ -37,6 +37,7 @@ import Dispatch
|
||||
///
|
||||
/// - ``dumpContent(format:to:)``
|
||||
/// - ``dumpRequest(_:format:to:)``
|
||||
/// - ``dumpSchema(to:)``
|
||||
/// - ``dumpSQL(_:format:to:)``
|
||||
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
|
||||
/// - ``DumpFormat``
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
///
|
||||
/// - ``isModified(byEventsOfKind:)``
|
||||
/// - ``isModified(by:)``
|
||||
public struct DatabaseRegion {
|
||||
public struct DatabaseRegion: Sendable {
|
||||
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
|
||||
|
||||
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
|
||||
|
||||
@@ -222,6 +222,11 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: database cursors must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension DatabaseValueCursor: Sendable { }
|
||||
|
||||
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
|
||||
/// cursors, arrays, or single values:
|
||||
///
|
||||
|
||||
@@ -152,6 +152,11 @@ public struct PreparedRequest {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `PreparedRequest` contains
|
||||
// a statement.
|
||||
@available(*, unavailable)
|
||||
extension PreparedRequest: Sendable { }
|
||||
|
||||
extension PreparedRequest: Refinable { }
|
||||
|
||||
// MARK: - AdaptedFetchRequest
|
||||
|
||||
+12
-1
@@ -245,6 +245,12 @@ public final class Row {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: a row contains transient
|
||||
// information. TODO GRDB7: split non sendable statement rows from sendable
|
||||
// copied rows.
|
||||
@available(*, unavailable)
|
||||
extension Row: Sendable { }
|
||||
|
||||
extension Row {
|
||||
|
||||
// MARK: - Columns
|
||||
@@ -1377,6 +1383,11 @@ public final class RowCursor: DatabaseCursor {
|
||||
public func _element(sqliteStatement: SQLiteStatement) -> Row { _row }
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: database cursors must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension RowCursor: Sendable { }
|
||||
|
||||
extension Row {
|
||||
|
||||
// MARK: - Fetching From Prepared Statement
|
||||
@@ -2059,7 +2070,7 @@ typealias RowIndex = Row.Index
|
||||
|
||||
extension Row {
|
||||
/// An index to a (column, value) pair in a ``Row``.
|
||||
public struct Index {
|
||||
public struct Index: Sendable {
|
||||
let index: Int
|
||||
init(_ index: Int) { self.index = index }
|
||||
}
|
||||
|
||||
@@ -378,7 +378,7 @@ extension RowAdapter {
|
||||
///
|
||||
/// This limit adapter may turn out useful in some narrow use cases. You'll
|
||||
/// be happy to find it when you need it.
|
||||
public struct EmptyRowAdapter: RowAdapter {
|
||||
public struct EmptyRowAdapter: RowAdapter, Sendable {
|
||||
/// Creates an `EmptyRowAdapter`.
|
||||
public init() { }
|
||||
|
||||
@@ -403,7 +403,7 @@ public struct EmptyRowAdapter: RowAdapter {
|
||||
///
|
||||
/// Note that columns that are not present in the dictionary are not present
|
||||
/// in the resulting adapted row.
|
||||
public struct ColumnMapping: RowAdapter {
|
||||
public struct ColumnMapping: RowAdapter, Sendable {
|
||||
/// A dictionary from mapped column names to column names in a base row.
|
||||
let mapping: [String: String]
|
||||
|
||||
@@ -444,7 +444,7 @@ public struct ColumnMapping: RowAdapter {
|
||||
/// // [c:2, d: 3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```
|
||||
public struct SuffixRowAdapter: RowAdapter {
|
||||
public struct SuffixRowAdapter: RowAdapter, Sendable {
|
||||
/// The suffix index
|
||||
let index: Int
|
||||
|
||||
@@ -473,7 +473,7 @@ public struct SuffixRowAdapter: RowAdapter {
|
||||
/// // [b:1 c:2]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// ```
|
||||
public struct RangeRowAdapter: RowAdapter {
|
||||
public struct RangeRowAdapter: RowAdapter, Sendable {
|
||||
/// The range
|
||||
let range: CountableRange<Int>
|
||||
|
||||
|
||||
@@ -623,6 +623,11 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: statements must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension Statement: Sendable { }
|
||||
|
||||
extension Statement: CustomStringConvertible {
|
||||
public var description: String {
|
||||
SchedulingWatchdog.allows(database) ? sql : "Statement"
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#if os(Linux)
|
||||
#if canImport(string_h)
|
||||
import string_h
|
||||
#elseif os(Linux)
|
||||
import Glibc
|
||||
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
/// `StatementAuthorizer` provides information about compiled database
|
||||
|
||||
@@ -241,6 +241,11 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: database cursors must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension FastDatabaseValueCursor: Sendable { }
|
||||
|
||||
/// Types that adopt both DatabaseValueConvertible and
|
||||
/// StatementColumnConvertible can be efficiently initialized from
|
||||
/// database values.
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import Foundation
|
||||
|
||||
/// A database value that holds date components.
|
||||
public struct DatabaseDateComponents {
|
||||
public struct DatabaseDateComponents: Sendable {
|
||||
|
||||
/// The SQLite formats for date components.
|
||||
public enum Format: String {
|
||||
public enum Format: String, Sendable {
|
||||
|
||||
/// The format "yyyy-MM-dd".
|
||||
case YMD = "yyyy-MM-dd"
|
||||
|
||||
@@ -4,7 +4,6 @@ import Foundation
|
||||
|
||||
@usableFromInline
|
||||
struct SQLiteDateParser {
|
||||
// swiftlint:disable:next unneeded_synthesized_initializer
|
||||
@usableFromInline
|
||||
init() { }
|
||||
|
||||
|
||||
@@ -135,7 +135,7 @@ extension Database {
|
||||
}
|
||||
|
||||
/// The extent of the observation performed by a ``TransactionObserver``.
|
||||
public enum TransactionObservationExtent {
|
||||
public enum TransactionObservationExtent: Sendable {
|
||||
/// Observation lasts until observer is deallocated.
|
||||
case observerLifetime
|
||||
/// Observation lasts until the next transaction.
|
||||
@@ -1056,7 +1056,7 @@ struct StatementObservation {
|
||||
/// See the ``TransactionObserver/observes(eventsOfKind:)`` method in the
|
||||
/// ``TransactionObserver`` protocol for more information.
|
||||
@frozen
|
||||
public enum DatabaseEventKind {
|
||||
public enum DatabaseEventKind: Sendable {
|
||||
/// The insertion of a row in a database table.
|
||||
case insert(tableName: String)
|
||||
|
||||
@@ -1109,7 +1109,7 @@ protocol DatabaseEventProtocol {
|
||||
/// ``TransactionObserver`` protocol for more information.
|
||||
public struct DatabaseEvent {
|
||||
/// An event kind.
|
||||
public enum Kind: CInt {
|
||||
public enum Kind: CInt, Sendable {
|
||||
/// An insertion event
|
||||
case insert = 18 // SQLITE_INSERT
|
||||
|
||||
@@ -1173,6 +1173,11 @@ public struct DatabaseEvent {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: this type can't be made Sendable
|
||||
// until GRDB7 where we can distinguish between a transient event and its copy.
|
||||
@available(*, unavailable)
|
||||
extension DatabaseEvent: Sendable { }
|
||||
|
||||
extension DatabaseEvent: DatabaseEventProtocol {
|
||||
func send(to observer: TransactionObservation) {
|
||||
observer.databaseDidChange(with: self)
|
||||
|
||||
@@ -21,7 +21,9 @@
|
||||
/// Yes, this is an awfully complex logic.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
|
||||
final class WALSnapshot: Sendable {
|
||||
final class WALSnapshot: @unchecked Sendable {
|
||||
// @unchecked because sqlite3_snapshot has no threading requirements.
|
||||
// <https://www.sqlite.org/c3ref/snapshot.html>
|
||||
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
|
||||
|
||||
init(_ db: Database) throws {
|
||||
|
||||
@@ -46,7 +46,9 @@ class WALSnapshotTransaction {
|
||||
// Open a long-lived transaction, and enter snapshot isolation
|
||||
self.walSnapshot = try reader.sync(allowingLongLivedTransaction: true) { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
// This also acquires snapshot isolation because checking
|
||||
// database schema performs a read access.
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try WALSnapshot(db)
|
||||
}
|
||||
self.reader = reader
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ extension Database {
|
||||
/// // Prints
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// db.dumpSQL("SELECT * FROM player ORDER BY id")
|
||||
/// try db.dumpSQL("SELECT * FROM player ORDER BY id")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -40,7 +40,7 @@ extension Database {
|
||||
/// // Prints
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// db.dumpRequest(Player.orderByPrimaryKey())
|
||||
/// try db.dumpRequest(Player.orderByPrimaryKey())
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -72,7 +72,7 @@ extension Database {
|
||||
/// // team
|
||||
/// // 1|Red
|
||||
/// // 2|Blue
|
||||
/// db.dumpTables(["player", "team"])
|
||||
/// try db.dumpTables(["player", "team"])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -111,7 +111,7 @@ extension Database {
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// db.dumpContent()
|
||||
/// try db.dumpContent()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -145,6 +145,40 @@ extension Database {
|
||||
var dumpStream = DumpStream(stream)
|
||||
try _dumpContent(format: format, to: &dumpStream)
|
||||
}
|
||||
|
||||
/// Prints the schema of the database.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// try db.dumpSchema()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This prints the database schema. For example:
|
||||
///
|
||||
/// ```
|
||||
/// sqlite_master
|
||||
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
|
||||
/// ```
|
||||
///
|
||||
/// > Note: Internal SQLite and GRDB schema objects are not recorded
|
||||
/// > (those with a name that starts with "sqlite_" or "grdb_").
|
||||
/// >
|
||||
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
|
||||
/// > not recorded, starting SQLite 3.37+.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - stream: A stream for text output, which directs output to the
|
||||
/// console by default.
|
||||
public func dumpSchema(
|
||||
to stream: (any TextOutputStream)? = nil)
|
||||
throws
|
||||
{
|
||||
var dumpStream = DumpStream(stream)
|
||||
try _dumpSchema(to: &dumpStream)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
@@ -241,6 +275,26 @@ extension Database {
|
||||
format: some DumpFormat,
|
||||
to stream: inout DumpStream)
|
||||
throws
|
||||
{
|
||||
try _dumpSchema(to: &stream)
|
||||
stream.margin()
|
||||
|
||||
let tables = try String
|
||||
.fetchAll(self, sql: """
|
||||
SELECT name
|
||||
FROM sqlite_master
|
||||
WHERE type = 'table'
|
||||
ORDER BY name COLLATE NOCASE
|
||||
""")
|
||||
.filter {
|
||||
try !ignoresObject(named: $0)
|
||||
}
|
||||
try _dumpTables(tables, format: format, tableHeader: .always, stableOrder: true, to: &stream)
|
||||
}
|
||||
|
||||
func _dumpSchema(
|
||||
to stream: inout DumpStream)
|
||||
throws
|
||||
{
|
||||
stream.writeln("sqlite_master")
|
||||
let sqlRows = try Row.fetchAll(self, sql: """
|
||||
@@ -260,20 +314,6 @@ extension Database {
|
||||
}
|
||||
stream.writeln(row[0])
|
||||
}
|
||||
|
||||
let tables = try String
|
||||
.fetchAll(self, sql: """
|
||||
SELECT name
|
||||
FROM sqlite_master
|
||||
WHERE type = 'table'
|
||||
ORDER BY name COLLATE NOCASE
|
||||
""")
|
||||
.filter {
|
||||
try !ignoresObject(named: $0)
|
||||
}
|
||||
if tables.isEmpty { return }
|
||||
stream.write("\n")
|
||||
try _dumpTables(tables, format: format, tableHeader: .always, stableOrder: true, to: &stream)
|
||||
}
|
||||
|
||||
private func ignoresObject(named name: String) throws -> Bool {
|
||||
@@ -308,7 +348,7 @@ extension Database {
|
||||
}
|
||||
|
||||
/// Options for printing table names.
|
||||
public enum DumpTableHeaderOptions {
|
||||
public enum DumpTableHeaderOptions: Sendable {
|
||||
/// Table names are only printed when several tables are printed.
|
||||
case automatic
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ extension DatabaseReader {
|
||||
/// // Prints
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// dbQueue.dumpSQL("SELECT * FROM player ORDER BY id")
|
||||
/// try dbQueue.dumpSQL("SELECT * FROM player ORDER BY id")
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -34,7 +34,7 @@ extension DatabaseReader {
|
||||
/// // Prints
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// dbQueue.dumpRequest(Player.orderByPrimaryKey())
|
||||
/// try dbQueue.dumpRequest(Player.orderByPrimaryKey())
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -65,7 +65,7 @@ extension DatabaseReader {
|
||||
/// // team
|
||||
/// // 1|Red
|
||||
/// // 2|Blue
|
||||
/// dbQueue.dumpTables(["player", "team"])
|
||||
/// try dbQueue.dumpTables(["player", "team"])
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -103,7 +103,7 @@ extension DatabaseReader {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// dbQueue.dumpContent()
|
||||
/// try dbQueue.dumpContent()
|
||||
/// ```
|
||||
///
|
||||
/// This prints the database schema as well as the content of all
|
||||
@@ -137,4 +137,37 @@ extension DatabaseReader {
|
||||
try db.dumpContent(format: format, to: stream)
|
||||
}
|
||||
}
|
||||
|
||||
/// Prints the schema of the database.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.dumpSchema()
|
||||
/// ```
|
||||
///
|
||||
/// This prints the database schema. For example:
|
||||
///
|
||||
/// ```
|
||||
/// sqlite_master
|
||||
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
|
||||
/// ```
|
||||
///
|
||||
/// > Note: Internal SQLite and GRDB schema objects are not recorded
|
||||
/// > (those with a name that starts with "sqlite_" or "grdb_").
|
||||
/// >
|
||||
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
|
||||
/// > not recorded, starting SQLite 3.37+.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - stream: A stream for text output, which directs output to the
|
||||
/// console by default.
|
||||
public func dumpSchema(
|
||||
to stream: (any TextOutputStream)? = nil)
|
||||
throws
|
||||
{
|
||||
try unsafeReentrantRead { db in
|
||||
try db.dumpSchema(to: stream)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ import Foundation
|
||||
/// // Craig|200
|
||||
/// try db.dumpRequest(Player.all(), format: .debug())
|
||||
/// ```
|
||||
public struct DebugDumpFormat {
|
||||
public struct DebugDumpFormat: Sendable {
|
||||
/// A boolean value indicating if column labels are printed as the first
|
||||
/// line of output.
|
||||
public var header: Bool
|
||||
|
||||
@@ -27,7 +27,7 @@ import Foundation
|
||||
/// encoder.outputFormatting = .prettyPrinted
|
||||
/// try db.dumpRequest(Player.all(), format: .json(encoder))
|
||||
/// ```
|
||||
public struct JSONDumpFormat {
|
||||
public struct JSONDumpFormat: Sendable {
|
||||
/// The default `JSONEncoder` for database values.
|
||||
///
|
||||
/// It is configured so that blob values (`Data`) are encoded in the
|
||||
|
||||
@@ -13,7 +13,7 @@ import Foundation
|
||||
/// // score = 1000
|
||||
/// try db.dumpRequest(Player.all(), format: .line())
|
||||
/// ```
|
||||
public struct LineDumpFormat {
|
||||
public struct LineDumpFormat: Sendable {
|
||||
/// The string to print for NULL values.
|
||||
public var nullValue: String
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import Foundation
|
||||
/// // Craig|200
|
||||
/// try db.dumpRequest(Player.all(), format: .list())
|
||||
/// ```
|
||||
public struct ListDumpFormat {
|
||||
public struct ListDumpFormat: Sendable {
|
||||
/// A boolean value indicating if column labels are printed as the first
|
||||
/// line of output.
|
||||
public var header: Bool
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
/// // 'Craig',200
|
||||
/// try db.dumpRequest(Player.all(), format: .quote())
|
||||
/// ```
|
||||
public struct QuoteDumpFormat {
|
||||
public struct QuoteDumpFormat: Sendable {
|
||||
/// A boolean value indicating if column labels are printed as the first
|
||||
/// line of output.
|
||||
public var header: Bool
|
||||
|
||||
+6
-1
@@ -29,7 +29,7 @@
|
||||
/// - ``tokenize(_:withTokenizer:)``
|
||||
public struct FTS3 {
|
||||
/// Options for Latin script characters.
|
||||
public enum Diacritics {
|
||||
public enum Diacritics: Sendable {
|
||||
/// Do not remove diacritics from Latin script characters. This option
|
||||
/// matches the `remove_diacritics=0` tokenizer argument.
|
||||
///
|
||||
@@ -183,3 +183,8 @@ public final class FTS3TableDefinition {
|
||||
columns.append(name)
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `FTS3TableDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension FTS3TableDefinition: Sendable { }
|
||||
@@ -16,7 +16,7 @@
|
||||
/// - ``init(matchingAllTokensIn:)``
|
||||
/// - ``init(matchingAnyTokenIn:)``
|
||||
/// - ``init(matchingPhrase:)``
|
||||
public struct FTS3Pattern {
|
||||
public struct FTS3Pattern: Sendable {
|
||||
/// The raw pattern string.
|
||||
///
|
||||
/// It is guaranteed to be a valid FTS3/4 pattern.
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
/// - ``simple``
|
||||
/// - ``unicode61(diacritics:separators:tokenCharacters:)``
|
||||
/// - ``FTS3/Diacritics``
|
||||
public struct FTS3TokenizerDescriptor {
|
||||
public struct FTS3TokenizerDescriptor: Sendable {
|
||||
let name: String
|
||||
let arguments: [String]
|
||||
|
||||
|
||||
@@ -313,6 +313,11 @@ public final class FTS4TableDefinition {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `FTS4TableDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension FTS4TableDefinition: Sendable { }
|
||||
|
||||
/// Describes a column in an ``FTS4`` virtual table.
|
||||
///
|
||||
/// You get instances of `FTS4ColumnDefinition` when you create an ``FTS4``
|
||||
@@ -377,6 +382,11 @@ public final class FTS4ColumnDefinition {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `FTS4ColumnDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension FTS4ColumnDefinition: Sendable { }
|
||||
|
||||
extension Database {
|
||||
/// Deletes the synchronization triggers for a synchronized FTS4 table.
|
||||
///
|
||||
|
||||
+11
-1
@@ -44,7 +44,7 @@ public struct FTS5 {
|
||||
/// tokenizer argument.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#unicode61_tokenizer>
|
||||
public enum Diacritics {
|
||||
public enum Diacritics: Sendable {
|
||||
/// Do not remove diacritics from Latin script characters. This
|
||||
/// option matches the raw "remove_diacritics=0" tokenizer argument.
|
||||
case keep
|
||||
@@ -492,6 +492,11 @@ public final class FTS5TableDefinition {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `FTS5TableDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension FTS5TableDefinition: Sendable { }
|
||||
|
||||
/// Describes a column in an ``FTS5`` virtual table.
|
||||
///
|
||||
/// You get instances of `FTS5ColumnDefinition` when you create an ``FTS5``
|
||||
@@ -534,6 +539,11 @@ public final class FTS5ColumnDefinition {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `FTS5ColumnDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension FTS5ColumnDefinition: Sendable { }
|
||||
|
||||
extension Column {
|
||||
/// The ``FTS5`` rank column.
|
||||
public static let rank = Column("rank")
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
/// - ``init(matchingAnyTokenIn:)``
|
||||
/// - ``init(matchingPhrase:)``
|
||||
/// - ``init(matchingPrefixPhrase:)``
|
||||
public struct FTS5Pattern {
|
||||
public struct FTS5Pattern: Sendable {
|
||||
|
||||
/// The raw pattern string.
|
||||
///
|
||||
|
||||
@@ -16,7 +16,7 @@ public typealias FTS5TokenCallback = @convention(c) (
|
||||
/// The reason why FTS5 is requesting tokenization.
|
||||
///
|
||||
/// See the `FTS5_TOKENIZE_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
|
||||
public struct FTS5Tokenization: OptionSet {
|
||||
public struct FTS5Tokenization: OptionSet, Sendable {
|
||||
public let rawValue: CInt
|
||||
|
||||
public init(rawValue: CInt) {
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
/// ### Instantiating Tokenizers
|
||||
///
|
||||
/// - ``Database/makeTokenizer(_:)``
|
||||
public struct FTS5TokenizerDescriptor {
|
||||
public struct FTS5TokenizerDescriptor: Sendable {
|
||||
/// The tokenizer components.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -4,7 +4,7 @@ import Foundation
|
||||
/// Flags that tell SQLite how to register a token.
|
||||
///
|
||||
/// See the `FTS5_TOKEN_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
|
||||
public struct FTS5TokenFlags: OptionSet {
|
||||
public struct FTS5TokenFlags: OptionSet, Sendable {
|
||||
public let rawValue: CInt
|
||||
|
||||
public init(rawValue: CInt) {
|
||||
|
||||
@@ -73,7 +73,7 @@
|
||||
/// > .fetchAll(db)
|
||||
/// > }
|
||||
/// > ```
|
||||
public struct JSONColumn: ColumnExpression, SQLJSONExpressible {
|
||||
public struct JSONColumn: ColumnExpression, SQLJSONExpressible, Sendable {
|
||||
public var name: String
|
||||
|
||||
/// Creates a `JSONColumn` given its name.
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -42,7 +42,7 @@ import Foundation
|
||||
/// - ``hasCompletedMigrations(_:)``
|
||||
public struct DatabaseMigrator {
|
||||
/// Controls how a migration handle foreign keys constraints.
|
||||
public enum ForeignKeyChecks {
|
||||
public enum ForeignKeyChecks: Sendable {
|
||||
/// The migration runs with disabled foreign keys.
|
||||
///
|
||||
/// Foreign keys are checked right before changes are committed on disk,
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSPrivacyTracking</key>
|
||||
<false/>
|
||||
<key>NSPrivacyCollectedDataTypes</key>
|
||||
<array/>
|
||||
<key>NSPrivacyTrackingDomains</key>
|
||||
<array/>
|
||||
<key>NSPrivacyAccessedAPITypes</key>
|
||||
<array/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -80,7 +80,7 @@
|
||||
/// using: Book.translatorForeignKey)
|
||||
/// }
|
||||
/// ```
|
||||
public struct ForeignKey: Equatable {
|
||||
public struct ForeignKey: Equatable, Sendable {
|
||||
var originColumns: [String]
|
||||
var destinationColumns: [String]?
|
||||
|
||||
|
||||
@@ -366,6 +366,7 @@ extension AssociationToMany {
|
||||
/// ### Top-Level Functions
|
||||
///
|
||||
/// - ``abs(_:)-43n8v``
|
||||
/// - ``cast(_:as:)-63ttx``
|
||||
/// - ``length(_:)-9dr2v``
|
||||
public struct AssociationAggregate<RowDecoder> {
|
||||
fileprivate let preparation: AssociationAggregatePreparation<RowDecoder>
|
||||
@@ -835,7 +836,7 @@ extension AssociationAggregate {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - IFNULL(...)
|
||||
// MARK: - Functions
|
||||
|
||||
extension AssociationAggregate {
|
||||
/// The `IFNULL` SQL function.
|
||||
@@ -854,8 +855,6 @@ extension AssociationAggregate {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ABS(...)
|
||||
|
||||
/// The `ABS` SQL function.
|
||||
public func abs<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
@@ -863,7 +862,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>)
|
||||
|
||||
@@ -61,6 +61,7 @@
|
||||
/// ### Batch Delete
|
||||
///
|
||||
/// - ``deleteAll(_:)``
|
||||
/// - ``deleteAndFetchIds(_:)``
|
||||
/// - ``deleteAndFetchCursor(_:)``
|
||||
/// - ``deleteAndFetchAll(_:)``
|
||||
/// - ``deleteAndFetchSet(_:)``
|
||||
@@ -528,7 +529,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter selection: The returned columns (must not be empty).
|
||||
@@ -561,7 +562,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A ``RecordCursor`` over the deleted records.
|
||||
@@ -588,7 +589,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of deleted records.
|
||||
@@ -614,7 +615,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of deleted records.
|
||||
@@ -625,6 +626,41 @@ extension QueryInterfaceRequest {
|
||||
{
|
||||
try Set(deleteAndFetchCursor(db))
|
||||
}
|
||||
|
||||
/// Executes a `DELETE RETURNING` statement and returns the set of
|
||||
/// deleted ids.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Fetch the ids of deleted players
|
||||
/// // DELETE FROM player RETURNING id
|
||||
/// let request = Player.all()
|
||||
/// let deletedPlayerIds = try request.deleteAndFetchIds(db)
|
||||
/// ```
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of deleted ids.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) // Identifiable
|
||||
public func deleteAndFetchIds(_ db: Database)
|
||||
throws -> Set<RowDecoder.ID>
|
||||
where RowDecoder: TableRecord & Identifiable,
|
||||
RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
let primaryKey = try db.primaryKey(RowDecoder.databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"Fetching id requires a single-column primary key in the table \(databaseTableName)")
|
||||
|
||||
let statement = try deleteAndFetchStatement(db, selection: [Column(primaryKey.columns[0])])
|
||||
|
||||
return try RowDecoder.ID.fetchSet(statement)
|
||||
}
|
||||
#else
|
||||
/// Returns a `DELETE RETURNING` prepared statement.
|
||||
///
|
||||
@@ -640,7 +676,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter selection: The returned columns (must not be empty).
|
||||
@@ -674,7 +710,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A ``RecordCursor`` over the deleted records.
|
||||
@@ -702,7 +738,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of deleted records.
|
||||
@@ -729,7 +765,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of deleted records.
|
||||
@@ -741,6 +777,41 @@ extension QueryInterfaceRequest {
|
||||
{
|
||||
try Set(deleteAndFetchCursor(db))
|
||||
}
|
||||
|
||||
/// Executes a `DELETE RETURNING` statement and returns the set of
|
||||
/// deleted ids.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Fetch the ids of deleted players
|
||||
/// // DELETE FROM player RETURNING id
|
||||
/// let request = Player.all()
|
||||
/// let deletedPlayerIds = try request.deleteAndFetchIds(db)
|
||||
/// ```
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of deleted ids.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func deleteAndFetchIds(_ db: Database)
|
||||
throws -> Set<RowDecoder.ID>
|
||||
where RowDecoder: TableRecord & Identifiable,
|
||||
RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
let primaryKey = try db.primaryKey(RowDecoder.databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"Fetching id requires a single-column primary key in the table \(databaseTableName)")
|
||||
|
||||
let statement = try deleteAndFetchStatement(db, selection: [Column(primaryKey.columns[0])])
|
||||
|
||||
return try RowDecoder.ID.fetchSet(statement)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -844,7 +915,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
@@ -893,7 +964,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
@@ -930,7 +1001,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
@@ -962,7 +1033,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
@@ -996,7 +1067,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
@@ -1046,7 +1117,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
@@ -1084,7 +1155,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
@@ -1117,7 +1188,7 @@ extension QueryInterfaceRequest {
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
|
||||
@@ -92,7 +92,7 @@ extension ColumnExpression where Self == Column {
|
||||
///
|
||||
/// - ``init(_:)-5grmu``
|
||||
/// - ``init(_:)-7xc4z``
|
||||
public struct Column {
|
||||
public struct Column: Sendable {
|
||||
/// The hidden rowID column.
|
||||
public static let rowID = Column("rowid")
|
||||
|
||||
|
||||
@@ -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,
|
||||
@@ -315,7 +323,7 @@ public struct SQLExpression {
|
||||
/// 1000.databaseValue]
|
||||
/// let request = Player.select(values.joined(operator: .add))
|
||||
/// ```
|
||||
public struct AssociativeBinaryOperator: Hashable {
|
||||
public struct AssociativeBinaryOperator: Hashable, Sendable {
|
||||
/// The SQL operator
|
||||
let sql: String
|
||||
|
||||
@@ -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
|
||||
@@ -2146,6 +2167,7 @@ extension SQLExpressible where Self == Column {
|
||||
/// - ``average(_:)``
|
||||
/// - ``average(_:filter:)``
|
||||
/// - ``capitalized``
|
||||
/// - ``cast(_:as:)-1dmu3``
|
||||
/// - ``count(_:)``
|
||||
/// - ``count(distinct:)``
|
||||
/// - ``dateTime(_:_:)``
|
||||
|
||||
@@ -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:
|
||||
@@ -408,7 +422,7 @@ extension SQLSpecificExpressible {
|
||||
/// A date modifier for SQLite date functions.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_datefunc.html>
|
||||
public enum SQLDateModifier: SQLSpecificExpressible {
|
||||
public enum SQLDateModifier: SQLSpecificExpressible, Sendable {
|
||||
/// Adds the specified amount of seconds
|
||||
case second(Double)
|
||||
|
||||
|
||||
@@ -171,7 +171,7 @@ struct SQLRelation {
|
||||
var source: SQLSource
|
||||
var selectionPromise: DatabasePromise<[SQLSelection]>
|
||||
var filterPromise: DatabasePromise<SQLExpression>?
|
||||
var ordering: SQLRelation.Ordering = SQLRelation.Ordering()
|
||||
var ordering = SQLRelation.Ordering()
|
||||
var ctes: OrderedDictionary<String, SQLCTE> = [:] // See also `allCTEs`
|
||||
var children: OrderedDictionary<String, Child> = [:]
|
||||
|
||||
|
||||
@@ -324,7 +324,7 @@ extension SQLSelection: SQLSelectable {
|
||||
/// let players = try Player.select(AllColumns()).fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
public struct AllColumns {
|
||||
public struct AllColumns: Sendable {
|
||||
/// The `*` selection.
|
||||
public init() { }
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@
|
||||
/// ### Database Observation Support
|
||||
///
|
||||
/// - ``databaseRegion(_:)``
|
||||
public struct Table<RowDecoder> {
|
||||
public struct Table<RowDecoder>: Sendable {
|
||||
/// The table name.
|
||||
public var tableName: String
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ public final class ColumnDefinition {
|
||||
/// The kind of a generated column.
|
||||
///
|
||||
/// Related SQLite documentation: <https://sqlite.org/gencol.html#virtual_versus_stored_columns>
|
||||
public enum GeneratedColumnQualification {
|
||||
public enum GeneratedColumnQualification: Sendable {
|
||||
/// A `VIRTUAL` generated column.
|
||||
case virtual
|
||||
/// A `STORED` generated column.
|
||||
@@ -565,3 +565,8 @@ public final class ColumnDefinition {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `ColumnDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension ColumnDefinition: Sendable { }
|
||||
@@ -681,7 +681,7 @@ extension Database {
|
||||
}
|
||||
|
||||
/// View creation options
|
||||
public struct ViewOptions: OptionSet {
|
||||
public struct ViewOptions: OptionSet, Sendable {
|
||||
public let rawValue: Int
|
||||
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
|
||||
@@ -104,3 +104,8 @@ public final class ForeignKeyDefinition {
|
||||
throw DatabaseError.noSuchTable(name)
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `ForeignKeyDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension ForeignKeyDefinition: Sendable { }
|
||||
@@ -7,7 +7,7 @@ struct IndexDefinition {
|
||||
}
|
||||
|
||||
/// Index creation options
|
||||
public struct IndexOptions: OptionSet {
|
||||
public struct IndexOptions: OptionSet, Sendable {
|
||||
public let rawValue: Int
|
||||
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
|
||||
@@ -161,3 +161,8 @@ public final class TableAlteration {
|
||||
alterations.append(.drop(name))
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `TableAlteration` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension TableAlteration: Sendable { }
|
||||
@@ -1,5 +1,5 @@
|
||||
/// Table creation options.
|
||||
public struct TableOptions: OptionSet {
|
||||
public struct TableOptions: OptionSet, Sendable {
|
||||
public let rawValue: Int
|
||||
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
@@ -753,3 +753,8 @@ public final class TableDefinition {
|
||||
literalConstraints.append(literal)
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `TableDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension TableDefinition: Sendable { }
|
||||
@@ -34,18 +34,7 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
|
||||
}
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
// @itaiferber on https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/11
|
||||
//
|
||||
// > Encoding a value into a single-value container is equivalent to
|
||||
// > encoding the value directly into the encoder, with the primary
|
||||
// > difference being the above: encoding into the encoder writes the
|
||||
// > contents of a type into the encoder, while encoding to a
|
||||
// > single-value container gives the encoder a chance to intercept the
|
||||
// > type as a whole.
|
||||
//
|
||||
// Wait for somebody hitting this fatal error so that we can write a
|
||||
// meaningful regression test.
|
||||
fatalError("single value encoding is not supported")
|
||||
self
|
||||
}
|
||||
|
||||
private struct KeyedContainer<Key: CodingKey>: KeyedEncodingContainerProtocol {
|
||||
@@ -169,6 +158,80 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
|
||||
}
|
||||
}
|
||||
|
||||
extension RecordEncoder: SingleValueEncodingContainer {
|
||||
private func unsupportedSingleValueEncoding() {
|
||||
fatalError("Can't encode a single value in a database row.")
|
||||
}
|
||||
|
||||
func encodeNil() throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode(_ value: Bool) throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode(_ value: String) throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode(_ value: Double) throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode(_ value: Float) throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode(_ value: Int) throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode(_ value: Int8) throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode(_ value: Int16) throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode(_ value: Int32) throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode(_ value: Int64) throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode(_ value: UInt) throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode(_ value: UInt8) throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode(_ value: UInt16) throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode(_ value: UInt32) throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode(_ value: UInt64) throws {
|
||||
unsupportedSingleValueEncoding()
|
||||
}
|
||||
|
||||
func encode<T>(_ value: T) throws where T: Encodable {
|
||||
if let record = value as? EncodableRecord {
|
||||
try record.encode(to: &_persistenceContainer)
|
||||
} else {
|
||||
try value.encode(to: self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ColumnEncoder
|
||||
|
||||
/// The encoder that encodes into a database column
|
||||
|
||||
@@ -585,7 +585,7 @@ public enum DatabaseDateEncodingStrategy {
|
||||
/// var uuid: UUID
|
||||
/// }
|
||||
/// ```
|
||||
public enum DatabaseUUIDEncodingStrategy {
|
||||
public enum DatabaseUUIDEncodingStrategy: Sendable {
|
||||
/// The strategy that uses formatting from the UUID type.
|
||||
///
|
||||
/// It encodes UUIDs as 16-bytes data blobs.
|
||||
|
||||
@@ -7,6 +7,7 @@ extension FetchableRecord where Self: Decodable {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO GRDB7: make it a final class, and Sendable.
|
||||
/// An object that decodes fetchable records from database rows.
|
||||
///
|
||||
/// The example below shows how to decode an instance of a simple `Player`
|
||||
@@ -107,8 +108,12 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
guard let key = codingPath.last else {
|
||||
// Decoding an array of scalars from rows: pick the first column
|
||||
return ColumnDecoder<R>(row: row, columnIndex: 0, codingPath: codingPath)
|
||||
// Not yet sure what we are decoding, this will be decided in the SingleValueDecodingContainer functions.
|
||||
// For decoding an array of scalars (in case of prefetched rows) we pick the first column.
|
||||
return SingleValueRowDecoder(
|
||||
columnDecoder: ColumnDecoder<R>(row: row, columnIndex: 0, codingPath: codingPath),
|
||||
columnDecodingStrategy: columnDecodingStrategy
|
||||
)
|
||||
}
|
||||
guard let index = row.index(forColumn: key.stringValue) else {
|
||||
// Don't use DecodingError.keyNotFound:
|
||||
@@ -146,6 +151,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)
|
||||
@@ -173,15 +179,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
|
||||
}
|
||||
|
||||
@@ -334,7 +350,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
|
||||
// Unknown key
|
||||
//
|
||||
// Should be throw an error? Well... The use case is the following:
|
||||
// Should we throw an error? Well... The use case is the following:
|
||||
//
|
||||
// // SELECT book.*, author.* FROM book
|
||||
// // JOIN author ON author.id = book.authorId
|
||||
@@ -375,7 +391,37 @@ 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 {
|
||||
@@ -445,6 +491,50 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
}
|
||||
}
|
||||
|
||||
private struct SingleValueRowDecoder<R: FetchableRecord>: SingleValueDecodingContainer {
|
||||
var columnDecoder: ColumnDecoder<R>
|
||||
var columnDecodingStrategy: DatabaseColumnDecodingStrategy
|
||||
let codingPath: [any CodingKey] = []
|
||||
|
||||
func decodeNil() -> Bool { columnDecoder.decodeNil() }
|
||||
func decode(_ type: Bool.Type) throws -> Bool { try columnDecoder.decode(type) }
|
||||
func decode(_ type: String.Type) throws -> String { try columnDecoder.decode(type) }
|
||||
func decode(_ type: Double.Type) throws -> Double { try columnDecoder.decode(type) }
|
||||
func decode(_ type: Float.Type) throws -> Float { try columnDecoder.decode(type) }
|
||||
func decode(_ type: Int.Type) throws -> Int { try columnDecoder.decode(type) }
|
||||
func decode(_ type: Int8.Type) throws -> Int8 { try columnDecoder.decode(type) }
|
||||
func decode(_ type: Int16.Type) throws -> Int16 { try columnDecoder.decode(type) }
|
||||
func decode(_ type: Int32.Type) throws -> Int32 { try columnDecoder.decode(type) }
|
||||
func decode(_ type: Int64.Type) throws -> Int64 { try columnDecoder.decode(type) }
|
||||
#if compiler(>=6)
|
||||
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
|
||||
func decode(_ type: Int128.Type) throws -> Int128 { try columnDecoder.decode(type) }
|
||||
#endif
|
||||
func decode(_ type: UInt.Type) throws -> UInt { try columnDecoder.decode(type) }
|
||||
func decode(_ type: UInt8.Type) throws -> UInt8 { try columnDecoder.decode(type) }
|
||||
func decode(_ type: UInt16.Type) throws -> UInt16 { try columnDecoder.decode(type) }
|
||||
func decode(_ type: UInt32.Type) throws -> UInt32 { try columnDecoder.decode(type) }
|
||||
func decode(_ type: UInt64.Type) throws -> UInt64 { try columnDecoder.decode(type) }
|
||||
#if compiler(>=6)
|
||||
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
|
||||
func decode(_ type: UInt128.Type) throws -> UInt128 { try columnDecoder.decode(type) }
|
||||
#endif
|
||||
|
||||
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
|
||||
if let type = T.self as? any FetchableRecord.Type {
|
||||
// Prefer FetchableRecord decoding over Decodable.
|
||||
return try type.init(row: columnDecoder.row) as! T
|
||||
} else {
|
||||
let decoder = _RowDecoder<R>(
|
||||
row: columnDecoder.row,
|
||||
codingPath: [],
|
||||
columnDecodingStrategy: columnDecodingStrategy
|
||||
)
|
||||
return try T(from: decoder)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - PrefetchedRowsDecoder
|
||||
|
||||
private struct PrefetchedRowsDecoder<R: FetchableRecord>: Decoder {
|
||||
@@ -590,9 +680,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(
|
||||
@@ -689,6 +789,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),
|
||||
|
||||
@@ -854,6 +854,11 @@ public final class RecordCursor<Record: FetchableRecord>: DatabaseCursor {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: database cursors must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension RecordCursor: Sendable { }
|
||||
|
||||
// MARK: - DatabaseDataDecodingStrategy
|
||||
|
||||
/// `DatabaseDataDecodingStrategy` specifies how `FetchableRecord` types that
|
||||
|
||||
@@ -348,7 +348,7 @@ extension MutablePersistableRecord {
|
||||
/// See `MutablePersistableRecord.persistenceConflictPolicy`.
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_conflict.html>
|
||||
public struct PersistenceConflictPolicy {
|
||||
public struct PersistenceConflictPolicy: Sendable {
|
||||
/// The conflict resolution algorithm for insertions
|
||||
public let conflictResolutionForInsert: Database.ConflictResolution
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ extension String {
|
||||
/// A type that controls GRDB string inflections.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
public struct Inflections {
|
||||
public struct Inflections: Sendable {
|
||||
private var pluralizeRules: [(NSRegularExpression, String)] = []
|
||||
private var singularizeRules: [(NSRegularExpression, String)] = []
|
||||
private var uncountablesRegularExpressions: [String: NSRegularExpression] = [:]
|
||||
|
||||
@@ -865,6 +865,8 @@ extension ValueConcurrentObserver: DatabaseCancellable {
|
||||
// Notify cancellation
|
||||
let (events, dbPool): (ValueObservationEvents?, DatabasePool?) = lock.synchronized {
|
||||
let events = notificationCallbacks?.events
|
||||
// Set callbacks to nil so that we can't notify anything after
|
||||
// the cancellation.
|
||||
notificationCallbacks = nil
|
||||
return (events, databaseAccess?.dbPool)
|
||||
}
|
||||
|
||||
@@ -448,6 +448,8 @@ extension ValueWriteOnlyObserver: DatabaseCancellable {
|
||||
// Notify cancellation
|
||||
let (events, writer) = lock.synchronized {
|
||||
let events = notificationCallbacks?.events
|
||||
// Set callbacks to nil so that we can't notify anything after
|
||||
// the cancellation.
|
||||
notificationCallbacks = nil
|
||||
return (events, databaseAccess?.writer)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
/// The extent of the shared subscription to a ``SharedValueObservation``.
|
||||
public enum SharedValueObservationExtent {
|
||||
public enum SharedValueObservationExtent: Sendable {
|
||||
/// The ``SharedValueObservation`` starts a single database observation,
|
||||
/// which stops when the `SharedValueObservation` is deallocated and all
|
||||
/// subscriptions terminated.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -76,7 +80,7 @@ extension ValueObservationScheduler where Self == AsyncValueObservationScheduler
|
||||
/// A scheduler that notifies all values on the main `DispatchQueue`. The
|
||||
/// first value is immediately notified when the `ValueObservation`
|
||||
/// is started.
|
||||
public struct ImmediateValueObservationScheduler: ValueObservationScheduler {
|
||||
public struct ImmediateValueObservationScheduler: ValueObservationScheduler, Sendable {
|
||||
public init() { }
|
||||
|
||||
public func immediateInitialValue() -> Bool {
|
||||
|
||||
@@ -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 */; };
|
||||
@@ -332,6 +333,7 @@
|
||||
56FF45431D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */; };
|
||||
56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; };
|
||||
6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; };
|
||||
648704BA2B8261070036480B /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 648704B82B8261070036480B /* PrivacyInfo.xcprivacy */; };
|
||||
EED476F21CFD17270026A4EC /* GRDBCustomSQLite-USER.h in Headers */ = {isa = PBXBuildFile; fileRef = EED476F11CFD16FF0026A4EC /* GRDBCustomSQLite-USER.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
F3BA80661CFB2E55003DC1BA /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; };
|
||||
F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238711B9C75030082EB20 /* Database.swift */; };
|
||||
@@ -782,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>"; };
|
||||
@@ -859,6 +862,7 @@
|
||||
56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = "<group>"; };
|
||||
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
|
||||
6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = "<group>"; };
|
||||
648704B82B8261070036480B /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
|
||||
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = "<group>"; };
|
||||
DC3773F719C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
DC3773F819C8CBB3004FCF85 /* GRDB.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GRDB.h; sourceTree = "<group>"; };
|
||||
@@ -1556,6 +1560,7 @@
|
||||
children = (
|
||||
564E73E7203DA278000C443C /* JoinSupportTests.swift */,
|
||||
5616B4FE28B5F5490052017E /* SingletonRecordTest.swift */,
|
||||
56B6AB072BD3DCE0009A0B71 /* SingletonUserDefaultsTest.swift */,
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */,
|
||||
560B3FA41C19DFF800C58EC7 /* PersistableRecord */,
|
||||
56176C9E1EACEDF9000F3F2B /* Record */,
|
||||
@@ -1743,6 +1748,7 @@
|
||||
children = (
|
||||
56A2FA3724424F4200E97D23 /* Export.swift */,
|
||||
566DDE11288D76400000DCFB /* Fixits.swift */,
|
||||
648704B82B8261070036480B /* PrivacyInfo.xcprivacy */,
|
||||
56A2386F1B9C75030082EB20 /* Core */,
|
||||
567B5BED2AD3285100629622 /* Dump */,
|
||||
5698AC291D9E5A480056AF8C /* FTS */,
|
||||
@@ -1919,6 +1925,7 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
648704BA2B8261070036480B /* PrivacyInfo.xcprivacy in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -2326,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 */,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Copyright (C) 2015-2023 Gwendal Roué
|
||||
Copyright (C) 2015-2024 Gwendal Roué
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ test_framework_GRDB: test_framework_GRDBOSX test_framework_GRDBiOS test_framewor
|
||||
test_framework_GRDBCustom: test_framework_GRDBCustomSQLiteOSX test_framework_GRDBCustomSQLiteiOS
|
||||
test_framework_SQLCipher: test_framework_SQLCipher3 test_framework_SQLCipher3Encrypted test_framework_SQLCipher4 test_framework_SQLCipher4Encrypted
|
||||
test_archive: test_universal_xcframework
|
||||
test_install: test_install_manual test_install_SPM test_install_customSQLite test_install_GRDB_CocoaPods test_CocoaPodsLint
|
||||
test_install: test_install_manual test_install_SPM test_install_customSQLite test_install_GRDB_CocoaPods
|
||||
test_CocoaPodsLint: test_CocoaPodsLint_GRDB
|
||||
test_demo_apps: test_GRDBDemoiOS test_GRDBCombineDemo test_GRDBAsyncDemo
|
||||
|
||||
|
||||
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user