mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-01 04:38:44 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
389b14ede0 |
No files matched your search
+1
-53
@@ -7,10 +7,6 @@ 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)
|
||||
@@ -127,60 +123,12 @@ 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
|
||||
## Next Release
|
||||
|
||||
- **New**: [#1503](https://github.com/groue/GRDB.swift/pull/1503) by [@simba909](https://github.com/simba909): Conform Database.ColumnType to Sendable
|
||||
- **New**: [#1510](https://github.com/groue/GRDB.swift/pull/1510) by [@groue](https://github.com/groue): Add Sendable conformances and unavailabilities
|
||||
- **New**: [#1511](https://github.com/groue/GRDB.swift/pull/1511) by [@groue](https://github.com/groue): Database schema dump
|
||||
- **New**: [#1515](https://github.com/groue/GRDB.swift/pull/1515) by [@groue](https://github.com/groue): Support for the CAST SQLite function
|
||||
- **Fixed**: [#1508](https://github.com/groue/GRDB.swift/pull/1508) by [@groue](https://github.com/groue): Fix ValueObservation mishandling of database schema modification
|
||||
- **Fixed**: [#1512](https://github.com/groue/GRDB.swift/issues/1512): Decoding errors are now correctly reported when decoding NULL into a non-optional property of type `Data` or `Date`.
|
||||
|
||||
## 6.25.0
|
||||
|
||||
|
||||
@@ -2661,7 +2661,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0)
|
||||
```
|
||||
|
||||
- SQL functions `ABS`, `CAST`, and `LENGTH` are available as the `abs`, `cast`, and `length` Swift functions:
|
||||
- SQL functions `ABS` and `LENGTH` are available as the `abs` 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,7 +354,6 @@
|
||||
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",
|
||||
@@ -374,7 +373,6 @@
|
||||
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",
|
||||
@@ -514,7 +512,7 @@
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBAsyncDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -536,7 +534,7 @@
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBAsyncDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.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" : "a6c46dd38ecf11a5c37732870dc03a384d582fba",
|
||||
"version" : "0.9.0"
|
||||
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
|
||||
"version" : "0.6.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
@@ -5,12 +5,17 @@ import SwiftUI
|
||||
struct GRDBAsyncDemoApp: App {
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
AppView().appDatabase(.shared)
|
||||
AppView().environment(\.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() }
|
||||
@@ -23,10 +28,13 @@ extension EnvironmentValues {
|
||||
}
|
||||
}
|
||||
|
||||
extension View {
|
||||
func appDatabase(_ appDatabase: AppDatabase) -> some View {
|
||||
self
|
||||
.environment(\.appDatabase, appDatabase)
|
||||
.databaseContext(.readOnly { appDatabase.reader })
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import Combine
|
||||
import GRDB
|
||||
import GRDBQuery
|
||||
|
||||
@@ -13,18 +14,37 @@ import GRDBQuery
|
||||
/// List(players) { player in ... )
|
||||
/// }
|
||||
/// }
|
||||
struct PlayerRequest: ValueObservationQueryable {
|
||||
struct PlayerRequest: Queryable {
|
||||
enum Ordering {
|
||||
case byScore
|
||||
case byName
|
||||
}
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
/// The ordering used by the player request.
|
||||
var ordering: Ordering
|
||||
|
||||
func fetch(_ db: Database) throws -> [Player] {
|
||||
// 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] {
|
||||
switch ordering {
|
||||
case .byScore:
|
||||
return try Player.all().orderedByScore().fetchAll(db)
|
||||
|
||||
@@ -43,7 +43,7 @@ struct AppView: View {
|
||||
stopEditing()
|
||||
}))
|
||||
.toolbar { toolbarContent }
|
||||
.onChange(of: players) {
|
||||
.onChange(of: players) { players in
|
||||
if players.isEmpty {
|
||||
stopEditing()
|
||||
}
|
||||
@@ -141,14 +141,14 @@ private struct ToggleOrderingButton: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview("Empty") {
|
||||
// Preview the default, empty database
|
||||
AppView()
|
||||
}
|
||||
|
||||
#Preview("Populated") {
|
||||
// Preview a database of random players
|
||||
AppView().appDatabase(.random())
|
||||
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())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,8 +43,8 @@ struct PlayerCreationView: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
PlayerCreationView()
|
||||
struct PlayerCreationSheet_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
PlayerCreationView()
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ struct PlayerEditionView: View {
|
||||
|
||||
var body: some View {
|
||||
PlayerFormView(form: $form)
|
||||
.onChange(of: isPresented) {
|
||||
.onChange(of: isPresented) { isPresented in
|
||||
// Save when back button is pressed
|
||||
if !isPresented {
|
||||
Task {
|
||||
@@ -30,11 +30,11 @@ struct PlayerEditionView: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.makeRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
struct PlayerEditionView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.makeRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,16 +33,15 @@ extension PlayerForm {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview("Empty") {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: "",
|
||||
score: "")))
|
||||
}
|
||||
|
||||
#Preview("Prefilled") {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: Player.randomName(),
|
||||
score: "\(Player.randomScore())")))
|
||||
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())")))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,14 +46,14 @@ private struct PlayerRow: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
NavigationView {
|
||||
PlayerList(players: [
|
||||
Player(id: 1, name: "Arthur", score: 100),
|
||||
Player(id: 2, name: "Barbara", score: 1000),
|
||||
])
|
||||
.navigationTitle("Preview")
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.fetch)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
|
||||
// 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.fetch)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
|
||||
// Then the players are the two players ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player1])
|
||||
|
||||
@@ -13,9 +13,8 @@ The topics covered in this demo are:
|
||||
|
||||
- How to setup a database in an iOS app.
|
||||
- How to define a simple [Codable Record](../../../README.md#codable-records).
|
||||
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) Combine publishers.
|
||||
- How to track database changes and animate a SwiftUI List with an async sequence built from [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
|
||||
- How to apply the recommendations of [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,7 +354,6 @@
|
||||
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",
|
||||
@@ -374,7 +373,6 @@
|
||||
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",
|
||||
@@ -514,7 +512,6 @@
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -536,7 +533,6 @@
|
||||
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" : "a6c46dd38ecf11a5c37732870dc03a384d582fba",
|
||||
"version" : "0.9.0"
|
||||
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
|
||||
"version" : "0.6.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
@@ -5,12 +5,17 @@ import SwiftUI
|
||||
struct GRDBCombineDemoApp: App {
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
AppView().appDatabase(.shared)
|
||||
AppView().environment(\.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() }
|
||||
@@ -23,10 +28,13 @@ extension EnvironmentValues {
|
||||
}
|
||||
}
|
||||
|
||||
extension View {
|
||||
func appDatabase(_ appDatabase: AppDatabase) -> some View {
|
||||
self
|
||||
.environment(\.appDatabase, appDatabase)
|
||||
.databaseContext(.readOnly { appDatabase.reader })
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import Combine
|
||||
import GRDB
|
||||
import GRDBQuery
|
||||
|
||||
@@ -13,18 +14,37 @@ import GRDBQuery
|
||||
/// List(players) { player in ... )
|
||||
/// }
|
||||
/// }
|
||||
struct PlayerRequest: ValueObservationQueryable {
|
||||
struct PlayerRequest: Queryable {
|
||||
enum Ordering {
|
||||
case byScore
|
||||
case byName
|
||||
}
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
/// The ordering used by the player request.
|
||||
var ordering: Ordering
|
||||
|
||||
func fetch(_ db: Database) throws -> [Player] {
|
||||
// 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] {
|
||||
switch ordering {
|
||||
case .byScore:
|
||||
return try Player.all().orderedByScore().fetchAll(db)
|
||||
|
||||
@@ -43,7 +43,7 @@ struct AppView: View {
|
||||
stopEditing()
|
||||
}))
|
||||
.toolbar { toolbarContent }
|
||||
.onChange(of: players) {
|
||||
.onChange(of: players) { players in
|
||||
if players.isEmpty {
|
||||
stopEditing()
|
||||
}
|
||||
@@ -132,14 +132,14 @@ private struct ToggleOrderingButton: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview("Empty") {
|
||||
// Preview the default, empty database
|
||||
AppView()
|
||||
}
|
||||
|
||||
#Preview("Populated") {
|
||||
// Preview a database of random players
|
||||
AppView().appDatabase(.random())
|
||||
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())
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -43,8 +43,8 @@ struct PlayerCreationView: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
PlayerCreationView()
|
||||
struct PlayerCreationSheet_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
PlayerCreationView()
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -15,7 +15,7 @@ struct PlayerEditionView: View {
|
||||
|
||||
var body: some View {
|
||||
PlayerFormView(form: $form)
|
||||
.onChange(of: isPresented) {
|
||||
.onChange(of: isPresented) { isPresented in
|
||||
// Save when back button is pressed
|
||||
if !isPresented {
|
||||
var savedPlayer = player
|
||||
@@ -28,11 +28,11 @@ struct PlayerEditionView: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.makeRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
struct PlayerEditionView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.makeRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,16 +33,15 @@ extension PlayerForm {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview("Empty") {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: "",
|
||||
score: "")))
|
||||
}
|
||||
|
||||
#Preview("Prefilled") {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: Player.randomName(),
|
||||
score: "\(Player.randomScore())")))
|
||||
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())")))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,14 +44,14 @@ private struct PlayerRow: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
NavigationView {
|
||||
PlayerList(players: [
|
||||
Player(id: 1, name: "Arthur", score: 100),
|
||||
Player(id: 2, name: "Barbara", score: 1000),
|
||||
])
|
||||
.navigationTitle("Preview")
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
+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.fetch)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
|
||||
// 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.fetch)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
|
||||
// Then the players are the two players ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player1])
|
||||
|
||||
@@ -588,7 +588,6 @@
|
||||
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",
|
||||
@@ -615,7 +614,6 @@
|
||||
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",
|
||||
@@ -830,7 +828,6 @@
|
||||
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",
|
||||
@@ -848,7 +845,6 @@
|
||||
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,10 +18,8 @@ To release a new GRDB version:
|
||||
- README.md
|
||||
- Support/Info.plist
|
||||
- Commit and tag
|
||||
- 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
|
||||
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the master & development branch
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- Update [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.29.3'
|
||||
s.version = '6.25.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -276,7 +276,6 @@
|
||||
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 */; };
|
||||
@@ -771,7 +770,6 @@
|
||||
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>"; };
|
||||
@@ -1554,7 +1552,6 @@
|
||||
children = (
|
||||
564E73DE203D50B9000C443C /* JoinSupportTests.swift */,
|
||||
5616B4FA28B5F5220052017E /* SingletonRecordTest.swift */,
|
||||
56B6AB052BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift */,
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */,
|
||||
560B3FA41C19DFF800C58EC7 /* PersistableRecord */,
|
||||
56176C9E1EACEDF9000F3F2B /* Record */,
|
||||
@@ -2089,7 +2086,6 @@
|
||||
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 */,
|
||||
|
||||
@@ -195,56 +195,6 @@ 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 {
|
||||
|
||||
+11
-44
@@ -115,7 +115,6 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``trace(options:_:)``
|
||||
/// - ``CheckpointMode``
|
||||
/// - ``DatabaseBackupProgress``
|
||||
/// - ``StorageClass``
|
||||
/// - ``TraceEvent``
|
||||
/// - ``TracingOptions``
|
||||
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
@@ -124,6 +123,8 @@ 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,11 +819,6 @@ 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
|
||||
@@ -834,9 +830,12 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This method has no effect on a `ValueObservation` created with
|
||||
/// ``ValueObservation/tracking(regions:fetch:)``. In the example below,
|
||||
/// only the `player` table is tracked:
|
||||
/// 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:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Observes the 'player' table only
|
||||
@@ -1575,9 +1574,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// Frees as much memory as possible.
|
||||
public func releaseMemory() {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
if let sqliteConnection {
|
||||
sqlite3_db_release_memory(sqliteConnection)
|
||||
}
|
||||
sqlite3_db_release_memory(sqliteConnection)
|
||||
schemaCache.clear()
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
@@ -1923,6 +1920,7 @@ extension Database {
|
||||
/// 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
|
||||
@@ -2007,32 +2005,6 @@ 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`
|
||||
@@ -2082,8 +2054,7 @@ extension Database {
|
||||
/// ```
|
||||
public var sql: String {
|
||||
if let unexpandedSQL {
|
||||
let sql = String(cString: unexpandedSQL)
|
||||
return sql.hasPrefix("--") ? sql : sql.trimmedSQLStatement
|
||||
return String(cString: unexpandedSQL).trimmedSQLStatement
|
||||
} else {
|
||||
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
}
|
||||
@@ -2101,10 +2072,6 @@ 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 ""
|
||||
}
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
#if canImport(string_h)
|
||||
import string_h
|
||||
#elseif os(Linux)
|
||||
#if os(Linux)
|
||||
import Glibc
|
||||
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
/// `StatementAuthorizer` provides information about compiled database
|
||||
|
||||
@@ -4,6 +4,7 @@ import Foundation
|
||||
|
||||
@usableFromInline
|
||||
struct SQLiteDateParser {
|
||||
// swiftlint:disable:next unneeded_synthesized_initializer
|
||||
@usableFromInline
|
||||
init() { }
|
||||
|
||||
|
||||
@@ -80,8 +80,6 @@ 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.
|
||||
@@ -119,45 +117,16 @@ 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
|
||||
// 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)
|
||||
}
|
||||
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. 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``.
|
||||
|
||||
The other built-in scheduler ``ValueObservationScheduler/async(onQueue:)`` asynchronously schedules values and errors on the dispatch queue of your choice.
|
||||
|
||||
## ValueObservation Sharing
|
||||
|
||||
@@ -268,7 +237,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 ``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.
|
||||
> Tip: When the observation tracks a constant database region, create an optimized observation with the ``trackingConstantRegion(_:)`` method. See the documentation of this method for more information about what constitutes a "constant region", and the nature of the optimization.
|
||||
|
||||
**Truncating WAL checkpoints impact ValueObservation.** Such checkpoints are performed with ``Database/checkpoint(_:on:)`` or [`PRAGMA wal_checkpoint`](https://www.sqlite.org/pragma.html#pragma_wal_checkpoint). When an observation is started on a ``DatabasePool``, from a database that has a missing or empty [wal file](https://www.sqlite.org/tempfiles.html#write_ahead_log_wal_files), the observation will always notify two values when it starts, even if the database content is not changed. This is a consequence of the impossibility to create the [wal snapshot](https://www.sqlite.org/c3ref/snapshot_get.html) needed for detecting that no changes were performed during the observation startup. If your application performs truncating checkpoints, you will avoid this behavior if you recreate a non-empty wal file before starting observations. To do so, perform any kind of no-op transaction (such a creating and dropping a dummy table).
|
||||
|
||||
|
||||
@@ -147,4 +147,5 @@ The `->` and `->>` SQL operators are available on the ``SQLJSONExpressible`` pro
|
||||
|
||||
### Validate JSON values at the SQL level
|
||||
|
||||
- ``Database/jsonErrorPosition(_:)``
|
||||
- ``Database/jsonIsValid(_:)``
|
||||
@@ -8,11 +8,9 @@ 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.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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).
|
||||
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.
|
||||
|
||||
## The Single-Row Table
|
||||
|
||||
@@ -22,43 +20,63 @@ 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
|
||||
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
|
||||
// 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("storedFlag", .boolean)
|
||||
// ... other columns
|
||||
}
|
||||
// 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
|
||||
}
|
||||
```
|
||||
|
||||
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:
|
||||
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
|
||||
// DO NOT hesitate requiring NOT NULL columns when the app requires it.
|
||||
// NOT 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 }
|
||||
|
||||
t.column("flag", .boolean).notNull() // required
|
||||
// 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 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -73,37 +91,7 @@ struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// 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
|
||||
// The configuration properties
|
||||
var flag: Bool
|
||||
// ... other properties
|
||||
}
|
||||
@@ -114,7 +102,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: nil)
|
||||
static let `default` = AppConfiguration(flag: false)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -141,7 +129,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 find(_ db: Database) throws -> AppConfiguration {
|
||||
static func fetch(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
@@ -152,7 +140,7 @@ And that's it! Now we can use our singleton record:
|
||||
```swift
|
||||
// READ
|
||||
let config = try dbQueue.read { db in
|
||||
try AppConfiguration.find(db)
|
||||
try AppConfiguration.fetch(db)
|
||||
}
|
||||
if config.flag {
|
||||
// ...
|
||||
@@ -160,19 +148,17 @@ if config.flag {
|
||||
|
||||
// WRITE
|
||||
try dbQueue.write { db in
|
||||
// Update the config in the database
|
||||
var config = try AppConfiguration.find(db)
|
||||
// Saves a new config in the database
|
||||
var config = try AppConfiguration.fetch(db)
|
||||
try config.updateChanges(db) {
|
||||
$0.flag = true
|
||||
}
|
||||
|
||||
// Other possible ways to save the config:
|
||||
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
|
||||
try config.save(db)
|
||||
try config.update(db)
|
||||
try config.insert(db)
|
||||
try config.upsert(db)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -186,13 +172,11 @@ 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
|
||||
// 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 single row guarantee
|
||||
t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("storedFlag", .boolean)
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
```
|
||||
@@ -208,26 +192,14 @@ struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// The stored properties
|
||||
private var storedFlag: Bool?
|
||||
// The configuration properties
|
||||
var flag: 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(storedFlag: nil)
|
||||
static let `default` = AppConfiguration(flag: false, ...)
|
||||
}
|
||||
|
||||
// Database Access
|
||||
@@ -242,7 +214,7 @@ extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func find(_ db: Database) throws -> AppConfiguration {
|
||||
static func fetch(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
|
||||
@@ -521,6 +521,21 @@ 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:
|
||||
|
||||
@@ -366,7 +366,6 @@ extension AssociationToMany {
|
||||
/// ### Top-Level Functions
|
||||
///
|
||||
/// - ``abs(_:)-43n8v``
|
||||
/// - ``cast(_:as:)-63ttx``
|
||||
/// - ``length(_:)-9dr2v``
|
||||
public struct AssociationAggregate<RowDecoder> {
|
||||
fileprivate let preparation: AssociationAggregatePreparation<RowDecoder>
|
||||
@@ -836,7 +835,7 @@ extension AssociationAggregate {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
// MARK: - IFNULL(...)
|
||||
|
||||
extension AssociationAggregate {
|
||||
/// The `IFNULL` SQL function.
|
||||
@@ -855,6 +854,8 @@ extension AssociationAggregate {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ABS(...)
|
||||
|
||||
/// The `ABS` SQL function.
|
||||
public func abs<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
@@ -862,18 +863,7 @@ public func abs<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
|
||||
aggregate.map(abs)
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
// MARK: - LENGTH(...)
|
||||
|
||||
/// The `LENGTH` SQL function.
|
||||
public func length<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
|
||||
|
||||
@@ -61,7 +61,6 @@
|
||||
/// ### Batch Delete
|
||||
///
|
||||
/// - ``deleteAll(_:)``
|
||||
/// - ``deleteAndFetchIds(_:)``
|
||||
/// - ``deleteAndFetchCursor(_:)``
|
||||
/// - ``deleteAndFetchAll(_:)``
|
||||
/// - ``deleteAndFetchSet(_:)``
|
||||
@@ -529,7 +528,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter selection: The returned columns (must not be empty).
|
||||
@@ -562,7 +561,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A ``RecordCursor`` over the deleted records.
|
||||
@@ -589,7 +588,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of deleted records.
|
||||
@@ -615,7 +614,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of deleted records.
|
||||
@@ -626,41 +625,6 @@ 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.
|
||||
///
|
||||
@@ -676,7 +640,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter selection: The returned columns (must not be empty).
|
||||
@@ -710,7 +674,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A ``RecordCursor`` over the deleted records.
|
||||
@@ -738,7 +702,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of deleted records.
|
||||
@@ -765,7 +729,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of deleted records.
|
||||
@@ -777,41 +741,6 @@ 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
|
||||
}
|
||||
|
||||
@@ -915,7 +844,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
@@ -964,7 +893,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
@@ -1001,7 +930,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
@@ -1033,7 +962,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
@@ -1067,7 +996,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
@@ -1117,7 +1046,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
@@ -1155,7 +1084,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
@@ -1188,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#limitations_and_caveats>.
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
|
||||
@@ -90,11 +90,6 @@ 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>
|
||||
@@ -229,9 +224,6 @@ 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,
|
||||
@@ -1100,13 +1092,6 @@ 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.
|
||||
@@ -1284,9 +1269,6 @@ 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)) \
|
||||
@@ -1840,9 +1822,6 @@ 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
|
||||
@@ -2167,7 +2146,6 @@ extension SQLExpressible where Self == Column {
|
||||
/// - ``average(_:)``
|
||||
/// - ``average(_:filter:)``
|
||||
/// - ``capitalized``
|
||||
/// - ``cast(_:as:)-1dmu3``
|
||||
/// - ``count(_:)``
|
||||
/// - ``count(distinct:)``
|
||||
/// - ``dateTime(_:_:)``
|
||||
|
||||
@@ -57,20 +57,6 @@ 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:
|
||||
|
||||
@@ -171,7 +171,7 @@ struct SQLRelation {
|
||||
var source: SQLSource
|
||||
var selectionPromise: DatabasePromise<[SQLSelection]>
|
||||
var filterPromise: DatabasePromise<SQLExpression>?
|
||||
var ordering = SQLRelation.Ordering()
|
||||
var ordering: SQLRelation.Ordering = SQLRelation.Ordering()
|
||||
var ctes: OrderedDictionary<String, SQLCTE> = [:] // See also `allCTEs`
|
||||
var children: OrderedDictionary<String, Child> = [:]
|
||||
|
||||
|
||||
@@ -34,7 +34,18 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
|
||||
}
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
self
|
||||
// @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")
|
||||
}
|
||||
|
||||
private struct KeyedContainer<Key: CodingKey>: KeyedEncodingContainerProtocol {
|
||||
@@ -158,80 +169,6 @@ 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: Sendable {
|
||||
public enum DatabaseUUIDEncodingStrategy {
|
||||
/// The strategy that uses formatting from the UUID type.
|
||||
///
|
||||
/// It encodes UUIDs as 16-bytes data blobs.
|
||||
|
||||
@@ -108,12 +108,8 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
guard let key = codingPath.last else {
|
||||
// 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
|
||||
)
|
||||
// Decoding an array of scalars from rows: pick the first column
|
||||
return ColumnDecoder<R>(row: row, columnIndex: 0, codingPath: codingPath)
|
||||
}
|
||||
guard let index = row.index(forColumn: key.stringValue) else {
|
||||
// Don't use DecodingError.keyNotFound:
|
||||
@@ -151,7 +147,6 @@ 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)
|
||||
@@ -179,25 +174,15 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
|
||||
func decodeNil(forKey key: Key) throws -> Bool {
|
||||
let row = decoder.row
|
||||
|
||||
// Column?
|
||||
if let column = try? decodeColumn(forKey: key),
|
||||
let index = row.index(forColumn: column)
|
||||
{
|
||||
return row.hasNull(atIndex: index)
|
||||
if let column = try? decodeColumn(forKey: key), row[column] != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// Scope?
|
||||
if let scopedRow = row.scopesTree[key.stringValue] {
|
||||
return scopedRow.containsNonNullValue == false
|
||||
if row.scopesTree[key.stringValue] != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// Prefetched Rows?
|
||||
if row.prefetchedRows[key.stringValue] != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// Unknown key
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -350,7 +335,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
|
||||
// Unknown key
|
||||
//
|
||||
// Should we throw an error? Well... The use case is the following:
|
||||
// Should be throw an error? Well... The use case is the following:
|
||||
//
|
||||
// // SELECT book.*, author.* FROM book
|
||||
// // JOIN author ON author.id = book.authorId
|
||||
@@ -391,37 +376,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key)
|
||||
throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey
|
||||
{
|
||||
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)'"))
|
||||
fatalError("not implemented")
|
||||
}
|
||||
|
||||
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
|
||||
@@ -491,50 +446,6 @@ 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 {
|
||||
@@ -680,19 +591,9 @@ 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: statementIndex,
|
||||
atUncheckedIndex: CInt(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
} else {
|
||||
return try decode(
|
||||
@@ -789,16 +690,6 @@ 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),
|
||||
|
||||
@@ -865,8 +865,6 @@ 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,8 +448,6 @@ 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)
|
||||
}
|
||||
|
||||
@@ -595,18 +595,12 @@ extension ValueObservation {
|
||||
/// Creates an optimized `ValueObservation` that notifies the fetched value
|
||||
/// whenever it changes.
|
||||
///
|
||||
/// 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 reduces database contention by not blocking database
|
||||
/// writes when the fresh value is fetched.
|
||||
///
|
||||
/// 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.
|
||||
/// 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.
|
||||
///
|
||||
/// **Precondition**: The `fetch` function must perform requests that fetch
|
||||
/// from a single and constant database region. This region is made of
|
||||
@@ -629,7 +623,7 @@ extension ValueObservation {
|
||||
///
|
||||
/// // Tracks the 'score' column in the 'player' table
|
||||
/// let observation = ValueObservation.trackingConstantRegion { db -> Int? in
|
||||
/// try Int.fetchOne(db, sql: "SELECT MAX(score) FROM player")
|
||||
/// try Player.select(max(Column("score"))).fetchOne(db)
|
||||
/// }
|
||||
///
|
||||
/// // Tracks both the 'player' and 'team' tables
|
||||
@@ -640,93 +634,73 @@ extension ValueObservation {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// **Observations that do not track a constant database region must not
|
||||
/// use this method, because some changes may not be notified to
|
||||
/// the application.**
|
||||
/// Observations that do not track a constant region must not use this
|
||||
/// method. Use ``tracking(_:)`` instead, or else some changes will not
|
||||
/// be notified.
|
||||
///
|
||||
/// For example, the observations below do not track a constant region.
|
||||
/// They are correctly defined with ``tracking(_:)``, since
|
||||
/// `trackingConstantRegion(_:)` is unsuited:
|
||||
/// For example, the observations below do not track a constant region, and
|
||||
/// must not be optimized:
|
||||
///
|
||||
/// ```swift
|
||||
/// // 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 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 '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.
|
||||
/// // 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
|
||||
/// 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 config = try AppConfiguration.find(db)
|
||||
/// switch config.selection {
|
||||
/// case .food:
|
||||
/// return try Food.fetchCount(db)
|
||||
/// case .beverage:
|
||||
/// return try Beverage.fetchCount(db)
|
||||
/// let pref = try Preference.fetchOne(db) ?? .default
|
||||
/// switch pref.selection {
|
||||
/// case .food: return try Food.fetchCount(db)
|
||||
/// case .beverage: return try Beverage.fetchCount(db)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// 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:
|
||||
/// You can turn them into optimized observations of a constant region with
|
||||
/// the ``Database/registerAccess(to:)`` method:
|
||||
///
|
||||
/// - With ``tracking(regions:fetch:)``, you provide all tracked
|
||||
/// region(s) when the observation is created:
|
||||
/// ```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())
|
||||
///
|
||||
/// ```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 pref = try Preference.fetchOne(db) ?? .default
|
||||
/// return try Player.fetchOne(db, id: pref.favoritePlayerId)
|
||||
/// }
|
||||
///
|
||||
/// - With ``Database/registerAccess(to:)``, you extend the list of
|
||||
/// tracked region(s) from the fetching closure:
|
||||
/// 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())
|
||||
///
|
||||
/// ```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 pref = try Preference.fetchOne(db) ?? .default
|
||||
/// let playerIds: [Int64] = pref.favoritePlayerIds // may be empty
|
||||
/// return try Player.fetchAll(db, ids: playerIds)
|
||||
/// }
|
||||
///
|
||||
/// 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 -> 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)
|
||||
/// }
|
||||
/// ```
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter fetch: The closure that fetches the observed value.
|
||||
public static func trackingConstantRegion<Value>(
|
||||
@@ -784,19 +758,6 @@ 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.
|
||||
@@ -856,19 +817,6 @@ 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,10 +66,6 @@ extension ValueObservationScheduler where Self == AsyncValueObservationScheduler
|
||||
/// print("fresh players: \(players)")
|
||||
/// })
|
||||
/// ```
|
||||
///
|
||||
/// - warning: Make sure you provide a serial queue, because a
|
||||
/// concurrent one such as `DispachQueue.global(qos: .default)` would
|
||||
/// mess with the ordering of fresh value notifications.
|
||||
public static func async(onQueue queue: DispatchQueue) -> AsyncValueObservationScheduler {
|
||||
AsyncValueObservationScheduler(queue: queue)
|
||||
}
|
||||
|
||||
@@ -267,7 +267,6 @@
|
||||
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 */; };
|
||||
@@ -784,7 +783,6 @@
|
||||
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>"; };
|
||||
@@ -1560,7 +1558,6 @@
|
||||
children = (
|
||||
564E73E7203DA278000C443C /* JoinSupportTests.swift */,
|
||||
5616B4FE28B5F5490052017E /* SingletonRecordTest.swift */,
|
||||
56B6AB072BD3DCE0009A0B71 /* SingletonUserDefaultsTest.swift */,
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */,
|
||||
560B3FA41C19DFF800C58EC7 /* PersistableRecord */,
|
||||
56176C9E1EACEDF9000F3F2B /* Record */,
|
||||
@@ -2333,7 +2330,6 @@
|
||||
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 */,
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:6.0
|
||||
// swift-tools-version:5.7
|
||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||
|
||||
import Foundation
|
||||
@@ -34,7 +34,7 @@ let package = Package(
|
||||
name: "GRDB",
|
||||
defaultLocalization: "en", // for tests
|
||||
platforms: [
|
||||
.iOS(.v18),
|
||||
.iOS(.v11),
|
||||
.macOS(.v10_13),
|
||||
.tvOS(.v11),
|
||||
.watchOS(.v4),
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
|
||||
</p>
|
||||
|
||||
**Latest release**: September 7, 2024 • [version 6.29.3](https://github.com/groue/GRDB.swift/tree/v6.29.3) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
|
||||
**Latest release**: February 25, 2024 • [version 6.25.0](https://github.com/groue/GRDB.swift/tree/v6.25.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
|
||||
|
||||
**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+
|
||||
|
||||
@@ -340,17 +340,6 @@ See [Encryption](#encryption) for the installation procedure of GRDB with SQLCip
|
||||
See [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) for the installation procedure of GRDB with a customized build of SQLite.
|
||||
|
||||
|
||||
## Swift Package Manager
|
||||
|
||||
The [Swift Package Manager](https://swift.org/package-manager/) automates the distribution of Swift code. To use GRDB with SPM, add a dependency to `https://github.com/groue/GRDB.swift.git`
|
||||
|
||||
GRDB offers two libraries, `GRDB` and `GRDB-dynamic`. Pick only one. When in doubt, prefer `GRDB`. The `GRDB-dynamic` library can reveal useful if you are going to link it with multiple targets within your app and only wish to link to a shared, dynamic framework once. See [How to link a Swift Package as dynamic](https://forums.swift.org/t/how-to-link-a-swift-package-as-dynamic/32062) for more information.
|
||||
|
||||
> **Note**: Linux is not currently supported.
|
||||
>
|
||||
> **Warning**: Due to an Xcode bug, you will get "No such module 'CSQLite'" errors when you want to embed the GRDB package in other targets than the main application (watch extensions, for example). UI and Unit testing targets are OK, though. See [#642](https://github.com/groue/GRDB.swift/issues/642#issuecomment-575994093) for more information.
|
||||
|
||||
|
||||
## CocoaPods
|
||||
|
||||
[CocoaPods](http://cocoapods.org/) is a dependency manager for Xcode projects. To use GRDB with CocoaPods (version 1.2 or higher), specify in your `Podfile`:
|
||||
@@ -361,24 +350,15 @@ pod 'GRDB.swift'
|
||||
|
||||
GRDB can be installed as a framework, or a static library.
|
||||
|
||||
**Important Note for CocoaPods installation**
|
||||
## Swift Package Manager
|
||||
|
||||
Due to an [issue](https://github.com/CocoaPods/CocoaPods/issues/11839) in CocoaPods, it is currently not possible to deploy new versions of GRDB to CocoaPods. The last version available on CocoaPods is 6.24.1. To install later versions of GRDB using CocoaPods, use one of the following workarounds:
|
||||
The [Swift Package Manager](https://swift.org/package-manager/) automates the distribution of Swift code. To use GRDB with SPM, add a dependency to `https://github.com/groue/GRDB.swift.git`
|
||||
|
||||
- Depend on the `GRDB6` branch. This is more or less equivalent to what `pod 'GRDB.swift', '~> 6.0'` would normally do, if CocoaPods would accept new GRDB versions to be published:
|
||||
GRDB offers two libraries, `GRDB` and `GRDB-dynamic`. Pick only one. When in doubt, prefer `GRDB`. The `GRDB-dynamic` library can reveal useful if you are going to link it with multiple targets within your app and only wish to link to a shared, dynamic framework once. See [How to link a Swift Package as dynamic](https://forums.swift.org/t/how-to-link-a-swift-package-as-dynamic/32062) for more information.
|
||||
|
||||
```ruby
|
||||
# Can't use semantic versioning due to https://github.com/CocoaPods/CocoaPods/issues/11839
|
||||
pod 'GRDB.swift', git: 'https://github.com/groue/GRDB.swift.git', branch: 'GRDB6'
|
||||
```
|
||||
|
||||
- Depend on a specific version explicitly (Replace the tag with the version you want to use):
|
||||
|
||||
```ruby
|
||||
# Can't use semantic versioning due to https://github.com/CocoaPods/CocoaPods/issues/11839
|
||||
# Replace the tag with the tag that you want to use.
|
||||
pod 'GRDB.swift', git: 'https://github.com/groue/GRDB.swift.git', tag: 'v6.29.0'
|
||||
```
|
||||
> **Note**: Linux is not currently supported.
|
||||
>
|
||||
> **Warning**: Due to an Xcode bug, you will get "No such module 'CSQLite'" errors when you want to embed the GRDB package in other targets than the main application (watch extensions, for example). UI and Unit testing targets are OK, though. See [#642](https://github.com/groue/GRDB.swift/issues/642#issuecomment-575994093) for more information.
|
||||
|
||||
## Carthage
|
||||
|
||||
@@ -2363,7 +2343,7 @@ See [Persistence Methods], [Upsert](#upsert), and [`updateChanges` methods](#the
|
||||
|
||||
**Batch operations** can return updated or deleted values:
|
||||
|
||||
> **Warning**: Make sure you check the [documentation of the `RETURNING` clause](https://www.sqlite.org/lang_returning.html#limitations_and_caveats), which describes important limitations and caveats for batch operations.
|
||||
> **Warning**: Make sure you check the [documentation of the `RETURNING` clause](https://www.sqlite.org/lang_returning.html), which describes important limitations and caveats for batch operations.
|
||||
|
||||
```swift
|
||||
let request = Player.filter(...)...
|
||||
@@ -4311,17 +4291,6 @@ GRDB comes with a Swift version of many SQLite [built-in functions](https://sqli
|
||||
|
||||
For more information about the functions `dateTime` and `julianDay`, see [Date And Time Functions](https://www.sqlite.org/lang_datefunc.html).
|
||||
|
||||
- `CAST`
|
||||
|
||||
Use the `cast` Swift function:
|
||||
|
||||
```swift
|
||||
// SELECT (CAST(wins AS REAL) / games) AS successRate FROM player
|
||||
Player.select((cast(winsColumn, as: .real) / gamesColumn).forKey("successRate"))
|
||||
```
|
||||
|
||||
See [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr) for more information about SQLite conversions.
|
||||
|
||||
- `IFNULL`
|
||||
|
||||
Use the Swift `??` operator:
|
||||
@@ -5743,7 +5712,9 @@ Open a read-only connection to your resource:
|
||||
// HOW TO open a read-only connection to a database resource
|
||||
|
||||
// Get the path to the database resource.
|
||||
if let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite") {
|
||||
if let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite")
|
||||
|
||||
if let dbPath {
|
||||
// If the resource exists, open a read-only connection.
|
||||
// Writes are disallowed because resources can not be modified.
|
||||
var config = Configuration()
|
||||
|
||||
@@ -15,7 +15,6 @@ disabled_rules:
|
||||
- is_disjoint
|
||||
- large_tuple
|
||||
- nesting
|
||||
- non_optional_string_data_conversion
|
||||
- opening_brace
|
||||
- redundant_optional_initialization
|
||||
- syntactic_sugar
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>6.29.3</string>
|
||||
<string>6.25.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
|
||||
## Features
|
||||
|
||||
- [ ] Detect when `ColumnExpression.noOverwrite` excludes a non-existing column. Code is in DOA.upsertStatement()`. We should not silently ignore non-existing columns, as demonstrated by <https://github.com/groue/GRDB.swift/issues/1539>.
|
||||
- [ ] Can Swift 5.5 help us with `select(.all)` (request of RowDecoder), `select(.id)` (request of RowDecoder.ID), `select(.rowid)` (request of Int64)?
|
||||
- [ ] Direct access to statement for bindings
|
||||
- [ ] Property wrapper that decodes dictionaries (but how to tell the key column?)
|
||||
@@ -85,7 +84,6 @@
|
||||
- [ ] Check https://sqlite.org/sqlar.html
|
||||
- [ ] More schema alterations
|
||||
- [ ] Database.clearSchemaCache() is fine, but what about dbPool readers? Can we invalidate the cache for a whole pool?
|
||||
- [ ] What can we do with `cross-module-optimization`? See https://github.com/apple/swift-homomorphic-encryption
|
||||
|
||||
|
||||
## Unsure if necessary
|
||||
|
||||
@@ -9,8 +9,6 @@
|
||||
/* Begin PBXBuildFile section */
|
||||
5603CECF2AC8636E00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CECE2AC8636E00CF097D /* JSONExpressionsTests.swift */; };
|
||||
5603CED02AC8636E00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CECE2AC8636E00CF097D /* JSONExpressionsTests.swift */; };
|
||||
56071DE52BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56071DE42BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift */; };
|
||||
56071DE62BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56071DE42BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift */; };
|
||||
561F38DD2AC891710051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DC2AC891710051EEE9 /* JSONColumnTests.swift */; };
|
||||
561F38DE2AC891710051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DC2AC891710051EEE9 /* JSONColumnTests.swift */; };
|
||||
561F38F92AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; };
|
||||
@@ -504,7 +502,6 @@
|
||||
04298D834C818285823558AB /* Pods-GRDBTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.release.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.release.xcconfig"; sourceTree = "<group>"; };
|
||||
47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = "<group>"; };
|
||||
5603CECE2AC8636E00CF097D /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = "<group>"; };
|
||||
56071DE42BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SingletonUserDefaultsTest.swift; sourceTree = "<group>"; };
|
||||
561F38DC2AC891710051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
|
||||
561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
561F38F82AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1037,7 +1034,6 @@
|
||||
56419CFA24A5405A004967E1 /* SelectStatementTests.swift */,
|
||||
567B5C282AD32A2D00629622 /* SharedValueObservationTests.swift */,
|
||||
567B5C1E2AD32A2D00629622 /* SingletonRecordTest.swift */,
|
||||
56071DE42BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift */,
|
||||
567B5C232AD32A2D00629622 /* SQLExpressionIsConstantTests.swift */,
|
||||
56419CCA24A54056004967E1 /* SQLExpressionLiteralTests.swift */,
|
||||
567B5C1D2AD32A2D00629622 /* SQLIdentifyingColumnsTests.swift */,
|
||||
@@ -1463,7 +1459,6 @@
|
||||
56419E0324A54062004967E1 /* SchedulingWatchdogTests.swift in Sources */,
|
||||
56419E7D24A54063004967E1 /* DropWhileCursorTests.swift in Sources */,
|
||||
56419EBD24A54063004967E1 /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */,
|
||||
56071DE52BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift in Sources */,
|
||||
56419E8F24A54063004967E1 /* AssociationHasManySQLTests.swift in Sources */,
|
||||
5641A1A424A540D6004967E1 /* Support.swift in Sources */,
|
||||
5641A1BC24A540D6004967E1 /* PublisherExpectation.swift in Sources */,
|
||||
@@ -1711,7 +1706,6 @@
|
||||
56419E0424A54062004967E1 /* SchedulingWatchdogTests.swift in Sources */,
|
||||
56419E7E24A54063004967E1 /* DropWhileCursorTests.swift in Sources */,
|
||||
56419EBE24A54063004967E1 /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */,
|
||||
56071DE62BD3DDB5000802B6 /* SingletonUserDefaultsTest.swift in Sources */,
|
||||
56419E9024A54063004967E1 /* AssociationHasManySQLTests.swift in Sources */,
|
||||
5641A1A524A540D6004967E1 /* Support.swift in Sources */,
|
||||
5641A1BD24A540D6004967E1 /* PublisherExpectation.swift in Sources */,
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
56071DE22BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56071DE12BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift */; };
|
||||
56071DE32BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56071DE12BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift */; };
|
||||
561F38E12AC891890051EEE9 /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DF2AC891890051EEE9 /* JSONExpressionsTests.swift */; };
|
||||
561F38E22AC891890051EEE9 /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DF2AC891890051EEE9 /* JSONExpressionsTests.swift */; };
|
||||
561F38E32AC891890051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38E02AC891890051EEE9 /* JSONColumnTests.swift */; };
|
||||
@@ -505,7 +503,6 @@
|
||||
/* Begin PBXFileReference section */
|
||||
04298D834C818285823558AB /* Pods-GRDBTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.release.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.release.xcconfig"; sourceTree = "<group>"; };
|
||||
47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = "<group>"; };
|
||||
56071DE12BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SingletonUserDefaultsTest.swift; sourceTree = "<group>"; };
|
||||
561F38DF2AC891890051EEE9 /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = "<group>"; };
|
||||
561F38E02AC891890051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
|
||||
561F38FD2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1041,7 +1038,6 @@
|
||||
56419F5B24A54098004967E1 /* SelectStatementTests.swift */,
|
||||
567B5C0B2AD32A0000629622 /* SharedValueObservationTests.swift */,
|
||||
567B5C0A2AD32A0000629622 /* SingletonRecordTest.swift */,
|
||||
56071DE12BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift */,
|
||||
567B5C0C2AD32A0000629622 /* SQLExpressionIsConstantTests.swift */,
|
||||
56419F1C24A54094004967E1 /* SQLExpressionLiteralTests.swift */,
|
||||
567B5C0D2AD32A0000629622 /* SQLIdentifyingColumnsTests.swift */,
|
||||
@@ -1469,7 +1465,6 @@
|
||||
5641A04424A540A1004967E1 /* FTS3TokenizerTests.swift in Sources */,
|
||||
5641A14024A540A2004967E1 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
|
||||
561F38FF2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */,
|
||||
56071DE22BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift in Sources */,
|
||||
5641A08A24A540A1004967E1 /* EncryptionTests.swift in Sources */,
|
||||
5641A11E24A540A1004967E1 /* IndexInfoTests.swift in Sources */,
|
||||
56419FEC24A540A1004967E1 /* FTS4TableBuilderTests.swift in Sources */,
|
||||
@@ -1717,7 +1712,6 @@
|
||||
5641A04524A540A1004967E1 /* FTS3TokenizerTests.swift in Sources */,
|
||||
5641A14124A540A2004967E1 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
|
||||
561F39002AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */,
|
||||
56071DE32BD3DDA5000802B6 /* SingletonUserDefaultsTest.swift in Sources */,
|
||||
5641A08B24A540A1004967E1 /* EncryptionTests.swift in Sources */,
|
||||
5641A11F24A540A1004967E1 /* IndexInfoTests.swift in Sources */,
|
||||
56419FED24A540A1004967E1 /* FTS4TableBuilderTests.swift in Sources */,
|
||||
|
||||
@@ -1511,30 +1511,6 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testCast() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
do {
|
||||
let request = Team.annotated(with: cast(Team.players.count, as: .real))
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "team".*, CAST(COUNT(DISTINCT "player"."id") AS REAL) AS "playerCount" \
|
||||
FROM "team" \
|
||||
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
|
||||
GROUP BY "team"."id"
|
||||
""")
|
||||
}
|
||||
do {
|
||||
let request = Team.annotated(with: cast(Team.players.count, as: .real).forKey("foo"))
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "team".*, CAST(COUNT(DISTINCT "player"."id") AS REAL) AS "foo" \
|
||||
FROM "team" \
|
||||
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
|
||||
GROUP BY "team"."id"
|
||||
""")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testLength() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
|
||||
@@ -139,13 +139,4 @@ class BackupTestCase: GRDBTestCase {
|
||||
XCTAssertFalse(try db.tableExists("items"))
|
||||
}
|
||||
}
|
||||
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
func testBackupToAnyDatabaseWriter(
|
||||
_ reader: some DatabaseReader,
|
||||
destination: any DatabaseWriter
|
||||
) throws {
|
||||
try reader.backup(to: destination)
|
||||
}
|
||||
}
|
||||
@@ -223,32 +223,6 @@ class CursorTests: GRDBTestCase {
|
||||
let set = try Set(cursor, minimumCapacity: 100)
|
||||
XCTAssertEqual(set, [1, 2, 3])
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = AnyCursor([1, 2, 1, 3])
|
||||
let set: Set<Int> = [1, 4]
|
||||
try XCTAssertEqual(set.union(cursor), [1, 2, 3, 4])
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = AnyCursor([1, 2, 1, 3])
|
||||
var set: Set<Int> = [1, 4]
|
||||
try set.formUnion(cursor)
|
||||
XCTAssertEqual(set, [1, 2, 3, 4])
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = AnyCursor([1, 2, 1, 3])
|
||||
let set: Set<Int> = [1, 3, 4]
|
||||
try XCTAssertEqual(set.intersection(cursor), [1, 3])
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = AnyCursor([1, 2, 1, 3])
|
||||
var set: Set<Int> = [1, 3, 4]
|
||||
try set.formIntersection(cursor)
|
||||
XCTAssertEqual(set, [1, 3])
|
||||
}
|
||||
}
|
||||
|
||||
func testDictionaryGrouping() throws {
|
||||
|
||||
@@ -137,6 +137,7 @@ class DatabaseConfigurationTests: GRDBTestCase {
|
||||
}
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertEqual(error.message, "no such column: foo")
|
||||
XCTAssertEqual(error.sql, "SELECT \"foo\" FROM player")
|
||||
}
|
||||
|
||||
@@ -150,6 +151,10 @@ class DatabaseConfigurationTests: GRDBTestCase {
|
||||
}
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssert([
|
||||
"no such column: foo",
|
||||
"table player has no column named foo"]
|
||||
.contains(error.message))
|
||||
XCTAssertEqual(error.sql, "CREATE INDEX i ON player(\"foo\")")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,8 +51,10 @@ final class DatabaseDumpTests: GRDBTestCase {
|
||||
blob: utf8 short|您好🙂
|
||||
blob: uuid|69BF8A9C-D9F0-4777-BD11-93451D84CBCF
|
||||
double: -1.0|-1.0
|
||||
double: -inf|-inf
|
||||
double: 0.0|0.0
|
||||
double: 123.45|123.45
|
||||
double: inf|inf
|
||||
double: nan|
|
||||
integer: -1|-1
|
||||
integer: 0|0
|
||||
@@ -248,8 +250,10 @@ final class DatabaseDumpTests: GRDBTestCase {
|
||||
{"name":"blob: utf8 short","value":"5oKo5aW98J+Zgg=="},
|
||||
{"name":"blob: uuid","value":"ab+KnNnwR3e9EZNFHYTLzw=="},
|
||||
{"name":"double: -1.0","value":-1},
|
||||
{"name":"double: -inf","value":"-inf"},
|
||||
{"name":"double: 0.0","value":0},
|
||||
{"name":"double: 123.45","value":123.45},
|
||||
{"name":"double: inf","value":"inf"},
|
||||
{"name":"double: nan","value":null},
|
||||
{"name":"integer: -1","value":-1},
|
||||
{"name":"integer: 0","value":0},
|
||||
@@ -409,12 +413,18 @@ final class DatabaseDumpTests: GRDBTestCase {
|
||||
name = double: -1.0
|
||||
value = -1.0
|
||||
|
||||
name = double: -inf
|
||||
value = -inf
|
||||
|
||||
name = double: 0.0
|
||||
value = 0.0
|
||||
|
||||
name = double: 123.45
|
||||
value = 123.45
|
||||
|
||||
name = double: inf
|
||||
value = inf
|
||||
|
||||
name = double: nan
|
||||
value = \n\
|
||||
|
||||
@@ -594,8 +604,10 @@ final class DatabaseDumpTests: GRDBTestCase {
|
||||
blob: utf8 short|您好🙂
|
||||
blob: uuid|\("i\u{fffd}\u{fffd}\u{fffd}\u{fffd}\u{fffd}Gw\u{fffd}\u{11}\u{fffd}E\u{1d}\u{fffd}\u{fffd}\u{fffd}")
|
||||
double: -1.0|-1.0
|
||||
double: -inf|-inf
|
||||
double: 0.0|0.0
|
||||
double: 123.45|123.45
|
||||
double: inf|inf
|
||||
double: nan|
|
||||
integer: -1|-1
|
||||
integer: 0|0
|
||||
@@ -787,8 +799,10 @@ final class DatabaseDumpTests: GRDBTestCase {
|
||||
'blob: utf8 short',X'E682A8E5A5BDF09F9982'
|
||||
'blob: uuid',X'69BF8A9CD9F04777BD1193451D84CBCF'
|
||||
'double: -1.0',-1.0
|
||||
'double: -inf',-Inf
|
||||
'double: 0.0',0.0
|
||||
'double: 123.45',123.45
|
||||
'double: inf',Inf
|
||||
'double: nan',NULL
|
||||
'integer: -1',-1
|
||||
'integer: 0',0
|
||||
@@ -1572,8 +1586,10 @@ final class DatabaseDumpTests: GRDBTestCase {
|
||||
INSERT INTO value VALUES ('blob: uuid', x'69BF8A9CD9F04777BD1193451D84CBCF');
|
||||
|
||||
INSERT INTO value VALUES ('double: -1.0', -1.0);
|
||||
INSERT INTO value VALUES ('double: -inf', \(-1.0 / 0));
|
||||
INSERT INTO value VALUES ('double: 0.0', 0.0);
|
||||
INSERT INTO value VALUES ('double: 123.45', 123.45);
|
||||
INSERT INTO value VALUES ('double: inf', \(1.0 / 0));
|
||||
INSERT INTO value VALUES ('double: nan', \(0.0 / 0));
|
||||
|
||||
INSERT INTO value VALUES ('integer: 0', 0);
|
||||
|
||||
@@ -2,12 +2,6 @@ import XCTest
|
||||
import GRDB
|
||||
|
||||
class DatabaseMigratorTests : GRDBTestCase {
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
func testMigrateAnyDatabaseWriter(writer: any DatabaseWriter) throws {
|
||||
let migrator = DatabaseMigrator()
|
||||
try migrator.migrate(writer)
|
||||
}
|
||||
|
||||
func testEmptyMigratorSync() throws {
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
|
||||
@@ -439,12 +439,4 @@ class DatabasePoolTests: GRDBTestCase {
|
||||
// In the zombie state, closing is a noop
|
||||
try dbPool.close()
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1612>
|
||||
func test_releaseMemory_after_close() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
try dbPool.read { _ in } // Create a reader
|
||||
try dbPool.close()
|
||||
dbPool.releaseMemory()
|
||||
}
|
||||
}
|
||||
@@ -467,11 +467,4 @@ class DatabaseQueueTests: GRDBTestCase {
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1612>
|
||||
func test_releaseMemory_after_close() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.close()
|
||||
dbQueue.releaseMemory()
|
||||
}
|
||||
}
|
||||
@@ -2,29 +2,13 @@ import XCTest
|
||||
import GRDB
|
||||
|
||||
class DatabaseReaderTests : GRDBTestCase {
|
||||
|
||||
func testAnyDatabaseReader() throws {
|
||||
// This test passes if this code compiles.
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let _: any DatabaseReader = AnyDatabaseReader(dbQueue)
|
||||
}
|
||||
|
||||
// Test passes if it compiles.
|
||||
func testInitFromGeneric(_ reader: some DatabaseReader) {
|
||||
_ = AnyDatabaseReader(reader)
|
||||
}
|
||||
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
func testInitFromExistentialReader(_ reader: any DatabaseReader) {
|
||||
_ = AnyDatabaseReader(reader)
|
||||
}
|
||||
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
func testInitFromExistentialWriter(_ writer: any DatabaseWriter) {
|
||||
_ = AnyDatabaseReader(writer)
|
||||
}
|
||||
|
||||
// MARK: - Read
|
||||
|
||||
func testReadCanRead() throws {
|
||||
|
||||
@@ -2,18 +2,6 @@ import XCTest
|
||||
import GRDB
|
||||
|
||||
class DatabaseRegionObservationTests: GRDBTestCase {
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
func testAnyDatabaseWriter(writer: any DatabaseWriter) throws {
|
||||
let observation = DatabaseRegionObservation(tracking: .fullDatabase)
|
||||
|
||||
_ = observation.start(in: writer, onError: { _ in }, onChange: { _ in })
|
||||
|
||||
if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) {
|
||||
_ = observation.publisher(in: writer)
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseRegionObservation_FullDatabase() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write {
|
||||
|
||||
@@ -340,3 +340,51 @@ extension DatabaseValueConvertibleEncodableTests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Super Encoders
|
||||
|
||||
extension DatabaseValueConvertibleEncodableTests {
|
||||
func testSuperEncoder() throws {
|
||||
// Gets compiler-synthesized `Codable` impl
|
||||
class CodableSup: Codable, DatabaseValueConvertible {
|
||||
var x: Int
|
||||
init(_ x: Int) { self.x = x }
|
||||
}
|
||||
|
||||
// We have to override init(from:) and encode(to:) to avoid inheriting them
|
||||
class CodableSub: CodableSup {
|
||||
var y: Int
|
||||
init(_ x: Int, _ y: Int) { self.y = y; super.init(x) }
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case y
|
||||
}
|
||||
|
||||
required init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
y = try container.decode(Int.self, forKey: .y)
|
||||
|
||||
// This will effectively fetch a nested container for key "super", then return a `Decoder` wrapping it
|
||||
let superDecoder = try container.superDecoder()
|
||||
try super.init(from: superDecoder)
|
||||
}
|
||||
|
||||
override func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(y, forKey: .y)
|
||||
|
||||
// This will effectively create a nested container for key "super", then return an `Encoder` wrapping it
|
||||
let superEncoder = container.superEncoder()
|
||||
try super.encode(to: superEncoder)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let dbValue = CodableSup(42).databaseValue
|
||||
XCTAssertEqual(dbValue.storage.value as! String, #"{"x":42}"#)
|
||||
|
||||
let dbValue2 = CodableSub(42, 500).databaseValue
|
||||
XCTAssertEqual(dbValue2.storage.value as! String, #"{"super":{"x":42},"y":500}"#)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -637,26 +637,6 @@ class EncryptionTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// Test for the use case described in <https://github.com/groue/GRDB.swift/discussions/1517>
|
||||
func testEncryptedDatabaseCanBeAttached() throws {
|
||||
// Create encrypted db
|
||||
var config = Configuration()
|
||||
config.prepareDatabase { db in
|
||||
try db.usePassphrase("secret")
|
||||
}
|
||||
let encryptedDBQueue = try makeDatabaseQueue(filename: "encrypted.sqlite", configuration: config)
|
||||
try encryptedDBQueue.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
}
|
||||
|
||||
let attachingDBQueue = try makeDatabaseQueue()
|
||||
try attachingDBQueue.inDatabase { db in
|
||||
try db.execute(sql: "ATTACH DATABASE ? AS encrypted KEY ?", arguments: [encryptedDBQueue.path, "secret"])
|
||||
let count = try Table("t").fetchCount(db)
|
||||
XCTAssertEqual(count, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func testExportPlainTextDatabaseToEncryptedDatabase() throws {
|
||||
// See https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/868?source_topic_id=939
|
||||
do {
|
||||
|
||||
@@ -263,130 +263,14 @@ extension FetchableRecordDecodableTests {
|
||||
|
||||
extension FetchableRecordDecodableTests {
|
||||
|
||||
func testStructWithData() throws {
|
||||
struct StructWithData : FetchableRecord, Decodable {
|
||||
let data: Data
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
do {
|
||||
let data = "foo".data(using: .utf8)
|
||||
|
||||
do {
|
||||
let value = try StructWithData(row: ["data": data])
|
||||
XCTAssertEqual(value.data, data)
|
||||
}
|
||||
|
||||
do {
|
||||
let value = try dbQueue.read {
|
||||
try StructWithData.fetchOne($0, sql: "SELECT ? AS data", arguments: [data])!
|
||||
}
|
||||
XCTAssertEqual(value.data, data)
|
||||
}
|
||||
}
|
||||
do {
|
||||
do {
|
||||
_ = try StructWithData(row: ["data": nil])
|
||||
XCTFail("Expected Error")
|
||||
} catch let error as RowDecodingError {
|
||||
switch error {
|
||||
case .valueMismatch:
|
||||
XCTAssertEqual(error.description, """
|
||||
could not decode Data from database value NULL - \
|
||||
column: "data", \
|
||||
column index: 0, \
|
||||
row: [data:NULL]
|
||||
""")
|
||||
default:
|
||||
XCTFail("Unexpected Error")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try dbQueue.read {
|
||||
_ = try StructWithData.fetchOne($0, sql: "SELECT NULL AS data")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch let error as RowDecodingError {
|
||||
switch error {
|
||||
case .valueMismatch:
|
||||
XCTAssertEqual(error.description, """
|
||||
could not decode Data from database value NULL - \
|
||||
column: "data", \
|
||||
column index: 0, \
|
||||
row: [data:NULL], \
|
||||
sql: `SELECT NULL AS data`, \
|
||||
arguments: []
|
||||
""")
|
||||
default:
|
||||
XCTFail("Unexpected Error")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testStructWithDate() throws {
|
||||
struct StructWithDate : FetchableRecord, Decodable {
|
||||
let date: Date
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
do {
|
||||
let date = Date()
|
||||
|
||||
do {
|
||||
let value = try StructWithDate(row: ["date": date])
|
||||
XCTAssert(abs(value.date.timeIntervalSince(date)) < 0.001)
|
||||
}
|
||||
|
||||
do {
|
||||
let value = try dbQueue.read {
|
||||
try StructWithDate.fetchOne($0, sql: "SELECT ? AS date", arguments: [date])!
|
||||
}
|
||||
XCTAssert(abs(value.date.timeIntervalSince(date)) < 0.001)
|
||||
}
|
||||
}
|
||||
do {
|
||||
do {
|
||||
_ = try StructWithDate(row: ["date": nil])
|
||||
XCTFail("Expected Error")
|
||||
} catch let error as RowDecodingError {
|
||||
switch error {
|
||||
case .valueMismatch:
|
||||
XCTAssertEqual(error.description, """
|
||||
could not decode Date from database value NULL - \
|
||||
column: "date", \
|
||||
column index: 0, \
|
||||
row: [date:NULL]
|
||||
""")
|
||||
default:
|
||||
XCTFail("Unexpected Error")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try dbQueue.read {
|
||||
_ = try StructWithDate.fetchOne($0, sql: "SELECT NULL AS date")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch let error as RowDecodingError {
|
||||
switch error {
|
||||
case .valueMismatch:
|
||||
XCTAssertEqual(error.description, """
|
||||
could not decode Date from database value NULL - \
|
||||
column: "date", \
|
||||
column index: 0, \
|
||||
row: [date:NULL], \
|
||||
sql: `SELECT NULL AS date`, \
|
||||
arguments: []
|
||||
""")
|
||||
default:
|
||||
XCTFail("Unexpected Error")
|
||||
}
|
||||
}
|
||||
}
|
||||
let date = Date()
|
||||
let value = try StructWithDate(row: ["date": date])
|
||||
XCTAssert(abs(value.date.timeIntervalSince(date)) < 0.001)
|
||||
}
|
||||
|
||||
func testStructWithURL() throws {
|
||||
@@ -1652,331 +1536,3 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - KeyedContainer tests
|
||||
|
||||
extension FetchableRecordDecodableTests {
|
||||
struct AnyCodingKey: CodingKey {
|
||||
var stringValue: String
|
||||
var intValue: Int? { nil }
|
||||
|
||||
init(_ key: String) {
|
||||
self.stringValue = key
|
||||
}
|
||||
|
||||
init(stringValue: String) {
|
||||
self.stringValue = stringValue
|
||||
}
|
||||
|
||||
init?(intValue: Int) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func test_allKeys_and_containsKey() throws {
|
||||
struct Witness: Decodable, FetchableRecord {
|
||||
init(from decoder: any Decoder) throws {
|
||||
// Top
|
||||
let container = try decoder.container(keyedBy: AnyCodingKey.self)
|
||||
do {
|
||||
// Test allKeys
|
||||
let allKeys = container.allKeys
|
||||
XCTAssertEqual(Set(allKeys.map(\.stringValue)), [
|
||||
"a",
|
||||
"topLevelScope1",
|
||||
"topLevelScope2",
|
||||
"nestedScope1",
|
||||
"nestedScope2",
|
||||
"prefetchedRows1",
|
||||
"prefetchedRows2"])
|
||||
|
||||
// Test contains(_:)
|
||||
for key in allKeys {
|
||||
XCTAssertTrue(container.contains(key))
|
||||
}
|
||||
XCTAssertFalse(container.contains(AnyCodingKey("b")))
|
||||
XCTAssertFalse(container.contains(AnyCodingKey("c")))
|
||||
}
|
||||
|
||||
// topLevelScope1
|
||||
let topLevelScope1Container = try container.nestedContainer(
|
||||
keyedBy: AnyCodingKey.self,
|
||||
forKey: AnyCodingKey("topLevelScope1"))
|
||||
do {
|
||||
// Test allKeys
|
||||
let allKeys = topLevelScope1Container.allKeys
|
||||
XCTAssertEqual(Set(allKeys.map(\.stringValue)), [
|
||||
"c",
|
||||
])
|
||||
|
||||
// Test contains(_:)
|
||||
for key in allKeys {
|
||||
XCTAssertTrue(topLevelScope1Container.contains(key))
|
||||
}
|
||||
}
|
||||
|
||||
// topLevelScope2
|
||||
let topLevelScope2Container = try container.nestedContainer(
|
||||
keyedBy: AnyCodingKey.self,
|
||||
forKey: AnyCodingKey("topLevelScope2"))
|
||||
do {
|
||||
// Test allKeys
|
||||
let allKeys = topLevelScope2Container.allKeys
|
||||
XCTAssertEqual(Set(allKeys.map(\.stringValue)), [
|
||||
"nestedScope2",
|
||||
"nestedScope1",
|
||||
"prefetchedRows2",
|
||||
])
|
||||
|
||||
// Test contains(_:)
|
||||
for key in allKeys {
|
||||
XCTAssertTrue(topLevelScope2Container.contains(key))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().read { db in
|
||||
let row = try Row.fetchOne(
|
||||
db, sql: """
|
||||
SELECT 1 AS a, -- main row
|
||||
2 AS b, -- not exposed
|
||||
3 AS c, -- scope topLevelScope1
|
||||
4 AS d, -- scope topLevelScope2.nestedScope1
|
||||
5 AS e -- scope topLevelScope2.nestedScope2
|
||||
""",
|
||||
adapter: RangeRowAdapter(0..<1)
|
||||
.addingScopes([
|
||||
"topLevelScope1": RangeRowAdapter(2..<3),
|
||||
"topLevelScope2": EmptyRowAdapter().addingScopes([
|
||||
"nestedScope1": RangeRowAdapter(3..<4),
|
||||
"nestedScope2": RangeRowAdapter(4..<5),
|
||||
]),
|
||||
]))!
|
||||
|
||||
row.prefetchedRows.setRows([], forKeyPath: ["prefetchedRows1"])
|
||||
row.prefetchedRows.setRows([Row()], forKeyPath: ["topLevelScope2", "prefetchedRows2"])
|
||||
// Check test setup
|
||||
XCTAssertEqual(row.debugDescription, """
|
||||
▿ [a:1]
|
||||
unadapted: [a:1 b:2 c:3 d:4 e:5]
|
||||
- topLevelScope1: [c:3]
|
||||
- topLevelScope2: []
|
||||
- nestedScope1: [d:4]
|
||||
- nestedScope2: [e:5]
|
||||
+ prefetchedRows2: 1 row
|
||||
+ prefetchedRows1: 0 row
|
||||
+ prefetchedRows2: 1 row
|
||||
""")
|
||||
|
||||
// Test keyed container
|
||||
_ = try FetchableRecordDecoder().decode(Witness.self, from: row)
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1531>
|
||||
func test_decodeNil_and_containsKey() throws {
|
||||
struct Witness: Decodable, FetchableRecord {
|
||||
struct NestedRecord: Decodable, FetchableRecord { }
|
||||
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: AnyCodingKey.self)
|
||||
|
||||
// column
|
||||
do {
|
||||
let key = AnyCodingKey("a")
|
||||
let nilDecoded = try container.decodeNil(forKey: key)
|
||||
let value = try container.decodeIfPresent(Int.self, forKey: key)
|
||||
XCTAssertTrue(nilDecoded == (value == nil))
|
||||
XCTAssertTrue(container.contains(key))
|
||||
}
|
||||
|
||||
// scope
|
||||
do {
|
||||
let key = AnyCodingKey("nested")
|
||||
let nilDecoded = try container.decodeNil(forKey: key)
|
||||
let value = try container.decodeIfPresent(NestedRecord.self, forKey: key)
|
||||
XCTAssertTrue(nilDecoded == (value == nil))
|
||||
XCTAssertTrue(container.contains(key))
|
||||
}
|
||||
|
||||
// missing key
|
||||
do {
|
||||
let key = AnyCodingKey("missing")
|
||||
try XCTAssertTrue(container.decodeNil(forKey: key))
|
||||
try XCTAssertNil(container.decodeIfPresent(Int.self, forKey: key))
|
||||
try XCTAssertNil(container.decodeIfPresent(NestedRecord.self, forKey: key))
|
||||
XCTAssertFalse(container.contains(key))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().read { db in
|
||||
do {
|
||||
let row = try Row.fetchOne(
|
||||
db, sql: """
|
||||
SELECT 1 AS a, 2 AS b
|
||||
""",
|
||||
adapter: ScopeAdapter([
|
||||
"nested": RangeRowAdapter(1..<2),
|
||||
]))!
|
||||
|
||||
// Check test setup
|
||||
XCTAssertEqual(row.debugDescription, """
|
||||
▿ [a:1 b:2]
|
||||
unadapted: [a:1 b:2]
|
||||
- nested: [b:2]
|
||||
""")
|
||||
|
||||
// Test keyed container
|
||||
_ = try FetchableRecordDecoder().decode(Witness.self, from: row)
|
||||
}
|
||||
|
||||
do {
|
||||
let row = try Row.fetchOne(
|
||||
db, sql: """
|
||||
SELECT NULL AS a, NULL AS b
|
||||
""",
|
||||
adapter: ScopeAdapter([
|
||||
"nested": RangeRowAdapter(1..<2),
|
||||
]))!
|
||||
|
||||
// Check test setup
|
||||
XCTAssertEqual(row.debugDescription, """
|
||||
▿ [a:NULL b:NULL]
|
||||
unadapted: [a:NULL b:NULL]
|
||||
- nested: [b:NULL]
|
||||
""")
|
||||
|
||||
// Test keyed container
|
||||
_ = try FetchableRecordDecoder().decode(Witness.self, from: row)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1531>
|
||||
func test_decodeNil_when_scope_and_column_have_the_same_name() throws {
|
||||
struct Witness: Decodable, FetchableRecord {
|
||||
struct NestedRecord: Decodable, FetchableRecord { }
|
||||
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: AnyCodingKey.self)
|
||||
|
||||
let key = AnyCodingKey("a")
|
||||
let nilDecoded = try container.decodeNil(forKey: key)
|
||||
let intValue = try container.decodeIfPresent(Int.self, forKey: key)
|
||||
let recordValue = try container.decodeIfPresent(NestedRecord.self, forKey: key)
|
||||
XCTAssertTrue(nilDecoded == (intValue == nil))
|
||||
XCTAssertTrue(nilDecoded == (recordValue == nil))
|
||||
}
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().read { db in
|
||||
do {
|
||||
let row = try Row.fetchOne(
|
||||
db, sql: """
|
||||
SELECT 1 AS a
|
||||
""",
|
||||
adapter: ScopeAdapter([
|
||||
"a": SuffixRowAdapter(fromIndex: 0),
|
||||
]))!
|
||||
|
||||
// Check test setup
|
||||
XCTAssertEqual(row.debugDescription, """
|
||||
▿ [a:1]
|
||||
unadapted: [a:1]
|
||||
- a: [a:1]
|
||||
""")
|
||||
|
||||
// Test keyed container
|
||||
_ = try FetchableRecordDecoder().decode(Witness.self, from: row)
|
||||
}
|
||||
|
||||
do {
|
||||
let row = try Row.fetchOne(
|
||||
db, sql: """
|
||||
SELECT NULL AS a
|
||||
""",
|
||||
adapter: ScopeAdapter([
|
||||
"a": SuffixRowAdapter(fromIndex: 0),
|
||||
]))!
|
||||
|
||||
// Check test setup
|
||||
XCTAssertEqual(row.debugDescription, """
|
||||
▿ [a:NULL]
|
||||
unadapted: [a:NULL]
|
||||
- a: [a:NULL]
|
||||
""")
|
||||
|
||||
// Test keyed container
|
||||
_ = try FetchableRecordDecoder().decode(Witness.self, from: row)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1572>
|
||||
func testSingleValueContainer() throws {
|
||||
struct Struct: Decodable {
|
||||
let value: String
|
||||
}
|
||||
|
||||
struct Wrapper<Model: Decodable>: FetchableRecord, Decodable {
|
||||
var model: Model
|
||||
var otherValue: String
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case otherValue
|
||||
}
|
||||
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
otherValue = try container.decode(String.self, forKey: . otherValue)
|
||||
|
||||
let singleValueContainer = try decoder.singleValueContainer()
|
||||
model = try singleValueContainer.decode(Model.self)
|
||||
}
|
||||
}
|
||||
|
||||
let row = Row(["value": "foo", "otherValue": "bar"])
|
||||
|
||||
let wrapper = try Wrapper<Struct>(row: row)
|
||||
XCTAssertEqual(wrapper.model.value, "foo")
|
||||
XCTAssertEqual(wrapper.otherValue, "bar")
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1572>
|
||||
// Here we test that `FetchableRecord` takes precedence over `Decodable`
|
||||
// when a record is encoded with a `SingleValueEncodingContainer`.
|
||||
func testSingleValueContainerWithFetchableRecord() throws {
|
||||
struct Struct: Decodable, FetchableRecord {
|
||||
let value: String
|
||||
|
||||
init(row: Row) throws {
|
||||
value = row["actualValue"]
|
||||
}
|
||||
}
|
||||
|
||||
struct Wrapper<Model: Decodable>: FetchableRecord, Decodable {
|
||||
var model: Model
|
||||
var otherValue: String
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case otherValue
|
||||
}
|
||||
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
otherValue = try container.decode(String.self, forKey: . otherValue)
|
||||
|
||||
let singleValueContainer = try decoder.singleValueContainer()
|
||||
model = try singleValueContainer.decode(Model.self)
|
||||
}
|
||||
}
|
||||
|
||||
let row = Row(["value": "foo", "otherValue": "bar", "actualValue": "test"])
|
||||
|
||||
let wrapper = try Wrapper<Struct>(row: row)
|
||||
XCTAssertEqual(wrapper.model.value, "test")
|
||||
XCTAssertEqual(wrapper.otherValue, "bar")
|
||||
}
|
||||
}
|
||||
@@ -358,6 +358,11 @@ final class JSONExpressionsTests: GRDBTestCase {
|
||||
guard sqlite3_libversion_number() >= 3042000 else {
|
||||
throw XCTSkip("JSON_ERROR_JSON is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) else {
|
||||
throw XCTSkip("JSON_ERROR_JSON is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
try makeDatabaseQueue().inDatabase { db in
|
||||
try db.create(table: "player") { t in
|
||||
@@ -380,9 +385,6 @@ final class JSONExpressionsTests: GRDBTestCase {
|
||||
SELECT JSON_ERROR_POSITION("info") FROM "player"
|
||||
""")
|
||||
}
|
||||
#else
|
||||
throw XCTSkip("JSON_ERROR_JSON is not available")
|
||||
#endif
|
||||
}
|
||||
|
||||
func test_Database_jsonExtract_atPath() throws {
|
||||
|
||||
@@ -83,97 +83,6 @@ extension MutablePersistableRecordEncodableTests {
|
||||
XCTAssertEqual(string, "foo (MutablePersistableRecord)")
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1565>
|
||||
func testSingleValueContainer() throws {
|
||||
struct Struct: Encodable {
|
||||
let value: String
|
||||
}
|
||||
|
||||
struct Wrapper<Model: Encodable>: MutablePersistableRecord, Encodable {
|
||||
static var databaseTableName: String { "t1" }
|
||||
var model: Model
|
||||
var otherValue: String
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case otherValue
|
||||
}
|
||||
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var modelContainer = encoder.singleValueContainer()
|
||||
try modelContainer.encode(model)
|
||||
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(otherValue, forKey: .otherValue)
|
||||
}
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "t1") { t in
|
||||
t.column("value", .text)
|
||||
t.column("otherValue", .text)
|
||||
}
|
||||
|
||||
var value = Wrapper(model: Struct(value: "foo"), otherValue: "bar")
|
||||
try assert(value, isEncodedIn: ["value": "foo", "otherValue": "bar"])
|
||||
|
||||
try value.insert(db)
|
||||
let row = try Row.fetchOne(db, sql: "SELECT value, otherValue FROM t1")!
|
||||
XCTAssertEqual(row[0], "foo")
|
||||
XCTAssertEqual(row[1], "bar")
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1565>
|
||||
// Here we test that `EncodableRecord` takes precedence over `Encodable`
|
||||
// when a record is encoded with a `SingleValueEncodingContainer`.
|
||||
func testSingleValueContainerWithEncodableRecord() throws {
|
||||
struct Struct: Encodable, EncodableRecord {
|
||||
let value: String
|
||||
|
||||
func encode(to container: inout PersistenceContainer) throws {
|
||||
container["column1"] = "test"
|
||||
container["column2"] = 12
|
||||
}
|
||||
}
|
||||
|
||||
struct Wrapper<Model: Encodable>: MutablePersistableRecord, Encodable {
|
||||
static var databaseTableName: String { "t1" }
|
||||
var model: Model
|
||||
var otherValue: String
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case otherValue
|
||||
}
|
||||
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var modelContainer = encoder.singleValueContainer()
|
||||
try modelContainer.encode(model)
|
||||
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(otherValue, forKey: .otherValue)
|
||||
}
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "t1") { t in
|
||||
t.column("column1", .text)
|
||||
t.column("column2", .integer)
|
||||
t.column("otherValue", .text)
|
||||
}
|
||||
|
||||
var value = Wrapper(model: Struct(value: "foo"), otherValue: "bar")
|
||||
try assert(value, isEncodedIn: ["column1": "test", "column2": 12, "otherValue": "bar"])
|
||||
|
||||
try value.insert(db)
|
||||
let row = try Row.fetchOne(db, sql: "SELECT column1, column2, otherValue FROM t1")!
|
||||
XCTAssertEqual(row[0], "test")
|
||||
XCTAssertEqual(row[1], 12)
|
||||
XCTAssertEqual(row[2], "bar")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Different kinds of single-value properties
|
||||
@@ -935,3 +844,68 @@ extension MutablePersistableRecordEncodableTests {
|
||||
fileprivate extension CodingUserInfoKey {
|
||||
static let testKey = CodingUserInfoKey(rawValue: "correct")!
|
||||
}
|
||||
|
||||
// MARK: - Super Encoders
|
||||
|
||||
extension MutablePersistableRecordEncodableTests {
|
||||
func testSuperEncoder() throws {
|
||||
// Gets compiler-synthesized `Codable` impl
|
||||
class CodableSup: Codable {
|
||||
var x: Int
|
||||
init(_ x: Int) { self.x = x }
|
||||
}
|
||||
|
||||
// We have to override init(from:) and encode(to:) to avoid inheriting them
|
||||
class CodableSub: CodableSup {
|
||||
var y: Int
|
||||
init(_ x: Int, _ y: Int) { self.y = y; super.init(x) }
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case y
|
||||
}
|
||||
|
||||
required init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
y = try container.decode(Int.self, forKey: .y)
|
||||
|
||||
// This will effectively fetch a nested container for key "super", then return a `Decoder` wrapping it
|
||||
let superDecoder = try container.superDecoder()
|
||||
try super.init(from: superDecoder)
|
||||
}
|
||||
|
||||
override func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(y, forKey: .y)
|
||||
|
||||
// This will effectively create a nested container for key "super", then return an `Encoder` wrapping it
|
||||
let superEncoder = container.superEncoder()
|
||||
try super.encode(to: superEncoder)
|
||||
}
|
||||
}
|
||||
|
||||
struct Record: PersistableRecord, Encodable {
|
||||
var id: String
|
||||
var value: CodableSup
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "record") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("value", .jsonText)
|
||||
}
|
||||
|
||||
do {
|
||||
try Record(id: "sup", value: CodableSup(42)).insert(db)
|
||||
let value = try String.fetchOne(db, sql: "SELECT value FROM record WHERE id = 'sup'")
|
||||
XCTAssertEqual(value, #"{"x":42}"#)
|
||||
}
|
||||
|
||||
do {
|
||||
try Record(id: "sub", value: CodableSub(42, 500)).insert(db)
|
||||
let value = try String.fetchOne(db, sql: "SELECT value FROM record WHERE id = 'sub'")
|
||||
XCTAssertEqual(value, #"{"super":{"x":42},"y":500}"#)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1526,15 +1526,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
sql(dbQueue, tableRequest.select(average(Col.age / 2, filter: Col.age > 0))),
|
||||
"SELECT AVG(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testCastExpression() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(cast(Col.name, as: .blob))),
|
||||
"SELECT CAST(\"name\" AS BLOB) FROM \"readers\"")
|
||||
}
|
||||
|
||||
|
||||
func testLengthExpression() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
private func myCast<T: SQLExpressible>(_ value: T, as type: Database.ColumnType) -> SQLExpression {
|
||||
private func cast<T: SQLExpressible>(_ value: T, as type: Database.ColumnType) -> SQLExpression {
|
||||
SQL("CAST(\(value) AS \(sql: type.rawValue))").sqlExpression
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase {
|
||||
try db.execute(sql: "INSERT INTO records (text) VALUES (?)", arguments: ["foo"])
|
||||
|
||||
do {
|
||||
let request = Record.select(myCast(Column("text"), as: .blob))
|
||||
let request = Record.select(cast(Column("text"), as: .blob))
|
||||
let dbValue = try DatabaseValue.fetchOne(db, request)!
|
||||
switch dbValue.storage {
|
||||
case .blob:
|
||||
@@ -30,7 +30,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase {
|
||||
XCTAssertEqual(self.lastSQLQuery, "SELECT CAST(\"text\" AS BLOB) FROM \"records\" LIMIT 1")
|
||||
}
|
||||
do {
|
||||
let request = Record.select(myCast(Column("text"), as: .blob) && true)
|
||||
let request = Record.select(cast(Column("text"), as: .blob) && true)
|
||||
_ = try DatabaseValue.fetchOne(db, request)!
|
||||
XCTAssertEqual(self.lastSQLQuery, "SELECT (CAST(\"text\" AS BLOB)) AND 1 FROM \"records\" LIMIT 1")
|
||||
}
|
||||
|
||||
@@ -274,10 +274,6 @@ class SQLExpressionIsConstantTests: GRDBTestCase {
|
||||
XCTAssertFalse((Column("a") - 2.databaseValue).isConstantInRequest)
|
||||
XCTAssertFalse((1.databaseValue - Column("a")).isConstantInRequest)
|
||||
|
||||
// CAST
|
||||
XCTAssertTrue(cast(1.databaseValue, as: .real).isConstantInRequest)
|
||||
XCTAssertFalse(cast(Column("a"), as: .real).isConstantInRequest)
|
||||
|
||||
// SQLExpressionCollate
|
||||
XCTAssertTrue("foo".databaseValue.collating(.binary).isConstantInRequest)
|
||||
XCTAssertFalse(Column("a").collating(.binary).isConstantInRequest)
|
||||
|
||||
@@ -2,22 +2,6 @@ import XCTest
|
||||
import GRDB
|
||||
|
||||
class SharedValueObservationTests: GRDBTestCase {
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
func testInitFromAnyDatabaseReader(reader: any DatabaseReader) {
|
||||
_ = ValueObservation
|
||||
.trackingConstantRegion { _ in }
|
||||
.shared(in: reader)
|
||||
}
|
||||
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
func testInitFromAnyDatabaseWriter(writer: any DatabaseWriter) {
|
||||
_ = ValueObservation
|
||||
.trackingConstantRegion { _ in }
|
||||
.shared(in: writer)
|
||||
}
|
||||
|
||||
func test_immediate_observationLifetime() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
|
||||
@@ -31,7 +31,7 @@ extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func find(_ db: Database) throws -> AppConfiguration {
|
||||
static func fetch(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
// When
|
||||
let config = try AppConfiguration.find(db)
|
||||
let config = try AppConfiguration.fetch(db)
|
||||
// Then
|
||||
XCTAssertEqual(config.text, "default")
|
||||
}
|
||||
@@ -66,7 +66,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
try AppConfiguration(text: "initial").insert(db)
|
||||
// When
|
||||
let config = try AppConfiguration.find(db)
|
||||
let config = try AppConfiguration.fetch(db)
|
||||
// Then
|
||||
XCTAssertEqual(config.text, "initial")
|
||||
}
|
||||
@@ -79,7 +79,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").insert(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -93,7 +93,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").insert(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -106,7 +106,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").update(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -120,7 +120,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").update(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -131,12 +131,12 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
// When
|
||||
var config = try AppConfiguration.find(db)
|
||||
var config = try AppConfiguration.fetch(db)
|
||||
try config.updateChanges(db) {
|
||||
$0.text = "test"
|
||||
}
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -148,12 +148,12 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
try AppConfiguration(text: "initial").insert(db)
|
||||
// When
|
||||
var config = try AppConfiguration.find(db)
|
||||
var config = try AppConfiguration.fetch(db)
|
||||
try config.updateChanges(db) {
|
||||
$0.text = "test"
|
||||
}
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -166,7 +166,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").save(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -180,7 +180,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").save(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -203,7 +203,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").upsert(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
@@ -227,7 +227,7 @@ class SingletonRecordTest: GRDBTestCase {
|
||||
// When
|
||||
try AppConfiguration(text: "test").upsert(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.fetch(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "text": "test"])
|
||||
}
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
private struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// The stored properties
|
||||
private var storedText: String?
|
||||
// ... other properties
|
||||
|
||||
// The public properties
|
||||
var text: String {
|
||||
get { storedText ?? "default" }
|
||||
set { storedText = newValue }
|
||||
}
|
||||
|
||||
mutating func resetText() {
|
||||
storedText = nil
|
||||
}
|
||||
}
|
||||
|
||||
extension AppConfiguration {
|
||||
/// The default configuration
|
||||
static let `default` = AppConfiguration()
|
||||
}
|
||||
|
||||
// Database Access
|
||||
extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
// Customize the default PersistableRecord behavior
|
||||
func willUpdate(_ db: Database, columns: Set<String>) throws {
|
||||
// Insert the default configuration if it does not exist yet.
|
||||
if try !exists(db) {
|
||||
try AppConfiguration.default.insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func find(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
|
||||
class SingletonUserDefaultsTest: GRDBTestCase {
|
||||
private func createEmptyAppConfigurationTable(_ db: Database) throws {
|
||||
// Table creation
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("storedText", .text)
|
||||
// ... other columns
|
||||
}
|
||||
}
|
||||
|
||||
func test_find_in_empty_database() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
// When
|
||||
let config = try AppConfiguration.find(db)
|
||||
// Then
|
||||
XCTAssertEqual(config.text, "default")
|
||||
}
|
||||
}
|
||||
|
||||
func test_find_in_populated_database_null() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
try AppConfiguration().insert(db)
|
||||
// When
|
||||
let config = try AppConfiguration.find(db)
|
||||
// Then
|
||||
XCTAssertEqual(config.text, "default")
|
||||
}
|
||||
}
|
||||
|
||||
func test_find_from_populated_database_not_null() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
try db.execute(sql: "INSERT INTO appConfiguration(storedText) VALUES ('initial')")
|
||||
// When
|
||||
let config = try AppConfiguration.find(db)
|
||||
// Then
|
||||
XCTAssertEqual(config.text, "initial")
|
||||
}
|
||||
}
|
||||
|
||||
func test_save_in_empty_database() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
// When
|
||||
var appConfiguration = try AppConfiguration.find(db)
|
||||
appConfiguration.text = "test"
|
||||
try appConfiguration.save(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "storedText": "test"])
|
||||
}
|
||||
}
|
||||
|
||||
func test_save_in_populated_database() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
try db.execute(sql: "INSERT INTO appConfiguration(storedText) VALUES ('initial')")
|
||||
// When
|
||||
var appConfiguration = try AppConfiguration.find(db)
|
||||
appConfiguration.text = "test"
|
||||
try appConfiguration.save(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "storedText": "test"])
|
||||
}
|
||||
}
|
||||
|
||||
func test_reset_and_save_in_populated_database() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
try db.execute(sql: "INSERT INTO appConfiguration(storedText) VALUES ('initial')")
|
||||
// When
|
||||
var appConfiguration = try AppConfiguration.find(db)
|
||||
appConfiguration.resetText()
|
||||
try appConfiguration.save(db)
|
||||
// Then
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "default")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "storedText": nil])
|
||||
}
|
||||
}
|
||||
|
||||
func test_update_changes_in_empty_database() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
// When
|
||||
var config = try AppConfiguration.find(db)
|
||||
try config.updateChanges(db) {
|
||||
$0.text = "test"
|
||||
}
|
||||
// Then
|
||||
XCTAssertEqual(config.text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "storedText": "test"])
|
||||
}
|
||||
}
|
||||
|
||||
func test_update_changes_in_populated_database() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Given
|
||||
try createEmptyAppConfigurationTable(db)
|
||||
try db.execute(sql: "INSERT INTO appConfiguration(storedText) VALUES ('initial')")
|
||||
// When
|
||||
var config = try AppConfiguration.find(db)
|
||||
try config.updateChanges(db) {
|
||||
$0.text = "test"
|
||||
}
|
||||
// Then
|
||||
XCTAssertEqual(config.text, "test")
|
||||
try XCTAssertEqual(AppConfiguration.find(db).text, "test")
|
||||
let row = try XCTUnwrap(Row.fetchOne(db, sql: "SELECT * FROM appConfiguration"))
|
||||
XCTAssertEqual(row, ["id": 1, "storedText": "test"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -364,30 +364,6 @@ class TableRecordDeleteTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) // Identifiable
|
||||
func testRequestDeleteAndFetchIds() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
guard sqlite3_libversion_number() >= 3035000 else {
|
||||
throw XCTSkip("RETURNING clause is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
|
||||
throw XCTSkip("RETURNING clause is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try Person(id: 1, name: "Arthur", email: "arthur@example.com").insert(db)
|
||||
try Person(id: 2, name: "Barbara", email: "barbara@example.com").insert(db)
|
||||
try Person(id: 3, name: "Craig", email: "craig@example.com").insert(db)
|
||||
|
||||
let request = Person.filter(Column("id") != 2)
|
||||
let deletedIds = try request.deleteAndFetchIds(db)
|
||||
XCTAssertEqual(deletedIds, [1, 3])
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedRequestDeleteAll() throws {
|
||||
try makeDatabaseQueue().inDatabase { db in
|
||||
struct Player: MutablePersistableRecord {
|
||||
|
||||
@@ -3,33 +3,6 @@ import Dispatch
|
||||
@testable import GRDB
|
||||
|
||||
class ValueObservationTests: GRDBTestCase {
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
func testStartFromAnyDatabaseReader(reader: any DatabaseReader) {
|
||||
_ = ValueObservation
|
||||
.trackingConstantRegion { _ in }
|
||||
.start(in: reader, onError: { _ in }, onChange: { })
|
||||
}
|
||||
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
func testStartFromAnyDatabaseWriter(writer: any DatabaseWriter) {
|
||||
_ = ValueObservation
|
||||
.trackingConstantRegion { _ in }
|
||||
.start(in: writer, onError: { _ in }, onChange: { })
|
||||
}
|
||||
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
func testValuesFromAnyDatabaseWriter(writer: any DatabaseWriter) {
|
||||
func observe<T>(
|
||||
fetch: @Sendable @escaping (Database) throws -> T
|
||||
) throws -> AsyncValueObservation<T> {
|
||||
ValueObservation.tracking(fetch).values(in: writer)
|
||||
}
|
||||
}
|
||||
|
||||
func testImmediateError() throws {
|
||||
struct TestError: Error { }
|
||||
|
||||
@@ -775,53 +748,6 @@ class ValueObservationTests: GRDBTestCase {
|
||||
try test(makeDatabasePool())
|
||||
}
|
||||
|
||||
func testIssue1550() throws {
|
||||
func test(_ writer: some DatabaseWriter) throws {
|
||||
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
|
||||
|
||||
// Start observing
|
||||
var counts: [Int] = []
|
||||
let cancellable = ValueObservation
|
||||
.trackingConstantRegion { try Table("t").fetchCount($0) }
|
||||
.start(in: writer) { error in
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
} onChange: { count in
|
||||
counts.append(count)
|
||||
}
|
||||
|
||||
// Perform a write after cancellation, but before the
|
||||
// observation could schedule the removal of its transaction
|
||||
// observer from the writer dispatch queue.
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
writer.asyncWriteWithoutTransaction { db in
|
||||
semaphore.wait()
|
||||
do {
|
||||
try db.execute(sql: "INSERT INTO t(id) VALUES (NULL)")
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
}
|
||||
cancellable.cancel()
|
||||
semaphore.signal()
|
||||
|
||||
// Wait until a second write could run, after the observation
|
||||
// has removed its transaction observer from the writer
|
||||
// dispatch queue.
|
||||
let secondWriteExpectation = expectation(description: "cancelled")
|
||||
writer.asyncWriteWithoutTransaction { _ in
|
||||
secondWriteExpectation.fulfill()
|
||||
}
|
||||
wait(for: [secondWriteExpectation], timeout: 5)
|
||||
|
||||
// We should not have been notified of the first write, because
|
||||
// it was performed after cancellation.
|
||||
XCTAssertFalse(counts.contains(1))
|
||||
}
|
||||
|
||||
try test(makeDatabaseQueue())
|
||||
try test(makeDatabasePool())
|
||||
}
|
||||
|
||||
func testIssue1209() throws {
|
||||
func test(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 54;
|
||||
objectVersion = 52;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
|
||||
+9
-10
@@ -1,13 +1,12 @@
|
||||
{
|
||||
"originHash" : "8d182a38fc35b0d50c198e0cbd39dc7fa5922eae5336ff3b0c73c2d51bcba752",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "fmdb",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/ccgus/fmdb.git",
|
||||
"state" : {
|
||||
"revision" : "47a2fa12a242b5a2fe13b916c22f2212e426055c",
|
||||
"version" : "2.7.9"
|
||||
"revision" : "61e51fde7f7aab6554f30ab061cc588b28a97d04",
|
||||
"version" : "2.7.7"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -15,8 +14,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/realm/realm-core.git",
|
||||
"state" : {
|
||||
"revision" : "374dd672af357732dccc135fecc905406fec3223",
|
||||
"version" : "14.4.1"
|
||||
"revision" : "f0045b71f9d3e9a6d82c711828f14222811fa6e9",
|
||||
"version" : "13.9.4"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -24,8 +23,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/realm/realm-swift.git",
|
||||
"state" : {
|
||||
"revision" : "e0c2fbb442979fbf1e4be80e01d142f310a9c762",
|
||||
"version" : "10.49.1"
|
||||
"revision" : "00e098a61acdf5e8cee4e2a6292c9ec6762ba1b4",
|
||||
"version" : "10.38.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -33,10 +32,10 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/stephencelis/SQLite.swift.git",
|
||||
"state" : {
|
||||
"revision" : "e78ae0220e17525a15ac68c697a155eb7a672a8e",
|
||||
"version" : "0.15.0"
|
||||
"revision" : "7a2e3cd27de56f6d396e84f63beefd0267b55ccb",
|
||||
"version" : "0.14.1"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
"version" : 2
|
||||
}
|
||||
Reference in new issue
Block a user