Compare commits

...
Author SHA1 Message Date
Gwendal Roué 4c541a99b5 Min iOS target: v18 2024-09-14 12:23:07 +02:00
Gwendal Roué 2cf6c756e1 Merge branch 'development' 2024-09-07 14:20:48 +02:00
Gwendal Roué d56223cba1 v6.29.3 2024-09-07 12:59:25 +02:00
Gwendal Roué bc4fd8ff58 Merge pull request #1613 from groue/dev/fix-1612
Avoid SQLite misuse when releasing memory on a closed database connection
2024-09-07 12:56:16 +02:00
Gwendal Roué cdb181d9ca Don't invoke sqlite3_db_release_memory on closed database connections 2024-09-04 09:21:30 +02:00
Gwendal Roué f4b4035704 Fix Swiftlint warnings 2024-08-24 14:39:44 +02:00
Gwendal Roué 57a4587b5b Merge branch 'development' 2024-08-24 14:30:20 +02:00
Gwendal Roué ae837a3a44 v6.29.2 2024-08-24 11:46:45 +02:00
Gwendal Roué c64bc11627 Remove ill-advised TODO
This would force users to force-unwrap their custom `ColumnType(rawValue: "WHATEVER")!`
2024-08-24 11:38:37 +02:00
Gwendal Roué de96d5f6f0 Merge pull request #1595 from groue/dev/string_h
Enhance imports for strcmp
2024-08-24 11:33:39 +02:00
Gwendal Roué d3d2a9c4f7 Stop testing error messages that depend on the SQLite version 2024-08-24 10:26:34 +02:00
Gwendal Roué f10c74c374 Merge pull request #1593 from mingchen/development
README.md: Fix sample code
2024-08-22 09:13:28 +02:00
Gwendal Roué fcfdab2f11 Import string_h for strcmp
Thanks to @karianneberg in https://github.com/groue/GRDB.swift/commit/344878cdb2e3af07f46954e3bc2b93541489bd82
2024-08-22 08:17:04 +02:00
Ming C. f441341543 README.md: Fix sample code 2024-08-17 11:43:05 -07:00
Gwendal Roué dd6b98ce04 Merge branch 'development' 2024-08-07 12:18:34 +02:00
Gwendal Roué 5b73581126 v6.29.1 2024-08-07 12:16:57 +02:00
Gwendal Roué 9a896650ff Merge pull request #1589 from noremac/development
Fix compilation issue with Xcode 16 beta 5 due to a missing import.
2024-08-07 12:11:38 +02:00
Cameron Pulsford 344878cdb2 Fix compilation issue with Xcode 16 beta 5 due to a missing import. 2024-08-06 19:46:09 -04:00
Gwendal Roué 20ffddd572 Update TODO.md 2024-07-31 12:51:26 +02:00
Gwendal Roué 4ddb6b89ce Merge pull request #1584 from SagarSDagdu/update-cocoapods-instructions
Update README to highlight deployment issue with CocoaPods
2024-07-30 17:34:26 +02:00
Sagar DagduandGwendal Roué 9da1a83cca Fix indentation for code blocks
Co-authored-by: Gwendal Roué <gr@pierlis.com>
2024-07-30 21:00:14 +05:30
Sagar Dagdu 8205f02672 Address code review comments 2024-07-30 20:54:24 +05:30
Sagar Dagdu 78377d5cc0 Update README to highlight deployment issue with CocoaPods 2024-07-30 20:21:26 +05:30
Gwendal Roué 04543755d8 Merge pull request #1579 from groue/dev/modernize-demo-apps
Modernise the demo apps
2024-07-21 11:25:36 +02:00
Gwendal Roué cdc0131369 Modernize demo apps:
iOS 17+
GRDBQuery 0.9.0
#Preview macro
2024-07-20 14:38:14 +02:00
Gwendal Roué 1cd6c7cbff Merge branch 'development' 2024-07-20 11:22:16 +02:00
Gwendal Roué bbbe0d899d v6.29.0 2024-07-20 11:17:13 +02:00
Gwendal Roué 9f16865ff1 Merge pull request #1575 from Jason-Abbott/development
Show trigger comments for expanded statement tracing
2024-07-17 18:21:56 +02:00
Jason Abbott 14d2b931a4 Also return untrimmed comments when tracing without visible values 2024-07-17 09:17:03 -06:00
Jason Abbott 802b4ca78a Correct suffix/prefix test 2024-07-16 16:57:57 -06:00
Jason Abbott 1c60e5ef42 Show trigger comments for expanded statement tracing 2024-07-16 16:51:50 -06:00
Gwendal Roué 9f41e56c32 Merge pull request #1574 from sroebert/feature/single-value-container-decoding
Support for single value decoding
2024-07-13 17:07:15 +02:00
Steven RoebertandGwendal Roué 0ae3f32f7f Added compiler checks for Swift 6 specific code
Co-authored-by: Gwendal Roué <gr@pierlis.com>
2024-07-13 12:53:00 +02:00
Steven Roebert c977cb8226 Implemented support for single value decoding in _RowDecoder 2024-07-13 11:48:02 +02:00
Gwendal Roué 78448cf8f4 Merge branch 'development' 2024-07-11 07:49:09 +02:00
Gwendal Roué 30de9853d6 v6.28.0 2024-07-11 07:48:54 +02:00
Gwendal Roué 7a1196263d CHANGELOG 2024-07-11 07:46:32 +02:00
Gwendal Roué 3043d7dca5 DatabaseUUIDEncodingStrategy is Sendable
Fix #1567
2024-07-11 07:46:23 +02:00
Gwendal Roué d2dd757d0c CHANGELOG 2024-07-11 07:44:30 +02:00
Gwendal Roué 764ad4bf72 Merge pull request #1570 from groue/dev/single-value-encoding
Support single-value encoding
2024-07-11 07:42:41 +02:00
Gwendal Roué e6d4223b14 EncodableRecord takes precedence over Encodable when a record is encoded with a SingleValueEncodingContainer. 2024-07-10 08:47:49 +02:00
Gwendal Roué ba3c938eb9 Fix failing test for #1565 2024-07-09 13:42:52 +02:00
Gwendal Roué 5999227c01 Failing test for #1565 2024-07-09 13:31:54 +02:00
Gwendal Roué 78545f2c8c Tests for #1541 2024-06-09 13:02:27 +02:00
Gwendal Roué 263a549c21 Test that a cancelled ValueObservation does not notify of changes that were enqueued before cancellation.
This is a test for #1550
2024-06-08 13:47:21 +02:00
Gwendal Roué 6689470457 Remove Double infinities from database dump tests
Some SQLite versions store or read +inf and -inf as 9.0e+999 and -9.0e+999, and this makes some tests fail.

Known failure: SQLCipher4, test_quote_value_formatting(), https://github.com/groue/GRDB.swift/actions/runs/9388768610/job/25854709627

I could not reproduce.
2024-06-06 07:50:02 +02:00
Gwendal Roué bbbd6bba90 Add Set methods union, formUnion, intersection and formIntersection that accept a cursor. 2024-06-05 19:38:16 +02:00
Gwendal Roué bb789e3dee QueryInterfaceRequest.deleteAndFetchIds 2024-06-05 18:42:36 +02:00
Gwendal Roué b312d4cf5a Add missing DocC links to cast(_:as:) 2024-06-05 18:36:24 +02:00
Gwendal Roué f335123c2b Update link to SQLite RETURNING caveats 2024-06-05 18:23:56 +02:00
Gwendal Roué 34d87c0e85 Merge pull request #1544 from JoeParker/fix-cte-doc-example
Fix error in CTE association documentation
2024-06-02 12:09:59 +02:00
Joe Parker 0f2e993790 Update example snippet in CommonTableExpressions.md 2024-05-10 17:19:01 +01:00
Gwendal Roué 1831017d64 TODO
Related issue: https://github.com/groue/GRDB.swift/issues/1539
2024-05-01 13:38:14 +02:00
Gwendal Roué 4b934fda75 Fix link 2024-04-21 17:47:03 +02:00
Gwendal Roué 53c40fd80f Fix Swiftlint warning 2024-04-21 17:45:58 +02:00
57 changed files with 850 additions and 252 deletions

No files matched your search

+39 -1
View File
@@ -7,6 +7,8 @@ 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)
@@ -125,12 +127,48 @@ 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](Documentation/SingleRowTables.md) guide was updated with guidance about default configuration values.
- **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
+1 -1
View File
@@ -251,7 +251,7 @@ let rightCTE = ...
let association = LeftRecord.association(
to: rightCTE,
on: { left, right in
left[Column("x")] = right[Column("y")]
left[Column("x")] == right[Column("y")]
})
```
@@ -354,6 +354,7 @@
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = GRDBAsyncDemoTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -373,6 +374,7 @@
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = GRDBAsyncDemoTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -512,7 +514,7 @@
DEVELOPMENT_TEAM = "";
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBAsyncDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -534,7 +536,7 @@
DEVELOPMENT_TEAM = "";
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBAsyncDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -5,8 +5,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/groue/GRDBQuery",
"state" : {
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
"version" : "0.6.0"
"revision" : "a6c46dd38ecf11a5c37732870dc03a384d582fba",
"version" : "0.9.0"
}
}
],
@@ -5,17 +5,12 @@ import SwiftUI
struct GRDBAsyncDemoApp: App {
var body: some Scene {
WindowGroup {
AppView().environment(\.appDatabase, .shared)
AppView().appDatabase(.shared)
}
}
}
// MARK: - Give SwiftUI access to the database
//
// Define a new environment key that grants access to an AppDatabase.
//
// The technique is documented at
// <https://developer.apple.com/documentation/swiftui/environmentkey>.
private struct AppDatabaseKey: EnvironmentKey {
static var defaultValue: AppDatabase { .empty() }
@@ -28,13 +23,10 @@ extension EnvironmentValues {
}
}
// In this demo app, views observe the database with the @Query property
// wrapper, defined in the GRDBQuery package. Its documentation recommends to
// define a dedicated initializer for `appDatabase` access, so we comply:
extension Query where Request.DatabaseContext == AppDatabase {
/// Convenience initializer for requests that feed from `AppDatabase`.
init(_ request: Request) {
self.init(request, in: \.appDatabase)
extension View {
func appDatabase(_ appDatabase: AppDatabase) -> some View {
self
.environment(\.appDatabase, appDatabase)
.databaseContext(.readOnly { appDatabase.reader })
}
}
@@ -1,4 +1,3 @@
import Combine
import GRDB
import GRDBQuery
@@ -14,37 +13,18 @@ import GRDBQuery
/// List(players) { player in ... )
/// }
/// }
struct PlayerRequest: Queryable {
struct PlayerRequest: ValueObservationQueryable {
enum Ordering {
case byScore
case byName
}
static var defaultValue: [Player] { [] }
/// The ordering used by the player request.
var ordering: Ordering
// MARK: - Queryable Implementation
static var defaultValue: [Player] { [] }
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
// Build the publisher from the general-purpose read-only access
// granted by `appDatabase.reader`.
// Some apps will prefer to call a dedicated method of `appDatabase`.
ValueObservation
.tracking(fetchValue(_:))
.publisher(
in: appDatabase.reader,
// The `.immediate` scheduling feeds the view right on
// subscription, and avoids an undesired animation when the
// application starts.
scheduling: .immediate)
.eraseToAnyPublisher()
}
// This method is not required by Queryable, but it makes it easier
// to test PlayerRequest.
func fetchValue(_ db: Database) throws -> [Player] {
func fetch(_ db: Database) throws -> [Player] {
switch ordering {
case .byScore:
return try Player.all().orderedByScore().fetchAll(db)
@@ -43,7 +43,7 @@ struct AppView: View {
stopEditing()
}))
.toolbar { toolbarContent }
.onChange(of: players) { players in
.onChange(of: players) {
if players.isEmpty {
stopEditing()
}
@@ -141,14 +141,14 @@ private struct ToggleOrderingButton: View {
}
}
struct AppView_Previews: PreviewProvider {
static var previews: some View {
Group {
// Preview the default, empty database
AppView()
// Preview a database of random players
AppView().environment(\.appDatabase, .random())
}
}
// MARK: - Previews
#Preview("Empty") {
// Preview the default, empty database
AppView()
}
#Preview("Populated") {
// Preview a database of random players
AppView().appDatabase(.random())
}
@@ -43,8 +43,8 @@ struct PlayerCreationView: View {
}
}
struct PlayerCreationSheet_Previews: PreviewProvider {
static var previews: some View {
PlayerCreationView()
}
// MARK: - Previews
#Preview {
PlayerCreationView()
}
@@ -15,7 +15,7 @@ struct PlayerEditionView: View {
var body: some View {
PlayerFormView(form: $form)
.onChange(of: isPresented) { isPresented in
.onChange(of: isPresented) {
// Save when back button is pressed
if !isPresented {
Task {
@@ -30,11 +30,11 @@ struct PlayerEditionView: View {
}
}
struct PlayerEditionView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PlayerEditionView(player: Player.makeRandom())
.navigationBarTitle("Player Edition")
}
// MARK: - Previews
#Preview {
NavigationView {
PlayerEditionView(player: Player.makeRandom())
.navigationBarTitle("Player Edition")
}
}
@@ -33,15 +33,16 @@ extension PlayerForm {
}
}
struct PlayerFormView_Previews: PreviewProvider {
static var previews: some View {
Group {
PlayerFormView(form: .constant(PlayerForm(
name: "",
score: "")))
PlayerFormView(form: .constant(PlayerForm(
name: Player.randomName(),
score: "\(Player.randomScore())")))
}
}
// MARK: - Previews
#Preview("Empty") {
PlayerFormView(form: .constant(PlayerForm(
name: "",
score: "")))
}
#Preview("Prefilled") {
PlayerFormView(form: .constant(PlayerForm(
name: Player.randomName(),
score: "\(Player.randomScore())")))
}
@@ -46,14 +46,14 @@ private struct PlayerRow: View {
}
}
struct PlayerList_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PlayerList(players: [
Player(id: 1, name: "Arthur", score: 100),
Player(id: 2, name: "Barbara", score: 1000),
])
.navigationTitle("Preview")
}
// MARK: - Previews
#Preview {
NavigationView {
PlayerList(players: [
Player(id: 1, name: "Arthur", score: 100),
Player(id: 2, name: "Barbara", score: 1000),
])
.navigationTitle("Preview")
}
}
@@ -16,7 +16,7 @@ class PlayerRequestTests: XCTestCase {
// When we fetch players ordered by name
let playerRequest = PlayerRequest(ordering: .byName)
let players = try dbQueue.read(playerRequest.fetchValue)
let players = try dbQueue.read(playerRequest.fetch)
// Then the players are the two players ordered by name
XCTAssertEqual(players, [player1, player2])
@@ -35,7 +35,7 @@ class PlayerRequestTests: XCTestCase {
// When we fetch players ordered by score
let playerRequest = PlayerRequest(ordering: .byScore)
let players = try dbQueue.read(playerRequest.fetchValue)
let players = try dbQueue.read(playerRequest.fetch)
// Then the players are the two players ordered by score descending
XCTAssertEqual(players, [player2, player1])
@@ -354,6 +354,7 @@
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -373,6 +374,7 @@
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -512,6 +514,7 @@
DEVELOPMENT_TEAM = "";
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -533,6 +536,7 @@
DEVELOPMENT_TEAM = "";
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -5,8 +5,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/groue/GRDBQuery",
"state" : {
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
"version" : "0.6.0"
"revision" : "a6c46dd38ecf11a5c37732870dc03a384d582fba",
"version" : "0.9.0"
}
}
],
@@ -5,17 +5,12 @@ import SwiftUI
struct GRDBCombineDemoApp: App {
var body: some Scene {
WindowGroup {
AppView().environment(\.appDatabase, .shared)
AppView().appDatabase(.shared)
}
}
}
// MARK: - Give SwiftUI access to the database
//
// Define a new environment key that grants access to an AppDatabase.
//
// The technique is documented at
// <https://developer.apple.com/documentation/swiftui/environmentkey>.
private struct AppDatabaseKey: EnvironmentKey {
static var defaultValue: AppDatabase { .empty() }
@@ -28,13 +23,10 @@ extension EnvironmentValues {
}
}
// In this demo app, views observe the database with the @Query property
// wrapper, defined in the GRDBQuery package. Its documentation recommends to
// define a dedicated initializer for `appDatabase` access, so we comply:
extension Query where Request.DatabaseContext == AppDatabase {
/// Convenience initializer for requests that feed from `AppDatabase`.
init(_ request: Request) {
self.init(request, in: \.appDatabase)
extension View {
func appDatabase(_ appDatabase: AppDatabase) -> some View {
self
.environment(\.appDatabase, appDatabase)
.databaseContext(.readOnly { appDatabase.reader })
}
}
@@ -1,4 +1,3 @@
import Combine
import GRDB
import GRDBQuery
@@ -14,37 +13,18 @@ import GRDBQuery
/// List(players) { player in ... )
/// }
/// }
struct PlayerRequest: Queryable {
struct PlayerRequest: ValueObservationQueryable {
enum Ordering {
case byScore
case byName
}
static var defaultValue: [Player] { [] }
/// The ordering used by the player request.
var ordering: Ordering
// MARK: - Queryable Implementation
static var defaultValue: [Player] { [] }
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
// Build the publisher from the general-purpose read-only access
// granted by `appDatabase.reader`.
// Some apps will prefer to call a dedicated method of `appDatabase`.
ValueObservation
.tracking(fetchValue(_:))
.publisher(
in: appDatabase.reader,
// The `.immediate` scheduling feeds the view right on
// subscription, and avoids an undesired animation when the
// application starts.
scheduling: .immediate)
.eraseToAnyPublisher()
}
// This method is not required by Queryable, but it makes it easier
// to test PlayerRequest.
func fetchValue(_ db: Database) throws -> [Player] {
func fetch(_ db: Database) throws -> [Player] {
switch ordering {
case .byScore:
return try Player.all().orderedByScore().fetchAll(db)
@@ -43,7 +43,7 @@ struct AppView: View {
stopEditing()
}))
.toolbar { toolbarContent }
.onChange(of: players) { players in
.onChange(of: players) {
if players.isEmpty {
stopEditing()
}
@@ -132,14 +132,14 @@ private struct ToggleOrderingButton: View {
}
}
struct AppView_Previews: PreviewProvider {
static var previews: some View {
Group {
// Preview the default, empty database
AppView()
// Preview a database of random players
AppView().environment(\.appDatabase, .random())
}
}
// MARK: - Previews
#Preview("Empty") {
// Preview the default, empty database
AppView()
}
#Preview("Populated") {
// Preview a database of random players
AppView().appDatabase(.random())
}
@@ -43,8 +43,8 @@ struct PlayerCreationView: View {
}
}
struct PlayerCreationSheet_Previews: PreviewProvider {
static var previews: some View {
PlayerCreationView()
}
// MARK: - Previews
#Preview {
PlayerCreationView()
}
@@ -15,7 +15,7 @@ struct PlayerEditionView: View {
var body: some View {
PlayerFormView(form: $form)
.onChange(of: isPresented) { isPresented in
.onChange(of: isPresented) {
// Save when back button is pressed
if !isPresented {
var savedPlayer = player
@@ -28,11 +28,11 @@ struct PlayerEditionView: View {
}
}
struct PlayerEditionView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PlayerEditionView(player: Player.makeRandom())
.navigationBarTitle("Player Edition")
}
// MARK: - Previews
#Preview {
NavigationView {
PlayerEditionView(player: Player.makeRandom())
.navigationBarTitle("Player Edition")
}
}
@@ -33,15 +33,16 @@ extension PlayerForm {
}
}
struct PlayerFormView_Previews: PreviewProvider {
static var previews: some View {
Group {
PlayerFormView(form: .constant(PlayerForm(
name: "",
score: "")))
PlayerFormView(form: .constant(PlayerForm(
name: Player.randomName(),
score: "\(Player.randomScore())")))
}
}
// MARK: - Previews
#Preview("Empty") {
PlayerFormView(form: .constant(PlayerForm(
name: "",
score: "")))
}
#Preview("Prefilled") {
PlayerFormView(form: .constant(PlayerForm(
name: Player.randomName(),
score: "\(Player.randomScore())")))
}
@@ -44,14 +44,14 @@ private struct PlayerRow: View {
}
}
struct PlayerList_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PlayerList(players: [
Player(id: 1, name: "Arthur", score: 100),
Player(id: 2, name: "Barbara", score: 1000),
])
.navigationTitle("Preview")
}
// MARK: - Previews
#Preview {
NavigationView {
PlayerList(players: [
Player(id: 1, name: "Arthur", score: 100),
Player(id: 2, name: "Barbara", score: 1000),
])
.navigationTitle("Preview")
}
}
@@ -16,7 +16,7 @@ class PlayerRequestTests: XCTestCase {
// When we fetch players ordered by name
let playerRequest = PlayerRequest(ordering: .byName)
let players = try dbQueue.read(playerRequest.fetchValue)
let players = try dbQueue.read(playerRequest.fetch)
// Then the players are the two players ordered by name
XCTAssertEqual(players, [player1, player2])
@@ -35,7 +35,7 @@ class PlayerRequestTests: XCTestCase {
// When we fetch players ordered by score
let playerRequest = PlayerRequest(ordering: .byScore)
let players = try dbQueue.read(playerRequest.fetchValue)
let players = try dbQueue.read(playerRequest.fetch)
// Then the players are the two players ordered by score descending
XCTAssertEqual(players, [player2, player1])
@@ -588,6 +588,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
GCC_C_LANGUAGE_STANDARD = gnu11;
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -614,6 +615,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
GCC_C_LANGUAGE_STANDARD = gnu11;
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -828,6 +830,7 @@
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -845,6 +848,7 @@
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
+4 -2
View File
@@ -18,8 +18,10 @@ To release a new GRDB version:
- README.md
- Support/Info.plist
- Commit and tag
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
- Push to the master & development branch
- Look for undesired tags: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
- Push to the `master` branch
- Push to the `development` branch
- Push to the `GRDB6` branch
- `pod trunk push --allow-warnings GRDB.swift.podspec`
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '6.27.0'
s.version = '6.29.3'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+50
View File
@@ -195,6 +195,56 @@ extension Set {
// database cursors.
try cursor.forEach { insert($0) }
}
/// Returns a new set with the elements of both this set and the
/// given cursor.
///
/// If the set already contains one or more elements that are also in
/// the cursor, the existing members are kept. If the cursor contains
/// multiple instances of equivalent elements, only the first instance
/// is kept.
///
/// - parameter cursor: A cursor of elements.
/// - returns: A new set with the unique elements of this set
/// and `cursor`.
public func union(_ cursor: some Cursor<Element>) throws -> Set<Element> {
var result = self
try result.formUnion(cursor)
return result
}
/// Inserts the elements of the given cursor into the set.
///
/// If the set already contains one or more elements that are also in
/// the cursor, the existing members are kept. If the cursor contains
/// multiple instances of equivalent elements, only the first instance
/// is kept.
///
/// - parameter cursor: A cursor of elements.
public mutating func formUnion(_ cursor: some Cursor<Element>) throws {
while let element = try cursor.next() {
insert(element)
}
}
/// Returns a new set with the elements that are common to both this set
/// and the given cursor.
///
/// - parameter cursor: A cursor of elements.
/// - returns: A new set.
public func intersection(_ cursor: some Cursor<Element>) throws -> Set<Element> {
var result = self
try result.formIntersection(cursor)
return result
}
/// Removes the elements of the set that aren’t also in the
/// given cursor.
///
/// - parameter cursor: A cursor of elements.
public mutating func formIntersection(_ cursor: some Cursor<Element>) throws {
try formIntersection(Set(cursor))
}
}
extension Sequence {
+9 -5
View File
@@ -124,8 +124,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// MARK: - SQLite C API
// TODO: make it non optional, since one can't get a `Database` instance
// after `close()`.
/// The raw SQLite connection, suitable for the SQLite C API.
///
/// The result is nil after the database has been successfully closed with
@@ -1577,7 +1575,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// Frees as much memory as possible.
public func releaseMemory() {
SchedulingWatchdog.preconditionValidQueue(self)
sqlite3_db_release_memory(sqliteConnection)
if let sqliteConnection {
sqlite3_db_release_memory(sqliteConnection)
}
schemaCache.clear()
internalStatementCache.clear()
publicStatementCache.clear()
@@ -1923,7 +1923,6 @@ 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
@@ -2083,7 +2082,8 @@ extension Database {
/// ```
public var sql: String {
if let unexpandedSQL {
return String(cString: unexpandedSQL).trimmedSQLStatement
let sql = String(cString: unexpandedSQL)
return sql.hasPrefix("--") ? sql : sql.trimmedSQLStatement
} else {
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
}
@@ -2101,6 +2101,10 @@ extension Database {
/// information from leaking in unexpected locations, so use this
/// property with care.
public var expandedSQL: String {
if let unexpandedSQL {
let sql = String(cString: unexpandedSQL)
if sql.hasPrefix("--") { return sql }
}
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
return ""
}
+5 -1
View File
@@ -1,5 +1,9 @@
#if os(Linux)
#if canImport(string_h)
import string_h
#elseif os(Linux)
import Glibc
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
import Darwin
#endif
/// `StatementAuthorizer` provides information about compiled database
@@ -4,7 +4,6 @@ import Foundation
@usableFromInline
struct SQLiteDateParser {
// swiftlint:disable:next unneeded_synthesized_initializer
@usableFromInline
init() { }
@@ -366,6 +366,7 @@ extension AssociationToMany {
/// ### Top-Level Functions
///
/// - ``abs(_:)-43n8v``
/// - ``cast(_:as:)-63ttx``
/// - ``length(_:)-9dr2v``
public struct AssociationAggregate<RowDecoder> {
fileprivate let preparation: AssociationAggregatePreparation<RowDecoder>
@@ -61,6 +61,7 @@
/// ### Batch Delete
///
/// - ``deleteAll(_:)``
/// - ``deleteAndFetchIds(_:)``
/// - ``deleteAndFetchCursor(_:)``
/// - ``deleteAndFetchAll(_:)``
/// - ``deleteAndFetchSet(_:)``
@@ -528,7 +529,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter selection: The returned columns (must not be empty).
@@ -561,7 +562,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A ``RecordCursor`` over the deleted records.
@@ -588,7 +589,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: An array of deleted records.
@@ -614,7 +615,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A set of deleted records.
@@ -625,6 +626,41 @@ extension QueryInterfaceRequest {
{
try Set(deleteAndFetchCursor(db))
}
/// Executes a `DELETE RETURNING` statement and returns the set of
/// deleted ids.
///
/// For example:
///
/// ```swift
/// // Fetch the ids of deleted players
/// // DELETE FROM player RETURNING id
/// let request = Player.all()
/// let deletedPlayerIds = try request.deleteAndFetchIds(db)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A set of deleted ids.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) // Identifiable
public func deleteAndFetchIds(_ db: Database)
throws -> Set<RowDecoder.ID>
where RowDecoder: TableRecord & Identifiable,
RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible
{
let primaryKey = try db.primaryKey(RowDecoder.databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Fetching id requires a single-column primary key in the table \(databaseTableName)")
let statement = try deleteAndFetchStatement(db, selection: [Column(primaryKey.columns[0])])
return try RowDecoder.ID.fetchSet(statement)
}
#else
/// Returns a `DELETE RETURNING` prepared statement.
///
@@ -640,7 +676,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter selection: The returned columns (must not be empty).
@@ -674,7 +710,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A ``RecordCursor`` over the deleted records.
@@ -702,7 +738,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: An array of deleted records.
@@ -729,7 +765,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A set of deleted records.
@@ -741,6 +777,41 @@ extension QueryInterfaceRequest {
{
try Set(deleteAndFetchCursor(db))
}
/// Executes a `DELETE RETURNING` statement and returns the set of
/// deleted ids.
///
/// For example:
///
/// ```swift
/// // Fetch the ids of deleted players
/// // DELETE FROM player RETURNING id
/// let request = Player.all()
/// let deletedPlayerIds = try request.deleteAndFetchIds(db)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A set of deleted ids.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchIds(_ db: Database)
throws -> Set<RowDecoder.ID>
where RowDecoder: TableRecord & Identifiable,
RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible
{
let primaryKey = try db.primaryKey(RowDecoder.databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Fetching id requires a single-column primary key in the table \(databaseTableName)")
let statement = try deleteAndFetchStatement(db, selection: [Column(primaryKey.columns[0])])
return try RowDecoder.ID.fetchSet(statement)
}
#endif
}
@@ -844,7 +915,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -893,7 +964,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -930,7 +1001,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -962,7 +1033,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -996,7 +1067,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -1046,7 +1117,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -1084,7 +1155,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -1117,7 +1188,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -2167,6 +2167,7 @@ extension SQLExpressible where Self == Column {
/// - ``average(_:)``
/// - ``average(_:filter:)``
/// - ``capitalized``
/// - ``cast(_:as:)-1dmu3``
/// - ``count(_:)``
/// - ``count(distinct:)``
/// - ``dateTime(_:_:)``
+1 -1
View File
@@ -171,7 +171,7 @@ struct SQLRelation {
var source: SQLSource
var selectionPromise: DatabasePromise<[SQLSelection]>
var filterPromise: DatabasePromise<SQLExpression>?
var ordering: SQLRelation.Ordering = SQLRelation.Ordering()
var ordering = SQLRelation.Ordering()
var ctes: OrderedDictionary<String, SQLCTE> = [:] // See also `allCTEs`
var children: OrderedDictionary<String, Child> = [:]
+75 -12
View File
@@ -34,18 +34,7 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
}
func singleValueContainer() -> SingleValueEncodingContainer {
// @itaiferber on https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/11
//
// > Encoding a value into a single-value container is equivalent to
// > encoding the value directly into the encoder, with the primary
// > difference being the above: encoding into the encoder writes the
// > contents of a type into the encoder, while encoding to a
// > single-value container gives the encoder a chance to intercept the
// > type as a whole.
//
// Wait for somebody hitting this fatal error so that we can write a
// meaningful regression test.
fatalError("single value encoding is not supported")
self
}
private struct KeyedContainer<Key: CodingKey>: KeyedEncodingContainerProtocol {
@@ -169,6 +158,80 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
}
}
extension RecordEncoder: SingleValueEncodingContainer {
private func unsupportedSingleValueEncoding() {
fatalError("Can't encode a single value in a database row.")
}
func encodeNil() throws {
unsupportedSingleValueEncoding()
}
func encode(_ value: Bool) throws {
unsupportedSingleValueEncoding()
}
func encode(_ value: String) throws {
unsupportedSingleValueEncoding()
}
func encode(_ value: Double) throws {
unsupportedSingleValueEncoding()
}
func encode(_ value: Float) throws {
unsupportedSingleValueEncoding()
}
func encode(_ value: Int) throws {
unsupportedSingleValueEncoding()
}
func encode(_ value: Int8) throws {
unsupportedSingleValueEncoding()
}
func encode(_ value: Int16) throws {
unsupportedSingleValueEncoding()
}
func encode(_ value: Int32) throws {
unsupportedSingleValueEncoding()
}
func encode(_ value: Int64) throws {
unsupportedSingleValueEncoding()
}
func encode(_ value: UInt) throws {
unsupportedSingleValueEncoding()
}
func encode(_ value: UInt8) throws {
unsupportedSingleValueEncoding()
}
func encode(_ value: UInt16) throws {
unsupportedSingleValueEncoding()
}
func encode(_ value: UInt32) throws {
unsupportedSingleValueEncoding()
}
func encode(_ value: UInt64) throws {
unsupportedSingleValueEncoding()
}
func encode<T>(_ value: T) throws where T: Encodable {
if let record = value as? EncodableRecord {
try record.encode(to: &_persistenceContainer)
} else {
try value.encode(to: self)
}
}
}
// MARK: - ColumnEncoder
/// The encoder that encodes into a database column
+1 -1
View File
@@ -585,7 +585,7 @@ public enum DatabaseDateEncodingStrategy {
/// var uuid: UUID
/// }
/// ```
public enum DatabaseUUIDEncodingStrategy {
public enum DatabaseUUIDEncodingStrategy: Sendable {
/// The strategy that uses formatting from the UUID type.
///
/// It encodes UUIDs as 16-bytes data blobs.
+54 -4
View File
@@ -108,8 +108,12 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
func singleValueContainer() throws -> SingleValueDecodingContainer {
guard let key = codingPath.last else {
// Decoding an array of scalars from rows: pick the first column
return ColumnDecoder<R>(row: row, columnIndex: 0, codingPath: codingPath)
// Not yet sure what we are decoding, this will be decided in the SingleValueDecodingContainer functions.
// For decoding an array of scalars (in case of prefetched rows) we pick the first column.
return SingleValueRowDecoder(
columnDecoder: ColumnDecoder<R>(row: row, columnIndex: 0, codingPath: codingPath),
columnDecodingStrategy: columnDecodingStrategy
)
}
guard let index = row.index(forColumn: key.stringValue) else {
// Don't use DecodingError.keyNotFound:
@@ -346,7 +350,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
// Unknown key
//
// Should be throw an error? Well... The use case is the following:
// Should we throw an error? Well... The use case is the following:
//
// // SELECT book.*, author.* FROM book
// // JOIN author ON author.id = book.authorId
@@ -398,7 +402,9 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
KeyedDecodingContainer<NestedKey>.self,
DecodingError.Context(
codingPath: codingPath,
debugDescription: "not implemented: building a nested JSON container for the column '\(column)'"))
debugDescription: """
not implemented: building a nested JSON container for the column '\(column)'
"""))
}
// Scope?
@@ -485,6 +491,50 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
}
}
private struct SingleValueRowDecoder<R: FetchableRecord>: SingleValueDecodingContainer {
var columnDecoder: ColumnDecoder<R>
var columnDecodingStrategy: DatabaseColumnDecodingStrategy
let codingPath: [any CodingKey] = []
func decodeNil() -> Bool { columnDecoder.decodeNil() }
func decode(_ type: Bool.Type) throws -> Bool { try columnDecoder.decode(type) }
func decode(_ type: String.Type) throws -> String { try columnDecoder.decode(type) }
func decode(_ type: Double.Type) throws -> Double { try columnDecoder.decode(type) }
func decode(_ type: Float.Type) throws -> Float { try columnDecoder.decode(type) }
func decode(_ type: Int.Type) throws -> Int { try columnDecoder.decode(type) }
func decode(_ type: Int8.Type) throws -> Int8 { try columnDecoder.decode(type) }
func decode(_ type: Int16.Type) throws -> Int16 { try columnDecoder.decode(type) }
func decode(_ type: Int32.Type) throws -> Int32 { try columnDecoder.decode(type) }
func decode(_ type: Int64.Type) throws -> Int64 { try columnDecoder.decode(type) }
#if compiler(>=6)
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
func decode(_ type: Int128.Type) throws -> Int128 { try columnDecoder.decode(type) }
#endif
func decode(_ type: UInt.Type) throws -> UInt { try columnDecoder.decode(type) }
func decode(_ type: UInt8.Type) throws -> UInt8 { try columnDecoder.decode(type) }
func decode(_ type: UInt16.Type) throws -> UInt16 { try columnDecoder.decode(type) }
func decode(_ type: UInt32.Type) throws -> UInt32 { try columnDecoder.decode(type) }
func decode(_ type: UInt64.Type) throws -> UInt64 { try columnDecoder.decode(type) }
#if compiler(>=6)
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
func decode(_ type: UInt128.Type) throws -> UInt128 { try columnDecoder.decode(type) }
#endif
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
if let type = T.self as? any FetchableRecord.Type {
// Prefer FetchableRecord decoding over Decodable.
return try type.init(row: columnDecoder.row) as! T
} else {
let decoder = _RowDecoder<R>(
row: columnDecoder.row,
codingPath: [],
columnDecodingStrategy: columnDecodingStrategy
)
return try T(from: decoder)
}
}
}
// MARK: - PrefetchedRowsDecoder
private struct PrefetchedRowsDecoder<R: FetchableRecord>: Decoder {
@@ -865,6 +865,8 @@ extension ValueConcurrentObserver: DatabaseCancellable {
// Notify cancellation
let (events, dbPool): (ValueObservationEvents?, DatabasePool?) = lock.synchronized {
let events = notificationCallbacks?.events
// Set callbacks to nil so that we can't notify anything after
// the cancellation.
notificationCallbacks = nil
return (events, databaseAccess?.dbPool)
}
@@ -448,6 +448,8 @@ extension ValueWriteOnlyObserver: DatabaseCancellable {
// Notify cancellation
let (events, writer) = lock.synchronized {
let events = notificationCallbacks?.events
// Set callbacks to nil so that we can't notify anything after
// the cancellation.
notificationCallbacks = nil
return (events, databaseAccess?.writer)
}
+2 -2
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.7
// swift-tools-version:6.0
// 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(.v11),
.iOS(.v18),
.macOS(.v10_13),
.tvOS(.v11),
.watchOS(.v4),
+29 -11
View File
@@ -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**: April 21, 2024 • [version 6.27.0](https://github.com/groue/GRDB.swift/tree/v6.27.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
**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)
**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ &bull; SQLite 3.19.3+ &bull; Swift 5.7+ / Xcode 14+
@@ -340,6 +340,17 @@ 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`:
@@ -350,15 +361,24 @@ pod 'GRDB.swift'
GRDB can be installed as a framework, or a static library.
## Swift Package Manager
**Important Note for CocoaPods installation**
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`
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:
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.
- 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:
> **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.
```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'
```
## Carthage
@@ -2343,7 +2363,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), 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#limitations_and_caveats), which describes important limitations and caveats for batch operations.
```swift
let request = Player.filter(...)...
@@ -5723,9 +5743,7 @@ 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 {
if let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite") {
// If the resource exists, open a read-only connection.
// Writes are disallowed because resources can not be modified.
var config = Configuration()
+1
View File
@@ -15,6 +15,7 @@ disabled_rules:
- is_disjoint
- large_tuple
- nesting
- non_optional_string_data_conversion
- opening_brace
- redundant_optional_initialization
- syntactic_sugar
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>6.27.0</string>
<string>6.29.3</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+2
View File
@@ -17,6 +17,7 @@
## 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?)
@@ -84,6 +85,7 @@
- [ ] 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
View File
@@ -139,4 +139,13 @@ 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)
}
}
+26
View File
@@ -223,6 +223,32 @@ 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,7 +137,6 @@ 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")
}
@@ -151,10 +150,6 @@ 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\")")
}
}
-16
View File
@@ -51,10 +51,8 @@ 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
@@ -250,10 +248,8 @@ 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},
@@ -413,18 +409,12 @@ 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\
@@ -604,10 +594,8 @@ 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
@@ -799,10 +787,8 @@ 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
@@ -1586,10 +1572,8 @@ 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,6 +2,12 @@ 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 {
+8
View File
@@ -439,4 +439,12 @@ 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()
}
}
+7
View File
@@ -467,4 +467,11 @@ 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()
}
}
+17 -1
View File
@@ -2,13 +2,29 @@ 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,6 +2,18 @@ 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 {
@@ -1913,4 +1913,70 @@ extension FetchableRecordDecodableTests {
}
}
}
// 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")
}
}
@@ -83,6 +83,97 @@ 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
@@ -2,6 +2,22 @@ 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
@@ -364,6 +364,30 @@ 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,6 +3,33 @@ 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 { }
@@ -748,6 +775,53 @@ 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 {