From 910ca2d0ce16a97779d66ebebb9d9ec8bda07d86 Mon Sep 17 00:00:00 2001
From: Tom Brewe
Date: Fri, 1 Nov 2024 20:16:44 +0100
Subject: [PATCH 01/18] docs: fixes typos "FST"->"FTS"
---
Documentation/FTS5Tokenizers.md | 4 ++--
Documentation/FullTextSearch.md | 2 +-
2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/Documentation/FTS5Tokenizers.md b/Documentation/FTS5Tokenizers.md
index 29c9d7572..2a3bccf5a 100644
--- a/Documentation/FTS5Tokenizers.md
+++ b/Documentation/FTS5Tokenizers.md
@@ -3,7 +3,7 @@ FTS5 Tokenizers
**[FTS5](https://www.sqlite.org/fts5.html) is an extensible full-text search engine.**
-GRDB lets you define your own custom FST5 tokenizers, and extend SQLite built-in tokenizers. Possible use cases are:
+GRDB lets you define your own custom FTS5 tokenizers, and extend SQLite built-in tokenizers. Possible use cases are:
- Have "fi" match the ligature "fi" (U+FB01)
- Have "first" match "1st"
@@ -95,7 +95,7 @@ let documents = try Document.matching(pattern).fetchAll(db)
## FTS5Tokenizer
-**FST5Tokenizer** is the protocol for all FTS5 tokenizers.
+**FTS5Tokenizer** is the protocol for all FTS5 tokenizers.
It only requires a tokenization method that matches the low-level `xTokenize` C function documented at https://www.sqlite.org/fts5.html#custom_tokenizers. We'll discuss it more when describing custom tokenizers.
diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md
index 69b1ae757..cf414b62e 100644
--- a/Documentation/FullTextSearch.md
+++ b/Documentation/FullTextSearch.md
@@ -82,7 +82,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
- **The location of the indexed text in your database schema.** Only FTS4 and FTS5 support "contentless" and "external content" tables.
-- See [FST3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences.
+- See [FTS3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences.
> **Note**: In case you were still wondering, it is recommended to read the SQLite documentation: [FTS3 & FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html).
From c865a847fd01428a9b517a513052de3c60bbda41 Mon Sep 17 00:00:00 2001
From: Saleem Abdulrasool
Date: Tue, 12 Nov 2024 11:10:07 -0800
Subject: [PATCH 02/18] Foundation: elide extensions on Windows to match Linux
Similar to Linux, elide some extensions on Windows. This is required to
build this module on Windows.
---
GRDB/Core/Support/Foundation/NSNumber.swift | 2 +-
GRDB/Core/Support/Foundation/URL.swift | 2 +-
GRDB/Core/Support/Foundation/UUID.swift | 2 +-
3 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/GRDB/Core/Support/Foundation/NSNumber.swift b/GRDB/Core/Support/Foundation/NSNumber.swift
index 9867e8f43..1c5778c19 100644
--- a/GRDB/Core/Support/Foundation/NSNumber.swift
+++ b/GRDB/Core/Support/Foundation/NSNumber.swift
@@ -1,4 +1,4 @@
-#if !os(Linux)
+#if !os(Linux) && !os(Windows)
import Foundation
private let integerRoundingBehavior = NSDecimalNumberHandler(
diff --git a/GRDB/Core/Support/Foundation/URL.swift b/GRDB/Core/Support/Foundation/URL.swift
index cf4b96d12..6db66ec3b 100644
--- a/GRDB/Core/Support/Foundation/URL.swift
+++ b/GRDB/Core/Support/Foundation/URL.swift
@@ -1,6 +1,6 @@
import Foundation
-#if !os(Linux)
+#if !os(Linux) && !os(Windows)
/// NSURL stores its absoluteString in the database.
extension NSURL: DatabaseValueConvertible {
diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift
index 1ebca9d84..7595b53ef 100644
--- a/GRDB/Core/Support/Foundation/UUID.swift
+++ b/GRDB/Core/Support/Foundation/UUID.swift
@@ -9,7 +9,7 @@ import SQLite3
import Foundation
-#if !os(Linux)
+#if !os(Linux) && !os(Windows)
/// NSUUID adopts DatabaseValueConvertible
extension NSUUID: DatabaseValueConvertible {
/// Returns a BLOB database value containing the uuid bytes.
From 77a4d179407e6c25a365722a985581cc1adb17bf Mon Sep 17 00:00:00 2001
From: Saleem Abdulrasool
Date: Tue, 12 Nov 2024 11:10:40 -0800
Subject: [PATCH 03/18] Core: import `ucrt` on Windows for `strcmp`
This uses the deprecated `strcmp` interface on Windows, which requires
the C library to be imported. Add the missing import to allow building
on Windows.
---
GRDB/Core/StatementAuthorizer.swift | 2 ++
1 file changed, 2 insertions(+)
diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift
index d2427ac30..169b5dc5f 100644
--- a/GRDB/Core/StatementAuthorizer.swift
+++ b/GRDB/Core/StatementAuthorizer.swift
@@ -13,6 +13,8 @@ import string_h
import Glibc
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
import Darwin
+#elseif os(Windows)
+import ucrt
#endif
/// `StatementAuthorizer` provides information about compiled database
From 9f9f0d37dd39c34438c7e17489896d2a2ae2f896 Mon Sep 17 00:00:00 2001
From: JasonnnW3000
Date: Tue, 31 Dec 2024 23:58:47 -0500
Subject: [PATCH 04/18] Update LICENSE, fix license year
Signed-off-by: JasonnnW3000
---
LICENSE | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/LICENSE b/LICENSE
index 922a3e13a..550890c89 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,4 +1,4 @@
-Copyright (C) 2015-2024 Gwendal Roué
+Copyright (C) 2015-2025 Gwendal Roué
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
From b2e808b9e4f9d1d5bc102d831b1d485ba57a3d05 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Thu, 2 Jan 2025 12:27:39 +0100
Subject: [PATCH 05/18] Bump custom SQLite to 3.47.2
---
Documentation/CustomSQLiteBuilds.md | 2 +-
SQLiteCustom/src | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md
index 99b82911c..3a0a9e9be 100644
--- a/Documentation/CustomSQLiteBuilds.md
+++ b/Documentation/CustomSQLiteBuilds.md
@@ -3,7 +3,7 @@ Custom SQLite Builds
By default, GRDB uses the version of SQLite that ships with the target operating system.
-**You can build GRDB with a custom build of [SQLite 3.46.1](https://www.sqlite.org/changes.html).**
+**You can build GRDB with a custom build of [SQLite 3.47.2](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
diff --git a/SQLiteCustom/src b/SQLiteCustom/src
index 9007ade24..69395d1f7 160000
--- a/SQLiteCustom/src
+++ b/SQLiteCustom/src
@@ -1 +1 @@
-Subproject commit 9007ade247efe75bf870956fb8c37c08a0795241
+Subproject commit 69395d1f72e61f37cf2e5164c054d85c80d5481c
From 1e354ba79cc8300a71084d495a65a3b5f6b4df1f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Thu, 2 Jan 2025 17:07:55 +0100
Subject: [PATCH 06/18] Delete the rationale for Sendable records
... because the reality is that I just don't know how to relax this requirement.
See:
- https://www.youtube.com/watch?v=JmrnE7HUaDE
- https://forums.swift.org/t/swiftserverconf-feedback-on-leveraging-structured-concurrency-in-your-applications/75176
---
GRDB/Documentation.docc/SwiftConcurrency.md | 155 ++++++++------------
1 file changed, 63 insertions(+), 92 deletions(-)
diff --git a/GRDB/Documentation.docc/SwiftConcurrency.md b/GRDB/Documentation.docc/SwiftConcurrency.md
index d81e145b9..f16a00ef8 100644
--- a/GRDB/Documentation.docc/SwiftConcurrency.md
+++ b/GRDB/Documentation.docc/SwiftConcurrency.md
@@ -39,11 +39,73 @@ All safety guarantees of Swift 6 are enforced during database accesses. They are
The following sections describe, with more details, how GRDB interacts with Swift Concurrency.
--
-
-
+-
-
+### Shorthand Closure Notation
+
+In the Swift 5 language mode, the compiler emits a warning when a database access is written with the shorthand closure notation:
+
+```swift
+// Standard closure:
+let count = try await writer.read { db in
+ try Player.fetchCount(db)
+}
+
+// Shorthand notation:
+// ⚠️ Converting non-sendable function value to '@Sendable (Database)
+// throws -> Int' may introduce data races.
+let count = try await writer.read(Player.fetchCount)
+```
+
+**You can remove this warning** by enabling [SE-0418: Inferring `Sendable` for methods and key path literals](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0418-inferring-sendable-for-methods.md), as below:
+
+- **Using Xcode**
+
+ Set `SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES` to `YES` in the build settings of your target.
+
+- **In a SwiftPM package manifest**
+
+ Enable the `InferSendableFromCaptures` upcoming feature:
+
+ ```swift
+ .target(
+ name: "MyTarget",
+ swiftSettings: [
+ .enableUpcomingFeature("InferSendableFromCaptures")
+ ]
+ )
+ ```
+
+This language feature is not enabled by default, because it can potentially [affect source compatibility](https://www.swift.org/migration/documentation/swift-6-concurrency-migration-guide/sourcecompatibility#Inferring-Sendable-for-methods-and-key-path-literals).
+
+### Non-Sendable Configuration of Record Types
+
+In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when a record type specifies which columns it fetches from the database, with the ``TableRecord/databaseSelection-7iphs`` static property:
+
+```swift
+extension Player: FetchableRecord, PersistableRecord {
+ // ❌ Static property 'databaseSelection' is not concurrency-safe
+ // because non-'Sendable' type '[any SQLSelectable]'
+ // may have shared mutable state
+ static let databaseSelection: [any SQLSelectable] = [
+ Column("id"), Column("name"), Column("score")
+ ]
+}
+```
+
+**To fix this error**, replace the stored property with a computed property:
+
+```swift
+extension Player: FetchableRecord, PersistableRecord {
+ static var databaseSelection: [any SQLSelectable] {
+ [Column("id"), Column("name"), Column("score")]
+ }
+}
+```
+
### Non-Sendable Record Types
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when the application reads, writes, or observes a non-[`Sendable`](https://developer.apple.com/documentation/swift/sendable) type.
@@ -128,97 +190,6 @@ You do not need to perform this refactoring right away: you can compile your app
Yes. Classes that can not be modified, made of constant `let` properties, are Sendable. Those immutable classes will not make it easy to modify the database, though.
-#### FAQ: Why this Sendable requirement?
-
-**GRDB needs new features in the Swift language and the SDKs in order to deal with non-Sendable types.**
-
-[SE-0430: `sending` parameter and result values](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0430-transferring-parameters-and-results.md) looks like the language feature we need, but:
-
-- `DispatchQueue.async` does not accept a `sending` closure. GRDB needs this in order to accept non-Sendable records to be sent to the database, as below:
-
- ```swift
- let nonSendableRecord: Player
- try await writer.write { db in
- try nonSendableRecord.insert(db)
- }
- ```
-
- Please [file a feedback](http://feedbackassistant.apple.com) for requesting this DispatchQueue improvement. The more the merrier. I personally filed FB15270949.
-
-- Database access methods taint the values they fetch. In the code below, the rules of [SE-0414: Region based Isolation](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0414-region-based-isolation.md) have the compiler refuse that the fetched player is sent back to the caller:
-
- ```swift
- let player = try await writer.read { db in
- try Player.fetchOne(db, id: 42)
- }
- ```
-
- Strictly speaking, the compiler diagnostic is correct: one could copy the non-Sendable `db` argument into the fetched `Player` instance, making it unsuitable for later use. In practice, nobody does that. Copying `db` is a programmer error, and GRDB promptly raises a fatal error whenever a `db` copy would be improperly used. But there is no way to tell the compiler about this practice.
-
-For all those reasons, GRDB has to require values that are asynchronously written and read from the database to be `Sendable`.
-
-### Shorthand Closure Notation
-
-In the Swift 5 language mode, the compiler emits a warning when a database access is written with the shorthand closure notation:
-
-```swift
-// Standard closure:
-let count = try await writer.read { db in
- try Player.fetchCount(db)
-}
-
-// Shorthand notation:
-// ⚠️ Converting non-sendable function value to '@Sendable (Database)
-// throws -> Int' may introduce data races.
-let count = try await writer.read(Player.fetchCount)
-```
-
-**You can remove this warning** by enabling [SE-0418: Inferring `Sendable` for methods and key path literals](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0418-inferring-sendable-for-methods.md), as below:
-
-- **Using Xcode**
-
- Set `SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES` to `YES` in the build settings of your target.
-
-- **In a SwiftPM package manifest**
-
- Enable the `InferSendableFromCaptures` upcoming feature:
-
- ```swift
- .target(
- name: "MyTarget",
- swiftSettings: [
- .enableUpcomingFeature("InferSendableFromCaptures")
- ]
- )
- ```
-
-This language feature is not enabled by default, because it can potentially [affect source compatibility](https://www.swift.org/migration/documentation/swift-6-concurrency-migration-guide/sourcecompatibility#Inferring-Sendable-for-methods-and-key-path-literals).
-
-### Non-Sendable Configuration of Record Types
-
-In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when a record type specifies which columns it fetches from the database, with the ``TableRecord/databaseSelection-7iphs`` static property:
-
-```swift
-extension Player: FetchableRecord, MutablePersistableRecord {
- // ❌ Static property 'databaseSelection' is not concurrency-safe
- // because non-'Sendable' type '[any SQLSelectable]'
- // may have shared mutable state
- static let databaseSelection: [any SQLSelectable] = [
- Column("id"), Column("name"), Column("score")
- ]
-}
-```
-
-**To fix this error**, replace the stored property with a computed property:
-
-```swift
-extension Player: FetchableRecord, MutablePersistableRecord {
- static var databaseSelection: [any SQLSelectable] {
- [Column("id"), Column("name"), Column("score")]
- }
-}
-```
-
### Choosing between Synchronous and Asynchronous Database Accesses
GRDB connections provide two versions of `read` and `write`, one that is synchronous, and one that is asynchronous. It might not be clear how to choose one or the other.
From 1cca3686f5609c35f1f0225fbe2574aa8ad64305 Mon Sep 17 00:00:00 2001
From: Kevin LE GOFF
Date: Thu, 9 Jan 2025 00:01:48 +0200
Subject: [PATCH 07/18] Fix typo in Readme.md
---
README.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/README.md b/README.md
index 1ed1dd972..c01c0864c 100644
--- a/README.md
+++ b/README.md
@@ -1649,8 +1649,8 @@ To define a record type, define a type and extend it with protocols that come wi
For example:
-```
-struct Player: {
+```swift
+struct Player {
var id: Int64
var name: String
var score: Int
From 61c7fdf81b76c0923f70b830804aa88f07006458 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 19 Jan 2025 16:26:29 +0100
Subject: [PATCH 08/18] Github CI: use tvOS 18.1
---
.github/workflows/CI.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml
index 54a73ddac..ef5e3da7e 100644
--- a/.github/workflows/CI.yml
+++ b/.github/workflows/CI.yml
@@ -50,7 +50,7 @@ jobs:
name: "iOS"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
- destination: "OS=18.0,name=Apple TV"
+ destination: "OS=18.1,name=Apple TV"
name: "tvOS"
steps:
- uses: actions/checkout@v4
From a4132a00db9ba9100fda0e76d92bc0612087276f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 19 Jan 2025 14:40:01 +0100
Subject: [PATCH 09/18] Clarify code that aims at fixing #1357
---
GRDB/QueryInterface/SQL/SQLRelation.swift | 2 +-
GRDB/QueryInterface/SQL/SQLSelection.swift | 16 +++++++++++++---
2 files changed, 14 insertions(+), 4 deletions(-)
diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift
index 469c845bf..691889cb3 100644
--- a/GRDB/QueryInterface/SQL/SQLRelation.swift
+++ b/GRDB/QueryInterface/SQL/SQLRelation.swift
@@ -636,7 +636,7 @@ extension SQLRelation {
}
//
- guard selection.allSatisfy(\.isTriviallyCountable) else {
+ if selection.contains(where: \.requiresTrivialCount) {
return try fetchTrivialCount(db)
}
diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift
index a0f29120d..c616c701b 100644
--- a/GRDB/QueryInterface/SQL/SQLSelection.swift
+++ b/GRDB/QueryInterface/SQL/SQLSelection.swift
@@ -245,15 +245,25 @@ extension SQLSelection {
}
}
+ /// Returns whether this selection MUST be counted with a "trivial"
+ /// count: `SELECT COUNT(*) FROM (SELECT ...)`.
+ ///
/// Supports SQLRelation.fetchCount.
///
/// See
- var isTriviallyCountable: Bool {
+ var requiresTrivialCount: Bool {
switch impl {
case .aliasedExpression, .literal:
- return false
- case .allColumns, .qualifiedAllColumns, .expression:
+ // Trivial count is required.
+ //
+ // For example, the WHERE clause here requires the aliased
+ // column to be preserved in the counting request:
+ // SELECT *, column AS alt FROM player WHERE alt
return true
+ case .allColumns, .qualifiedAllColumns:
+ return false
+ case .expression:
+ return false
}
}
}
From d03208b33a6a98ecf1c385e7ec12644238217b17 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 19 Jan 2025 14:40:16 +0100
Subject: [PATCH 10/18] Remove unused code
---
GRDB/QueryInterface/SQL/SQLSelection.swift | 35 ----------------------
1 file changed, 35 deletions(-)
diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift
index c616c701b..a04883dc5 100644
--- a/GRDB/QueryInterface/SQL/SQLSelection.swift
+++ b/GRDB/QueryInterface/SQL/SQLSelection.swift
@@ -126,41 +126,6 @@ extension SQLSelection {
}
}
- /// Returns the SQL that feeds the argument of the `COUNT` function.
- ///
- /// For example:
- ///
- /// COUNT(*)
- /// COUNT(id)
- /// ^---- countedSQL
- ///
- /// - parameter context: An SQL generation context which accepts
- /// statement arguments.
- func countedSQL(_ context: SQLGenerationContext) throws -> String {
- switch impl {
- case .allColumns:
- return "*"
-
- case let .qualifiedAllColumns(alias):
- if context.qualifier(for: alias) != nil {
- // SELECT COUNT(t.*) is invalid SQL
- fatalError("Not implemented, or invalid query")
- }
- return "*"
-
- case let .expression(expression),
- let .aliasedExpression(expression, _):
- return try expression.sql(context)
-
- case .literal:
- fatalError("""
- Selection literals can't be counted. \
- To resolve this error, select one or several literal expressions instead. \
- See SQL.sqlExpression.
- """)
- }
- }
-
/// Returns the SQL that feeds the selection of a `SELECT` statement.
///
/// For example:
From a642ac51aa6012500b9f8c94be810f98ce4f240a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 19 Jan 2025 15:05:39 +0100
Subject: [PATCH 11/18] AllColumnsExcluding
---
GRDB/QueryInterface/SQL/Column.swift | 7 +
GRDB/QueryInterface/SQL/SQLExpression.swift | 9 +-
GRDB/QueryInterface/SQL/SQLSelection.swift | 205 +++++++++++++++++-
.../SQLGeneration/SQLGenerationContext.swift | 43 +++-
.../SQLGeneration/SQLQueryGenerator.swift | 36 ++-
.../SQLInterpolation+QueryInterface.swift | 11 +-
.../Record/MutablePersistableRecord+DAO.swift | 9 +-
GRDB/Record/Record.swift | 2 +-
GRDB/Record/TableRecord.swift | 8 +-
9 files changed, 301 insertions(+), 29 deletions(-)
diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift
index 535166789..cef9bcbe6 100644
--- a/GRDB/QueryInterface/SQL/Column.swift
+++ b/GRDB/QueryInterface/SQL/Column.swift
@@ -61,6 +61,13 @@ extension ColumnExpression {
extension ColumnExpression where Self == Column {
/// The hidden rowID column.
+ ///
+ /// For example:
+ ///
+ /// ```swift
+ /// // SELECT rowid FROM player
+ /// let rowids = try Player.select(.rowID).fetchSet(db)
+ /// ```
public static var rowID: Self { Column.rowID }
}
diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift
index 9f26b9983..a4955fcad 100644
--- a/GRDB/QueryInterface/SQL/SQLExpression.swift
+++ b/GRDB/QueryInterface/SQL/SQLExpression.swift
@@ -2136,7 +2136,14 @@ public protocol SQLExpressible {
}
extension SQLExpressible where Self == Column {
- /// The hidden rowID column
+ /// The hidden rowID column.
+ ///
+ /// For example:
+ ///
+ /// ```swift
+ /// // SELECT rowid FROM player
+ /// let rowids = try Player.select(.rowID).fetchSet(db)
+ /// ```
public static var rowID: Self { Column.rowID }
}
diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift
index a04883dc5..95ccd4ce7 100644
--- a/GRDB/QueryInterface/SQL/SQLSelection.swift
+++ b/GRDB/QueryInterface/SQL/SQLSelection.swift
@@ -26,6 +26,12 @@ public struct SQLSelection: Sendable {
/// All columns, qualified: `player.*`
case qualifiedAllColumns(TableAlias)
+ /// All columns but the specified ones
+ case allColumnsExcluding(Set)
+
+ /// All columns but the specified ones, qualified.
+ case qualifiedAllColumnsExcluding(TableAlias, Set)
+
/// An expression
case expression(SQLExpression)
@@ -41,11 +47,21 @@ public struct SQLSelection: Sendable {
/// All columns: `*`
static let allColumns = SQLSelection(impl: .allColumns)
+ /// All columns but the specified ones.
+ static func allColumnsExcluding(_ excludedColumns: Set) -> Self {
+ SQLSelection(impl: .allColumnsExcluding(excludedColumns))
+ }
+
/// All columns, qualified: `player.*`
static func qualifiedAllColumns(_ alias: TableAlias) -> Self {
self.init(impl: .qualifiedAllColumns(alias))
}
+ /// All columns but the specified ones, qualified.
+ static func qualifiedAllColumnsExcluding(_ alias: TableAlias, _ excludedColumns: Set) -> Self {
+ self.init(impl: .qualifiedAllColumnsExcluding(alias, excludedColumns))
+ }
+
/// An expression
static func expression(_ expression: SQLExpression) -> Self {
self.init(impl: .expression(expression))
@@ -70,13 +86,16 @@ extension SQLSelection {
/// Returns nil when the number of columns is unknown.
func columnCount(_ context: SQLGenerationContext) throws -> Int? {
switch impl {
- case .allColumns:
+ case .allColumns, .allColumnsExcluding:
// Likely a GRDB bug: we can't count the number of columns in an
// unqualified table.
return nil
case let .qualifiedAllColumns(alias):
- return try context.columnCount(in: alias.tableName)
+ return try context.columnCount(in: alias.tableName, excluding: [])
+
+ case let .qualifiedAllColumnsExcluding(alias, excludedColumns):
+ return try context.columnCount(in: alias.tableName, excluding: excludedColumns)
case .expression,
.aliasedExpression:
@@ -104,7 +123,28 @@ extension SQLSelection {
// SELECT COUNT(*) FROM tableName ...
return .all
- case .qualifiedAllColumns:
+ case .allColumnsExcluding:
+ // SELECT DISTINCT a, b, c FROM tableName ...
+ if distinct {
+ // TODO: if the selection were qualified, and if we had a
+ // database connection, we could detect the case where there
+ // remains only one column, and we could perform a
+ // SELECT COUNT(DISTINCT remainingColumn) FROM tableName
+ //
+ // Since most people will not use `.allColumns(excluding:)`
+ // when they want to select only one column, I guess that
+ // this optimization has little chance to be needed.
+ //
+ // Can't count
+ return nil
+ }
+
+ // SELECT a, b, c FROM tableName ...
+ // ->
+ // SELECT COUNT(*) FROM tableName ...
+ return .all
+
+ case .qualifiedAllColumns, .qualifiedAllColumnsExcluding:
return nil
case let .expression(expression),
@@ -144,11 +184,38 @@ extension SQLSelection {
case .allColumns:
return "*"
+ case .allColumnsExcluding:
+ // Likely a GRDB bug: we don't know the table name so we can't
+ // load remaining columns. This selection should have been
+ // turned into a `.qualifiedAllColumnsExcluding`.
+ fatalError("Not implemented, or invalid query")
+
case let .qualifiedAllColumns(alias):
if let qualifier = context.qualifier(for: alias) {
return qualifier.quotedDatabaseIdentifier + ".*"
}
return "*"
+
+ case let .qualifiedAllColumnsExcluding(alias, excludedColumns):
+ let columnsNames = try context.columnNames(in: alias.tableName)
+ let remainingColumnsNames = if excludedColumns.isEmpty {
+ columnsNames
+ } else {
+ columnsNames.filter {
+ !excludedColumns.contains(CaseInsensitiveIdentifier(rawValue: $0))
+ }
+ }
+ if columnsNames.count == remainingColumnsNames.count {
+ // We're not excluding anything
+ if let qualifier = context.qualifier(for: alias) {
+ return qualifier.quotedDatabaseIdentifier + ".*"
+ }
+ return "*"
+ } else {
+ return try remainingColumnsNames
+ .map { try SQLExpression.column($0).qualified(with: alias).sql(context) }
+ .joined(separator: ", ")
+ }
case let .expression(expression):
return try expression.sql(context)
@@ -193,12 +260,15 @@ extension SQLSelection {
/// Returns a qualified selection
func qualified(with alias: TableAlias) -> SQLSelection {
switch impl {
- case .qualifiedAllColumns:
+ case .qualifiedAllColumns, .qualifiedAllColumnsExcluding:
return self
case .allColumns:
return .qualifiedAllColumns(alias)
+ case let .allColumnsExcluding(excludedColumns):
+ return .qualifiedAllColumnsExcluding(alias, excludedColumns)
+
case let .expression(expression):
return .expression(expression.qualified(with: alias))
@@ -227,6 +297,8 @@ extension SQLSelection {
return true
case .allColumns, .qualifiedAllColumns:
return false
+ case .allColumnsExcluding, .qualifiedAllColumnsExcluding:
+ return false
case .expression:
return false
}
@@ -272,15 +344,41 @@ enum SQLCount {
///
/// ## Topics
///
+/// ### Standard Selections
+///
+/// - ``rowID``
+/// - ``allColumns``
+/// - ``allColumns(excluding:)-3sg4w``
+/// - ``allColumns(excluding:)-3blq4``
+///
/// ### Supporting Types
///
/// - ``AllColumns``
+/// - ``AllColumnsExcluding``
/// - ``SQLSelection``
public protocol SQLSelectable {
/// Returns an SQL selection.
var sqlSelection: SQLSelection { get }
}
+extension SQLSelectable where Self == Column {
+ /// The hidden rowID column.
+ ///
+ /// For example:
+ ///
+ /// ```swift
+ /// struct Player: FetchableRecord, TableRecord {
+ /// static var databaseSelection: [any SQLSelectable] {
+ /// [.allColumns, .rowID]
+ /// }
+ /// }
+ ///
+ /// // SELECT *, rowid FROM player
+ /// Player.fetchAll(db)
+ /// ```
+ public static var rowID: Self { Column.rowID }
+}
+
extension SQLSelection: SQLSelectable {
// Not a real deprecation, just a usage warning
@available(*, deprecated, message: "Already SQLSelection")
@@ -294,10 +392,14 @@ extension SQLSelection: SQLSelectable {
/// For example:
///
/// ```swift
-/// try dbQueue.read { db in
-/// // SELECT * FROM player
-/// let players = try Player.select(AllColumns()).fetchAll(db)
+/// struct Player: FetchableRecord, TableRecord {
+/// static var databaseSelection: [any SQLSelectable] {
+/// [.allColumns, .rowID]
+/// }
/// }
+///
+/// // SELECT *, rowid FROM player
+/// Player.fetchAll(db)
/// ```
public struct AllColumns: Sendable {
/// The `*` selection.
@@ -309,3 +411,92 @@ extension AllColumns: SQLSelectable {
.allColumns
}
}
+
+extension SQLSelectable where Self == AllColumns {
+ /// All columns of the requested table.
+ ///
+ /// For example:
+ ///
+ /// ```swift
+ /// struct Player: FetchableRecord, TableRecord {
+ /// static var databaseSelection: [any SQLSelectable] {
+ /// [.allColumns, .rowID]
+ /// }
+ /// }
+ ///
+ /// // SELECT *, rowid FROM player
+ /// Player.fetchAll(db)
+ /// ```
+ public static var allColumns: AllColumns { AllColumns() }
+}
+
+// MARK: - AllColumnsExcluding
+
+/// `AllColumnsExcluding` selects all columns in a database table, but the
+/// ones you specify.
+///
+/// For example:
+///
+/// ```swift
+/// struct Player: TableRecord {
+/// static var databaseSelection: [any SQLSelectable] {
+/// [.allColumns(excluding: ["computedColumn"])]
+/// }
+/// }
+///
+/// // SELECT id, name, score FROM player
+/// Player.fetchAll(db)
+/// ```
+public struct AllColumnsExcluding: Sendable {
+ var excludedColumns: Set
+
+ public init(_ excludedColumns: some Collection) {
+ self.excludedColumns = Set(excludedColumns.lazy.map {
+ CaseInsensitiveIdentifier(rawValue: $0)
+ })
+ }
+}
+
+extension AllColumnsExcluding: SQLSelectable {
+ public var sqlSelection: SQLSelection {
+ .allColumnsExcluding(excludedColumns)
+ }
+}
+
+extension SQLSelectable where Self == AllColumnsExcluding {
+ /// All columns of the requested table, excluding the provided columns.
+ ///
+ /// For example:
+ ///
+ /// ```swift
+ /// struct Player: TableRecord {
+ /// static var databaseSelection: [any SQLSelectable] {
+ /// [.allColumns(excluding: ["computedColumn"])]
+ /// }
+ /// }
+ ///
+ /// // SELECT id, name, score FROM player
+ /// Player.fetchAll(db)
+ /// ```
+ public static func allColumns(excluding excludedColumns: some Collection) -> Self {
+ AllColumnsExcluding(excludedColumns)
+ }
+
+ /// All columns of the requested table, excluding the provided columns.
+ ///
+ /// For example:
+ ///
+ /// ```swift
+ /// struct Player: TableRecord {
+ /// static var databaseSelection: [any SQLSelectable] {
+ /// [.allColumns(excluding: [Column("computedColumn")])]
+ /// }
+ /// }
+ ///
+ /// // SELECT id, name, score FROM player
+ /// Player.fetchAll(db)
+ /// ```
+ public static func allColumns(excluding excludedColumns: some Collection) -> Self {
+ AllColumnsExcluding(excludedColumns.map(\.name))
+ }
+}
diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift
index ed1470ecd..8da9ed9f4 100644
--- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift
+++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift
@@ -153,15 +153,50 @@ final class SQLGenerationContext {
return nil
}
- func columnCount(in tableName: String) throws -> Int {
+ /// Return the number of columns in the table or CTE identified
+ /// by `tableName`.
+ ///
+ /// - parameter tableName: The table name.
+ /// - parameter excludedColumns: The eventual set of excluded columns.
+ func columnCount(
+ in tableName: String,
+ excluding excludedColumns: Set
+ ) throws -> Int {
if let cte = ownCTEs[tableName.lowercased()] {
- return try cte.columnCount(db)
+ if excludedColumns.isEmpty {
+ return try cte.columnCount(db)
+ } else {
+ fatalError("Not implemented: counting CTE columns with excluded columns")
+ }
}
switch parent {
case let .context(context):
- return try context.columnCount(in: tableName)
+ return try context.columnCount(in: tableName, excluding: excludedColumns)
case let .none(db: db, argumentsSink: _):
- return try db.columns(in: tableName).count
+ if excludedColumns.isEmpty {
+ return try db.columns(in: tableName).count
+ } else {
+ return try db
+ .columns(in: tableName)
+ .filter { !excludedColumns.contains(CaseInsensitiveIdentifier(rawValue: $0.name)) }
+ .count
+ }
+ }
+ }
+
+ /// Return the names of the columns in the table or CTE identified
+ /// by `tableName`.
+ ///
+ /// - parameter tableName: The table name.
+ func columnNames(in tableName: String) throws -> [String] {
+ if ownCTEs[tableName.lowercased()] != nil {
+ fatalError("Not implemented: extracing CTE column names")
+ }
+ switch parent {
+ case let .context(context):
+ return try context.columnNames(in: tableName)
+ case let .none(db: db, argumentsSink: _):
+ return try db.columns(in: tableName).map(\.name)
}
}
}
diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift
index 5b37ead62..e18a46c32 100644
--- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift
+++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift
@@ -235,7 +235,11 @@ struct SQLQueryGenerator: Refinable {
sql += " LIMIT " + limit.sql
}
- return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
+ return try makeStatement(
+ db, sql: sql,
+ arguments: context.arguments,
+ returning: selection,
+ from: relation.source.tableName)
case .unique:
return try makeTrivialDeleteStatement(db, selection: selection)
@@ -264,7 +268,11 @@ struct SQLQueryGenerator: Refinable {
sql += try selectPrimaryKey.requestSQL(subqueryContext)
sql += ")"
- return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
+ return try makeStatement(
+ db, sql: sql,
+ arguments: context.arguments,
+ returning: selection,
+ from: tableName)
}
/// Returns an `UPDATE` statement, with `RETURNING` clause if `selection`
@@ -323,7 +331,11 @@ struct SQLQueryGenerator: Refinable {
sql += " LIMIT " + limit.sql
}
- return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
+ return try makeStatement(
+ db, sql: sql,
+ arguments: context.arguments,
+ returning: selection,
+ from: relation.source.tableName)
case .unique:
return try makeTrivialUpdateStatement(
@@ -380,7 +392,11 @@ struct SQLQueryGenerator: Refinable {
sql += try selectPrimaryKey.requestSQL(subqueryContext)
sql += ")"
- return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
+ return try makeStatement(
+ db, sql: sql,
+ arguments: context.arguments,
+ returning: selection,
+ from: tableName)
}
// Support for the RETURNING clause
@@ -388,7 +404,8 @@ struct SQLQueryGenerator: Refinable {
_ db: Database,
sql: String,
arguments: StatementArguments,
- returning selection: [any SQLSelectable])
+ returning selection: [any SQLSelectable],
+ from tableName: String)
throws -> Statement
{
if selection.isEmpty {
@@ -396,12 +413,17 @@ struct SQLQueryGenerator: Refinable {
statement.arguments = arguments
return statement
} else {
- let context = SQLGenerationContext(db)
+ // Generate the RETURNING clause by turning selection into SQL.
+ // Make sure the selection is qualified with a table alias, so
+ // that selectables such as `.allColumns(excluding:)` can query
+ // the database about the database table.
+ let alias = TableAlias(tableName: tableName)
+ let context = SQLGenerationContext(db, aliases: [alias])
var sql = sql
var arguments = arguments
sql += " RETURNING "
sql += try selection
- .map { try $0.sqlSelection.sql(context) }
+ .map { try $0.sqlSelection.qualified(with: alias).sql(context) }
.joined(separator: ", ")
arguments += context.arguments
let statement = try db.makeStatement(sql: sql)
diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift
index 35a9912b1..b12f4f47d 100644
--- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift
+++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift
@@ -67,7 +67,12 @@ extension SQLInterpolation {
/// let player: Player = ...
/// let request: SQLRequest = "SELECT \(columnsOf: Player.self, tableAlias: "p") FROM player p"
public mutating func appendInterpolation(columnsOf recordType: (some TableRecord).Type, tableAlias: String? = nil) {
- let alias = TableAlias(name: tableAlias ?? recordType.databaseTableName)
+ // Make sure we provide the tableName, so that we can interpolate
+ // the columns of a type whose `databaseSelection` contains an
+ // instance of `AllColumnsExcluding`.
+ let alias = TableAlias(
+ tableName: recordType.databaseTableName,
+ userName: tableAlias ?? recordType.databaseTableName)
elements.append(contentsOf: recordType.databaseSelection
.map { CollectionOfOne(.selection($0.sqlSelection.qualified(with: alias))) }
.joined(separator: CollectionOfOne(.sql(", "))))
@@ -79,7 +84,7 @@ extension SQLInterpolation {
///
/// // SELECT * FROM player
/// let request: SQLRequest = """
- /// SELECT \(AllColumns()) FROM player
+ /// SELECT \(.allColumns) FROM player
/// """
public mutating func appendInterpolation(_ selection: some SQLSelectable) {
elements.append(.selection(selection.sqlSelection))
@@ -89,7 +94,7 @@ extension SQLInterpolation {
///
/// // SELECT * FROM player
/// let request: SQLRequest = """
- /// SELECT \(AllColumns()) FROM player
+ /// SELECT \(.allColumns) FROM player
/// """
@_disfavoredOverload
public mutating func appendInterpolation(_ selection: (any SQLSelectable)?) {
diff --git a/GRDB/Record/MutablePersistableRecord+DAO.swift b/GRDB/Record/MutablePersistableRecord+DAO.swift
index 89efd4cd7..82d8b199d 100644
--- a/GRDB/Record/MutablePersistableRecord+DAO.swift
+++ b/GRDB/Record/MutablePersistableRecord+DAO.swift
@@ -249,12 +249,17 @@ final class DAO {
statement.setUncheckedArguments(arguments)
return statement
} else {
- let context = SQLGenerationContext(db)
+ // Generate the RETURNING clause by turning selection into SQL.
+ // Make sure the selection is qualified with a table alias, so
+ // that selectables such as `.allColumns(excluding:)` can query
+ // the database about the database table.
+ let alias = TableAlias(tableName: databaseTableName)
+ let context = SQLGenerationContext(db, aliases: [alias])
var sql = sql
var arguments = arguments
sql += " RETURNING "
sql += try selection
- .map { try $0.sqlSelection.sql(context) }
+ .map { try $0.sqlSelection.qualified(with: alias).sql(context) }
.joined(separator: ", ")
arguments += context.arguments
let statement = try db.internalCachedStatement(sql: sql)
diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift
index eed3a1292..443ddf728 100644
--- a/GRDB/Record/Record.swift
+++ b/GRDB/Record/Record.swift
@@ -107,7 +107,7 @@ open class Record {
/// try PartialPlayer.fetchAll(db)
/// ```
open class var databaseSelection: [any SQLSelectable] {
- [AllColumns()]
+ [.allColumns]
}
/// Encodes the record into the provided persistence container.
diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift
index 72719873c..f246419d5 100644
--- a/GRDB/Record/TableRecord.swift
+++ b/GRDB/Record/TableRecord.swift
@@ -135,7 +135,7 @@ public protocol TableRecord {
/// ```swift
/// struct Player: TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
- /// [AllColumns()]
+ /// [.allColumns]
/// }
/// }
///
@@ -168,7 +168,7 @@ public protocol TableRecord {
/// > // concurrency-safe because non-'Sendable' type
/// > // '[any SQLSelectable]' may have shared
/// > // mutable state.
- /// > static let databaseSelection: [any SQLSelectable] = [AllColumns()]
+ /// > static let databaseSelection: [any SQLSelectable] = [.allColumns]
/// > ```
static var databaseSelection: [any SQLSelectable] { get }
}
@@ -215,9 +215,9 @@ extension TableRecord {
defaultDatabaseTableName
}
- /// The default selection is all columns: `[AllColumns()]`.
+ /// The default selection is all columns: `[.allColumns]`.
public static var databaseSelection: [any SQLSelectable] {
- [AllColumns()]
+ [.allColumns]
}
}
From c5366f4a01a2eb3947ed11d85ab5ad14c1d4024b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 19 Jan 2025 15:23:24 +0100
Subject: [PATCH 12/18] AllColumnsExcluding documentation
---
Documentation/QueryInterfaceOrganization.md | 4 +-
.../DatabaseSchemaRecommendations.md | 2 +-
GRDB/QueryInterface/SQL/SQLSelection.swift | 6 +-
.../Schema/ColumnDefinition.swift | 92 +++++++++++++++++++
GRDB/Record/TableRecord.swift | 10 ++
README.md | 34 +++++--
6 files changed, 135 insertions(+), 13 deletions(-)
diff --git a/Documentation/QueryInterfaceOrganization.md b/Documentation/QueryInterfaceOrganization.md
index e78e652a0..0619b9a41 100644
--- a/Documentation/QueryInterfaceOrganization.md
+++ b/Documentation/QueryInterfaceOrganization.md
@@ -497,7 +497,7 @@ protocol SQLSelectable {
SQLSelectable feeds the `select()` method of the query interface:
```swift
-Player.select(AllColumns())
+Player.select(.allColumns)
Player.select(Column("name"), Column("score"))
```
@@ -505,7 +505,7 @@ All [SQLSpecificExpressible] values are selectable. Other selectable values are:
```swift
// SELECT * FROM player
-Player.select(AllColumns())
+Player.select(.allColumns)
// SELECT MAX(score) AS maxScore FROM player
Player.select(max(Column("score")).forKey("maxScore"))
diff --git a/GRDB/Documentation.docc/DatabaseSchemaRecommendations.md b/GRDB/Documentation.docc/DatabaseSchemaRecommendations.md
index 997981ece..cb92143bb 100644
--- a/GRDB/Documentation.docc/DatabaseSchemaRecommendations.md
+++ b/GRDB/Documentation.docc/DatabaseSchemaRecommendations.md
@@ -151,7 +151,7 @@ extension Player: FetchableRecord, MutablePersistableRecord {
// Required because the primary key
// is the hidden rowid column.
static var databaseSelection: [any SQLSelectable] {
- [AllColumns(), Column.rowID]
+ [.allColumns, .rowID]
}
// Update id upon successful insertion
diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift
index 95ccd4ce7..d4f052fa1 100644
--- a/GRDB/QueryInterface/SQL/SQLSelection.swift
+++ b/GRDB/QueryInterface/SQL/SQLSelection.swift
@@ -440,7 +440,7 @@ extension SQLSelectable where Self == AllColumns {
/// ```swift
/// struct Player: TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
-/// [.allColumns(excluding: ["computedColumn"])]
+/// [.allColumns(excluding: ["generatedColumn"])]
/// }
/// }
///
@@ -471,7 +471,7 @@ extension SQLSelectable where Self == AllColumnsExcluding {
/// ```swift
/// struct Player: TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
- /// [.allColumns(excluding: ["computedColumn"])]
+ /// [.allColumns(excluding: ["generatedColumn"])]
/// }
/// }
///
@@ -489,7 +489,7 @@ extension SQLSelectable where Self == AllColumnsExcluding {
/// ```swift
/// struct Player: TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
- /// [.allColumns(excluding: [Column("computedColumn")])]
+ /// [.allColumns(excluding: [Column("generatedColumn")])]
/// }
/// }
///
diff --git a/GRDB/QueryInterface/Schema/ColumnDefinition.swift b/GRDB/QueryInterface/Schema/ColumnDefinition.swift
index 88cf0103a..c398ed11e 100644
--- a/GRDB/QueryInterface/Schema/ColumnDefinition.swift
+++ b/GRDB/QueryInterface/Schema/ColumnDefinition.swift
@@ -370,6 +370,29 @@ public final class ColumnDefinition {
/// }
/// ```
///
+ /// When you want to ignore generated columns in record types, instruct
+ /// GRDB not to select them:
+ ///
+ /// ```swift
+ /// struct Player: Codable {
+ /// // No property for `totalScore`
+ /// var id: Int64
+ /// var score: Int
+ /// var bonus: Int
+ /// }
+ ///
+ /// extension Player: FetchableRecord, PersistableRecord {
+ /// static var databaseSelection: [any SQLSelectable] {
+ /// [.allColumns(excluding: ["totalScore"])]
+ /// }
+ /// }
+ ///
+ /// // SELECT id, score, bonus FROM player
+ /// let players = try dbQueue.read { db in
+ /// try Player.fetchAll(db)
+ /// }
+ /// ```
+ ///
/// Related SQLite documentation:
///
/// - parameters:
@@ -409,6 +432,29 @@ public final class ColumnDefinition {
/// }
/// ```
///
+ /// When you want to ignore generated columns in record types, instruct
+ /// GRDB not to select them:
+ ///
+ /// ```swift
+ /// struct Player: Codable {
+ /// // No property for `totalScore`
+ /// var id: Int64
+ /// var score: Int
+ /// var bonus: Int
+ /// }
+ ///
+ /// extension Player: FetchableRecord, PersistableRecord {
+ /// static var databaseSelection: [any SQLSelectable] {
+ /// [.allColumns(excluding: ["totalScore"])]
+ /// }
+ /// }
+ ///
+ /// // SELECT id, score, bonus FROM player
+ /// let players = try dbQueue.read { db in
+ /// try Player.fetchAll(db)
+ /// }
+ /// ```
+ ///
/// Related SQLite documentation:
///
/// - parameters:
@@ -447,6 +493,29 @@ public final class ColumnDefinition {
/// }
/// ```
///
+ /// When you want to ignore generated columns in record types, instruct
+ /// GRDB not to select them:
+ ///
+ /// ```swift
+ /// struct Player: Codable {
+ /// // No property for `totalScore`
+ /// var id: Int64
+ /// var score: Int
+ /// var bonus: Int
+ /// }
+ ///
+ /// extension Player: FetchableRecord, PersistableRecord {
+ /// static var databaseSelection: [any SQLSelectable] {
+ /// [.allColumns(excluding: ["totalScore"])]
+ /// }
+ /// }
+ ///
+ /// // SELECT id, score, bonus FROM player
+ /// let players = try dbQueue.read { db in
+ /// try Player.fetchAll(db)
+ /// }
+ /// ```
+ ///
/// Related SQLite documentation:
///
/// - parameters:
@@ -487,6 +556,29 @@ public final class ColumnDefinition {
/// }
/// ```
///
+ /// When you want to ignore generated columns in record types, instruct
+ /// GRDB not to select them:
+ ///
+ /// ```swift
+ /// struct Player: Codable {
+ /// // No property for `totalScore`
+ /// var id: Int64
+ /// var score: Int
+ /// var bonus: Int
+ /// }
+ ///
+ /// extension Player: FetchableRecord, PersistableRecord {
+ /// static var databaseSelection: [any SQLSelectable] {
+ /// [.allColumns(excluding: ["totalScore"])]
+ /// }
+ /// }
+ ///
+ /// // SELECT id, score, bonus FROM player
+ /// let players = try dbQueue.read { db in
+ /// try Player.fetchAll(db)
+ /// }
+ /// ```
+ ///
/// Related SQLite documentation:
///
/// - parameters:
diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift
index f246419d5..68da21851 100644
--- a/GRDB/Record/TableRecord.swift
+++ b/GRDB/Record/TableRecord.swift
@@ -134,6 +134,7 @@ public protocol TableRecord {
///
/// ```swift
/// struct Player: TableRecord {
+ /// // This is the default
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns]
/// }
@@ -146,11 +147,20 @@ public protocol TableRecord {
/// }
/// }
///
+ /// struct Team: TableRecord {
+ /// static var databaseSelection: [any SQLSelectable] {
+ /// [.allColumns(excluding: ["generatedColumn"])]
+ /// }
+ /// }
+ ///
/// // SELECT * FROM player
/// try Player.fetchAll(db)
///
/// // SELECT id, name FROM player
/// try PartialPlayer.fetchAll(db)
+ ///
+ /// // SELECT id, name, color FROM team
+ /// try Team.fetchAll(db)
/// ```
///
/// > Important: Make sure the `databaseSelection` property is
diff --git a/README.md b/README.md
index c01c0864c..aacabce0a 100644
--- a/README.md
+++ b/README.md
@@ -3604,21 +3604,41 @@ let request = Player.select(max(Column("score")), as: Int.self)
let maxScore = try request.fetchOne(db) // Int?
```
-The default selection for a record type is controlled by the `databaseSelection` property:
+The default selection for a record type is controlled by the `databaseSelection` property. For example:
```swift
+// Select a limited set of columns
struct RestrictedPlayer : TableRecord {
static let databaseTableName = "player"
- static var databaseSelection: [any SQLSelectable] { [Column("id"), Column("name")] }
-}
-
-struct ExtendedPlayer : TableRecord {
- static let databaseTableName = "player"
- static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
+ static var databaseSelection: [any SQLSelectable] {
+ [Column("id"), Column("name")]
+ }
}
// SELECT id, name FROM player
let request = RestrictedPlayer.all()
+```
+
+```swift
+// Select all but a few columns
+struct Player : TableRecord {
+ static var databaseSelection: [any SQLSelectable] {
+ [.allColumns(excluding: ["generatedColumn"])]
+ }
+}
+
+// SELECT id, name FROM player
+let request = RestrictedPlayer.all()
+```
+
+```swift
+// Select all columns are more
+struct ExtendedPlayer : TableRecord {
+ static let databaseTableName = "player"
+ static var databaseSelection: [any SQLSelectable] {
+ [.allColumns, .rowID]
+ }
+}
// SELECT *, rowid FROM player
let request = ExtendedPlayer.all()
From 6b23181337410bfa5f5c310a04833d44e607baf9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 19 Jan 2025 15:29:12 +0100
Subject: [PATCH 13/18] Use .allColumns and .rowID instead of AllColumns() and
Column.rowID
---
.../AssociationBelongsToSQLDerivationTests.swift | 6 +++---
.../AssociationHasOneSQLDerivationTests.swift | 6 +++---
...ssociationHasOneThroughSQLDerivationTests.swift | 6 +++---
Tests/GRDBTests/DerivableRequestTests.swift | 8 ++++----
Tests/GRDBTests/FTS3RecordTests.swift | 2 +-
Tests/GRDBTests/FTS4RecordTests.swift | 2 +-
Tests/GRDBTests/FTS5RecordTests.swift | 2 +-
.../GRDBTests/MutablePersistableRecordTests.swift | 14 +++++++-------
.../RecordPrimaryKeyHiddenRowIDTests.swift | 2 +-
Tests/GRDBTests/SQLLiteralTests.swift | 8 ++++----
Tests/GRDBTests/TableRecordDeleteTests.swift | 4 ++--
Tests/GRDBTests/TableRecordTests.swift | 2 +-
12 files changed, 31 insertions(+), 31 deletions(-)
diff --git a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift
index 829ff6c02..d49743028 100644
--- a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift
+++ b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift
@@ -21,7 +21,7 @@ private struct RestrictedB : TableRecord {
private struct ExtendedB : TableRecord {
static let databaseTableName = "b"
- static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
+ static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
}
/// Test SQL generation
@@ -76,8 +76,8 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
do {
let request = A.including(required: A.b
.select(
- AllColumns(),
- Column.rowID))
+ .allColumns,
+ .rowID))
try assertEqualSQL(db, request, """
SELECT "a".*, "b".*, "b"."rowid" \
FROM "a" \
diff --git a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift
index 32bd7f465..230695f06 100644
--- a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift
+++ b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift
@@ -21,7 +21,7 @@ private struct RestrictedB : TableRecord {
private struct ExtendedB : TableRecord {
static let databaseTableName = "b"
- static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
+ static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
}
/// Test SQL generation
@@ -76,8 +76,8 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
do {
let request = A.including(required: A.b
.select(
- AllColumns(),
- Column.rowID))
+ .allColumns,
+ .rowID))
try assertEqualSQL(db, request, """
SELECT "a".*, "b".*, "b"."rowid" \
FROM "a" \
diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift
index 47dff4710..6e974ab3a 100644
--- a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift
+++ b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift
@@ -24,7 +24,7 @@ private struct RestrictedC : TableRecord {
private struct ExtendedC : TableRecord {
static let databaseTableName = "c"
- static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
+ static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
}
/// Test SQL generation
@@ -87,8 +87,8 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase {
do {
let request = A.including(required: A.c
.select(
- AllColumns(),
- Column.rowID))
+ .allColumns,
+ .rowID))
try assertEqualSQL(db, request, """
SELECT "a".*, "c".*, "c"."rowid" \
FROM "a" \
diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift
index 98b0c87fb..aa8681d7c 100644
--- a/Tests/GRDBTests/DerivableRequestTests.swift
+++ b/Tests/GRDBTests/DerivableRequestTests.swift
@@ -174,11 +174,11 @@ class DerivableRequestTests: GRDBTestCase {
try libraryMigrator.migrate(dbQueue)
try dbQueue.inDatabase { db in
try db.create(view: "authorView", as: Author.select(
- AllColumns(),
+ .allColumns,
[Column("firstName"), Column("lastName")]
.joined(operator: .concat)
.forKey("fullName")))
-
+
// ... for one table
clearSQLQueries()
let authorNames = try Author.all()
@@ -221,7 +221,7 @@ class DerivableRequestTests: GRDBTestCase {
XCTAssertEqual(lastSQLQuery, """
SELECT * FROM "author" ORDER BY "id"
""")
-
+
clearSQLQueries()
_ /* stableOrderAuthors */ = try Author.all()
.orderByFullName()
@@ -267,7 +267,7 @@ class DerivableRequestTests: GRDBTestCase {
XCTAssertEqual(lastSQLQuery, """
SELECT * FROM "authorView" ORDER BY 1, 2, 3, 4, 5
""")
-
+
clearSQLQueries()
_ /* stableOrderAuthorViews */ = try Table("authorView").all()
.order(Column("fullName"))
diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift
index 0369fc959..162532342 100644
--- a/Tests/GRDBTests/FTS3RecordTests.swift
+++ b/Tests/GRDBTests/FTS3RecordTests.swift
@@ -19,7 +19,7 @@ extension Book : FetchableRecord {
extension Book : MutablePersistableRecord {
static let databaseTableName = "books"
- static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
+ static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
func encode(to container: inout PersistenceContainer) {
container[.rowID] = id
diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift
index c197dfad9..ed3641c10 100644
--- a/Tests/GRDBTests/FTS4RecordTests.swift
+++ b/Tests/GRDBTests/FTS4RecordTests.swift
@@ -19,7 +19,7 @@ extension Book : FetchableRecord {
extension Book : MutablePersistableRecord {
static let databaseTableName = "books"
- static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
+ static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
func encode(to container: inout PersistenceContainer) {
container[.rowID] = id
diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift
index 0a47ce2ce..1415a5631 100644
--- a/Tests/GRDBTests/FTS5RecordTests.swift
+++ b/Tests/GRDBTests/FTS5RecordTests.swift
@@ -20,7 +20,7 @@ extension Book : FetchableRecord {
extension Book : MutablePersistableRecord {
static let databaseTableName = "books"
- static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
+ static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
func encode(to container: inout PersistenceContainer) {
container[.rowID] = id
diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift
index a5da3c08d..d18bfc8b4 100644
--- a/Tests/GRDBTests/MutablePersistableRecordTests.swift
+++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift
@@ -1802,7 +1802,7 @@ extension MutablePersistableRecordTests {
try dbQueue.inDatabase { db in
var player = FullPlayer(id: 1, name: "Arthur", score: 1000)
do {
- _ = try player.updateAndFetch(db, selection: [AllColumns()]) { statement in
+ _ = try player.updateAndFetch(db, selection: [.allColumns]) { statement in
try Row.fetchOne(statement)
}
XCTFail("Expected RecordError")
@@ -1813,7 +1813,7 @@ extension MutablePersistableRecordTests {
player.score = 0
do {
- let row = try player.updateAndFetch(db, selection: [AllColumns()]) { statement in
+ let row = try player.updateAndFetch(db, selection: [.allColumns]) { statement in
try Row.fetchOne(statement)
}
XCTAssertEqual(row, ["id": 1, "name": "Barbara", "score": 0])
@@ -1856,7 +1856,7 @@ extension MutablePersistableRecordTests {
try dbQueue.inDatabase { db in
var player = FullPlayer(id: 1, name: "Arthur", score: 1000)
do {
- _ = try player.updateAndFetch(db, columns: [Column("score")], selection: [AllColumns()]) { statement in
+ _ = try player.updateAndFetch(db, columns: [Column("score")], selection: [.allColumns]) { statement in
try Row.fetchOne(statement)
}
XCTFail("Expected RecordError")
@@ -1867,7 +1867,7 @@ extension MutablePersistableRecordTests {
player.score = 0
do {
- let row = try player.updateAndFetch(db, columns: [Column("score")], selection: [AllColumns()]) { statement in
+ let row = try player.updateAndFetch(db, columns: [Column("score")], selection: [.allColumns]) { statement in
try Row.fetchOne(statement)
}
XCTAssertEqual(row, ["id": 1, "name": "Arthur", "score": 0])
@@ -2032,7 +2032,7 @@ extension MutablePersistableRecordTests {
var player = FullPlayer(id: 1, name: "Arthur", score: 1000)
do {
_ = try player.updateChangesAndFetch(
- db, selection: [AllColumns()],
+ db, selection: [.allColumns],
fetch: { statement in try Row.fetchOne(statement) },
modify: { $0.name = "Barbara" })
XCTFail("Expected RecordError")
@@ -2043,7 +2043,7 @@ extension MutablePersistableRecordTests {
do {
// Update with no change
let update = try player.updateChangesAndFetch(
- db, selection: [AllColumns()],
+ db, selection: [.allColumns],
fetch: { statement in
XCTFail("Should not be called")
return "ignored"
@@ -2054,7 +2054,7 @@ extension MutablePersistableRecordTests {
do {
let updatedRow = try player.updateChangesAndFetch(
- db, selection: [AllColumns()],
+ db, selection: [.allColumns],
fetch: { statement in try Row.fetchOne(statement) },
modify: { $0.name = "Craig" })
XCTAssertEqual(updatedRow, ["id": 1, "name": "Craig", "score": 1000])
diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift
index ca99bceb3..d8bc981db 100644
--- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift
+++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift
@@ -28,7 +28,7 @@ private class Person : Record, Hashable {
// Record
override static var databaseSelection: [any SQLSelectable] {
- [AllColumns(), Column.rowID]
+ [.allColumns, .rowID]
}
override class var databaseTableName: String {
diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift
index d49de427a..7a5c0d7ba 100644
--- a/Tests/GRDBTests/SQLLiteralTests.swift
+++ b/Tests/GRDBTests/SQLLiteralTests.swift
@@ -640,7 +640,7 @@ extension SQLLiteralTests {
func testPlusOperatorWithInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
- var query: SQL = "SELECT \(AllColumns()) "
+ var query: SQL = "SELECT \(.allColumns) "
query = query + "FROM player "
query = query + "WHERE id = \(1)"
@@ -654,7 +654,7 @@ extension SQLLiteralTests {
func testPlusEqualOperatorWithInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
- var query: SQL = "SELECT \(AllColumns()) "
+ var query: SQL = "SELECT \(.allColumns) "
query += "FROM player "
query += "WHERE id = \(1)"
@@ -668,7 +668,7 @@ extension SQLLiteralTests {
func testAppendLiteralWithInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
- var query: SQL = "SELECT \(AllColumns()) "
+ var query: SQL = "SELECT \(.allColumns) "
query.append(literal: "FROM player ")
query.append(literal: "WHERE id = \(1)")
@@ -682,7 +682,7 @@ extension SQLLiteralTests {
func testAppendRawSQLWithInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
- var query: SQL = "SELECT \(AllColumns()) "
+ var query: SQL = "SELECT \(.allColumns) "
query.append(sql: "FROM player ")
query.append(sql: "WHERE score > \(1000) ")
query.append(sql: "AND \("name") = :name", arguments: ["name": "Arthur"])
diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift
index 758d314ed..dc0656dad 100644
--- a/Tests/GRDBTests/TableRecordDeleteTests.swift
+++ b/Tests/GRDBTests/TableRecordDeleteTests.swift
@@ -479,7 +479,7 @@ class TableRecordDeleteTests: GRDBTestCase {
do {
let request = Player.including(required: Player.team)
- let statement = try request.deleteAndFetchStatement(db, selection: [AllColumns()])
+ let statement = try request.deleteAndFetchStatement(db, selection: [.allColumns])
XCTAssertEqual(statement.sql, """
DELETE FROM "player" WHERE "id" IN (\
SELECT "player"."id" \
@@ -511,7 +511,7 @@ class TableRecordDeleteTests: GRDBTestCase {
}
do {
let request = Team.having(Team.players.isEmpty)
- let statement = try request.deleteAndFetchStatement(db, selection: [AllColumns()])
+ let statement = try request.deleteAndFetchStatement(db, selection: [.allColumns])
XCTAssertEqual(statement.sql, """
DELETE FROM "team" WHERE "id" IN (\
SELECT "team"."id" \
diff --git a/Tests/GRDBTests/TableRecordTests.swift b/Tests/GRDBTests/TableRecordTests.swift
index e1c653635..e5ad72156 100644
--- a/Tests/GRDBTests/TableRecordTests.swift
+++ b/Tests/GRDBTests/TableRecordTests.swift
@@ -103,7 +103,7 @@ class TableRecordTests: GRDBTestCase {
func testExtendedDatabaseSelection() throws {
struct Record: TableRecord {
static let databaseTableName = "t1"
- static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
+ static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
From 33103bb37380d1c0398c770d0354c37918582187 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 19 Jan 2025 15:30:21 +0100
Subject: [PATCH 14/18] AllColumnsExcluding tests
---
.../AssociationBelongsToRowScopeTests.swift | 54 +++
...sociationBelongsToSQLDerivationTests.swift | 23 +-
.../AssociationBelongsToSQLTests.swift | 179 ++++++++-
.../AssociationHasOneSQLDerivationTests.swift | 23 +-
...ationHasOneThroughSQLDerivationTests.swift | 21 +-
Tests/GRDBTests/PersistableRecordTests.swift | 352 +++++++++++++++++-
Tests/GRDBTests/SQLLiteralTests.swift | 40 +-
...bleRecord+QueryInterfaceRequestTests.swift | 26 ++
Tests/GRDBTests/TableRecordDeleteTests.swift | 22 +-
Tests/GRDBTests/TableRecordTests.swift | 15 +
Tests/GRDBTests/TableRecordUpdateTests.swift | 26 +-
11 files changed, 751 insertions(+), 30 deletions(-)
diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift
index 813a993e2..e21ebefe4 100644
--- a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift
+++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift
@@ -66,6 +66,16 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[0].scopes["team"]!, ["id":1, "name":"Reds"])
}
+ func testDefaultScopeIncludingRequiredRestrictedSelection() throws {
+ let dbQueue = try makeDatabaseQueue()
+ let request = Player.select(.allColumns(excluding: ["name"])).including(required: Player.defaultTeam)
+ let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
+ XCTAssertEqual(rows.count, 1)
+ XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1])
+ XCTAssertEqual(Set(rows[0].scopes.names), ["team"])
+ XCTAssertEqual(rows[0].scopes["team"]!, ["id":1, "name":"Reds"])
+ }
+
func testDefaultScopeAnnotatedWithRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withRequired: Player.defaultTeam)
@@ -82,6 +92,14 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "teamName":"Reds"])
}
+ func testDefaultScopeAnnotatedWithRequiredRestrictedSelection() throws {
+ let dbQueue = try makeDatabaseQueue()
+ let request = Player.annotated(withRequired: Player.defaultTeam.select(.allColumns(excluding: ["name"])))
+ let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
+ XCTAssertEqual(rows.count, 1)
+ XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1])
+ }
+
func testDefaultScopeIncludingOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.including(optional: Player.defaultTeam)
@@ -113,6 +131,15 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "teamName":nil])
}
+ func testDefaultScopeAnnotatedWithOptionalRestrictedSelection() throws {
+ let dbQueue = try makeDatabaseQueue()
+ let request = Player.annotated(withOptional: Player.defaultTeam.select(.allColumns(excluding: ["name"])))
+ let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
+ XCTAssertEqual(rows.count, 2)
+ XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1])
+ XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "id":nil])
+ }
+
func testDefaultScopeJoiningRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.joining(required: Player.defaultTeam)
@@ -153,6 +180,16 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[0].scopes["customTeam"]!, ["id":1, "name":"Reds"])
}
+ func testCustomScopeIncludingRequiredRestrictedSelection() throws {
+ let dbQueue = try makeDatabaseQueue()
+ let request = Player.select(.allColumns(excluding: ["name"])).including(required: Player.customTeam)
+ let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
+ XCTAssertEqual(rows.count, 1)
+ XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1])
+ XCTAssertEqual(Set(rows[0].scopes.names), ["customTeam"])
+ XCTAssertEqual(rows[0].scopes["customTeam"]!, ["id":1, "name":"Reds"])
+ }
+
func testCustomScopeAnnotatedWithRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withRequired: Player.customTeam)
@@ -169,6 +206,14 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "teamName":"Reds"])
}
+ func testCustomScopeAnnotatedWithRequiredRestrictedSelection() throws {
+ let dbQueue = try makeDatabaseQueue()
+ let request = Player.annotated(withRequired: Player.customTeam.select(.allColumns(excluding: ["name"])))
+ let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
+ XCTAssertEqual(rows.count, 1)
+ XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1])
+ }
+
func testCustomScopeIncludingOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.including(optional: Player.customTeam)
@@ -200,6 +245,15 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "teamName":nil])
}
+ func testCustomScopeAnnotatedWithOptionalRestrictedSelection() throws {
+ let dbQueue = try makeDatabaseQueue()
+ let request = Player.annotated(withOptional: Player.customTeam.select(.allColumns(excluding: ["name"])))
+ let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
+ XCTAssertEqual(rows.count, 2)
+ XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1])
+ XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "id":nil])
+ }
+
func testCustomPluralScopeIncludingRequired() throws {
// Make sure explicit plural keys are preserved
let dbQueue = try makeDatabaseQueue()
diff --git a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift
index d49743028..2cd18cab5 100644
--- a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift
+++ b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift
@@ -5,7 +5,8 @@ import GRDB
private struct A : TableRecord {
static let databaseTableName = "a"
static let b = belongsTo(B.self)
- static let restrictedB = belongsTo(RestrictedB.self)
+ static let restrictedB1 = belongsTo(RestrictedB1.self)
+ static let restrictedB2 = belongsTo(RestrictedB2.self)
static let extendedB = belongsTo(ExtendedB.self)
}
@@ -14,11 +15,16 @@ private struct B : TableRecord {
static let databaseTableName = "b"
}
-private struct RestrictedB : TableRecord {
+private struct RestrictedB1 : TableRecord {
static let databaseTableName = "b"
static var databaseSelection: [any SQLSelectable] { [Column("name")] }
}
+private struct RestrictedB2 : TableRecord {
+ static let databaseTableName = "b"
+ static var databaseSelection: [any SQLSelectable] { [.allColumns(excluding: ["id"])] }
+}
+
private struct ExtendedB : TableRecord {
static let databaseTableName = "b"
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
@@ -48,7 +54,12 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
FROM "a" \
JOIN "b" ON "b"."id" = "a"."bid"
""")
- try assertEqualSQL(db, A.including(required: A.restrictedB), """
+ try assertEqualSQL(db, A.including(required: A.restrictedB1), """
+ SELECT "a".*, "b"."name" \
+ FROM "a" \
+ JOIN "b" ON "b"."id" = "a"."bid"
+ """)
+ try assertEqualSQL(db, A.including(required: A.restrictedB2), """
SELECT "a".*, "b"."name" \
FROM "a" \
JOIN "b" ON "b"."id" = "a"."bid"
@@ -89,9 +100,9 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
let request = A
.aliased(aAlias)
.including(required: A.b
- .select(
- Column("name"),
- (Column("id") + aAlias[Column("id")]).forKey("foo")))
+ .select(
+ Column("name"),
+ (Column("id") + aAlias[Column("id")]).forKey("foo")))
try assertEqualSQL(db, request, """
SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \
FROM "a" \
diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift
index 2e44dfc36..3e4c2fd43 100644
--- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift
+++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift
@@ -76,6 +76,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."rowid" = "children"."parentId"
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
+ SELECT "children".*, "parents".* \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."rowid" = "children"."parentId"
+ """)
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
+ SELECT "children".*, "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."rowid" = "children"."parentId"
+ """)
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "rowid" = 1
@@ -139,6 +149,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
+ SELECT "children".*, "parents".* \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
+ """)
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
+ SELECT "children".*, "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
+ """)
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -229,6 +249,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
+ SELECT "children".*, "parents".* \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
+ """)
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
+ SELECT "children".*, "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
+ """)
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -292,6 +322,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
+ SELECT "children".*, "parents".* \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
+ """)
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
+ SELECT "children".*, "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
+ """)
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -380,6 +420,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
+ SELECT "children".*, "parents".* \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
+ """)
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
+ SELECT "children".*, "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
+ """)
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -443,6 +493,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
+ SELECT "children".*, "parents".* \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
+ """)
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
+ SELECT "children".*, "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
+ """)
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -506,6 +566,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
+ SELECT "children".*, "parents".* \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
+ """)
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
+ SELECT "children".*, "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
+ """)
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -599,6 +669,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
+ SELECT "children".*, "parents".* \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
+ """)
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
+ SELECT "children".*, "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
+ """)
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -662,6 +742,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
+ SELECT "children".*, "parents".* \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
+ """)
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
+ SELECT "children".*, "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
+ """)
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -725,7 +815,17 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
""")
-
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
+ SELECT "children".*, "parents".* \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
+ """)
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
+ SELECT "children".*, "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
+ """)
+
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 2
""")
@@ -788,6 +888,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
+ SELECT "children".*, "parents".* \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
+ """)
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
+ SELECT "children".*, "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
+ """)
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 2
@@ -882,6 +992,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
+ SELECT "children".*, "parents"."b", "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
+ """)
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -991,6 +1106,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
+ SELECT "children".*, "parents"."b", "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
+ """)
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -1068,6 +1188,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
+ SELECT "children".*, "parents"."b", "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
+ """)
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -1176,6 +1301,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
+ SELECT "children".*, "parents"."b", "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
+ """)
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -1253,6 +1383,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
+ SELECT "children".*, "parents"."b", "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
+ """)
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -1330,6 +1465,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
+ SELECT "children".*, "parents"."b", "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
+ """)
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -1447,6 +1587,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
+ SELECT "children".*, "parents"."b", "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
+ """)
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -1524,6 +1669,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
+ SELECT "children".*, "parents"."b", "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
+ """)
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -1601,6 +1751,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
+ SELECT "children".*, "parents"."b", "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
+ """)
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 3) AND ("b" = 4)
@@ -1678,6 +1833,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
+ SELECT "children".*, "parents"."b", "parents"."name" \
+ FROM "children" \
+ LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
+ """)
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 3) AND ("b" = 4)
@@ -1699,7 +1859,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: nil, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """
SELECT "custom".* FROM "parents" "custom" WHERE 0
""")
-
+
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: nil, parent2B: nil).request(for: association), """
SELECT * FROM "parents" WHERE 0
""")
@@ -1896,6 +2056,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
+ SELECT "CHILDREN".*, "PARENTS"."name" \
+ FROM "CHILDREN" \
+ LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
+ """)
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "PARENTS" WHERE "id" = 1
@@ -1959,6 +2124,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
+ SELECT "CHILDREN".*, "PARENTS"."name" \
+ FROM "CHILDREN" \
+ LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
+ """)
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "PARENTS" WHERE "id" = 1
@@ -2022,6 +2192,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID"
""")
+ try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
+ SELECT "CHILDREN".*, "PARENTS"."name" \
+ FROM "CHILDREN" \
+ LEFT JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID"
+ """)
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "PARENTS" WHERE "ID" = 1
diff --git a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift
index 230695f06..ff449c841 100644
--- a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift
+++ b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift
@@ -5,7 +5,8 @@ import GRDB
private struct A : TableRecord {
static let databaseTableName = "a"
static let b = hasOne(B.self)
- static let restrictedB = hasOne(RestrictedB.self)
+ static let restrictedB1 = hasOne(RestrictedB1.self)
+ static let restrictedB2 = hasOne(RestrictedB2.self)
static let extendedB = hasOne(ExtendedB.self)
}
@@ -14,11 +15,16 @@ private struct B : TableRecord {
static let databaseTableName = "b"
}
-private struct RestrictedB : TableRecord {
+private struct RestrictedB1 : TableRecord {
static let databaseTableName = "b"
static var databaseSelection: [any SQLSelectable] { [Column("name")] }
}
+private struct RestrictedB2 : TableRecord {
+ static let databaseTableName = "b"
+ static var databaseSelection: [any SQLSelectable] { [.allColumns(excluding: ["id"])] }
+}
+
private struct ExtendedB : TableRecord {
static let databaseTableName = "b"
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
@@ -48,11 +54,16 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
FROM "a" \
JOIN "b" ON "b"."aid" = "a"."id"
""")
- try assertEqualSQL(db, A.including(required: A.restrictedB), """
+ try assertEqualSQL(db, A.including(required: A.restrictedB1), """
SELECT "a".*, "b"."name" \
FROM "a" \
JOIN "b" ON "b"."aid" = "a"."id"
""")
+ try assertEqualSQL(db, A.including(required: A.restrictedB2), """
+ SELECT "a".*, "b"."aid", "b"."name" \
+ FROM "a" \
+ JOIN "b" ON "b"."aid" = "a"."id"
+ """)
try assertEqualSQL(db, A.including(required: A.extendedB), """
SELECT "a".*, "b".*, "b"."rowid" \
FROM "a" \
@@ -89,9 +100,9 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
let request = A
.aliased(aAlias)
.including(required: A.b
- .select(
- Column("name"),
- (Column("id") + aAlias[Column("id")]).forKey("foo")))
+ .select(
+ Column("name"),
+ (Column("id") + aAlias[Column("id")]).forKey("foo")))
try assertEqualSQL(db, request, """
SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \
FROM "a" \
diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift
index 6e974ab3a..06ceee522 100644
--- a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift
+++ b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift
@@ -4,24 +4,31 @@ import GRDB
private struct A: TableRecord {
static let b = belongsTo(B.self)
static let c = hasOne(C.self, through: b, using: B.c)
- static let restrictedC = hasOne(RestrictedC.self, through: b, using: B.restrictedC)
+ static let restrictedC1 = hasOne(RestrictedC1.self, through: b, using: B.restrictedC1)
+ static let restrictedC2 = hasOne(RestrictedC2.self, through: b, using: B.restrictedC2)
static let extendedC = hasOne(ExtendedC.self, through: b, using: B.extendedC)
}
private struct B: TableRecord {
static let c = belongsTo(C.self)
- static let restrictedC = belongsTo(RestrictedC.self)
+ static let restrictedC1 = belongsTo(RestrictedC1.self)
+ static let restrictedC2 = belongsTo(RestrictedC2.self)
static let extendedC = belongsTo(ExtendedC.self)
}
private struct C: TableRecord {
}
-private struct RestrictedC : TableRecord {
+private struct RestrictedC1 : TableRecord {
static let databaseTableName = "c"
static var databaseSelection: [any SQLSelectable] { [Column("name")] }
}
+private struct RestrictedC2 : TableRecord {
+ static let databaseTableName = "c"
+ static var databaseSelection: [any SQLSelectable] { [.allColumns(excluding: ["id"])] }
+}
+
private struct ExtendedC : TableRecord {
static let databaseTableName = "c"
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
@@ -56,7 +63,13 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase {
JOIN "b" ON "b"."id" = "a"."bId" \
JOIN "c" ON "c"."id" = "b"."cId"
""")
- try assertEqualSQL(db, A.including(required: A.restrictedC), """
+ try assertEqualSQL(db, A.including(required: A.restrictedC1), """
+ SELECT "a".*, "c"."name" \
+ FROM "a" \
+ JOIN "b" ON "b"."id" = "a"."bId" \
+ JOIN "c" ON "c"."id" = "b"."cId"
+ """)
+ try assertEqualSQL(db, A.including(required: A.restrictedC2), """
SELECT "a".*, "c"."name" \
FROM "a" \
JOIN "b" ON "b"."id" = "a"."bId" \
diff --git a/Tests/GRDBTests/PersistableRecordTests.swift b/Tests/GRDBTests/PersistableRecordTests.swift
index c391e27da..a6577efb1 100644
--- a/Tests/GRDBTests/PersistableRecordTests.swift
+++ b/Tests/GRDBTests/PersistableRecordTests.swift
@@ -1375,7 +1375,7 @@ extension PersistableRecordTests {
}
}
- func test_insertAndFetch_selection_fetch() throws {
+ func test_insertAndFetch_selection_fetch_column() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -1423,6 +1423,104 @@ extension PersistableRecordTests {
}
}
}
+
+ func test_insertAndFetch_selection_fetch_allColumns() 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
+ do {
+ clearSQLQueries()
+ let partialPlayer = PartialPlayer(name: "Arthur")
+ let row = try partialPlayer.insertAndFetch(db, selection: [.allColumns]) { (statement: Statement) in
+ try Row.fetchOne(statement)!
+ }
+
+ XCTAssert(sqlQueries.contains("""
+ INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING *
+ """), sqlQueries.joined(separator: "\n"))
+
+ XCTAssertEqual(row, ["id": 1, "name": "Arthur", "score": 1000])
+
+ XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0)
+
+ XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0)
+ }
+ }
+ }
+
+ func test_insertAndFetch_selection_fetch_allColumns_excluding() 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
+ do {
+ clearSQLQueries()
+ let partialPlayer = PartialPlayer(name: "Arthur")
+ let row = try partialPlayer.insertAndFetch(db, selection: [.allColumns(excluding: ["score"])]) { (statement: Statement) in
+ try Row.fetchOne(statement)!
+ }
+
+ XCTAssert(sqlQueries.contains("""
+ INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "id", "name"
+ """), sqlQueries.joined(separator: "\n"))
+
+ XCTAssertEqual(row, ["id": 1, "name": "Arthur"])
+
+ XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0)
+
+ XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0)
+ }
+ }
+ }
}
// MARK: - Save and Fetch
@@ -1551,7 +1649,7 @@ extension PersistableRecordTests {
}
}
- func test_saveAndFetch_selection_fetch() throws {
+ func test_saveAndFetch_selection_fetch_column() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -1673,6 +1771,256 @@ extension PersistableRecordTests {
}
}
}
+
+ func test_saveAndFetch_selection_fetch_allColumns() 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
+ do {
+ clearSQLQueries()
+ let partialPlayer = PartialPlayer(name: "Arthur")
+ let row = try partialPlayer.saveAndFetch(db, selection: [.allColumns]) { (
+ statement: Statement
+ ) in
+ try Row.fetchOne(statement)
+ }
+
+ XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") })
+ XCTAssert(sqlQueries.contains("""
+ INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING *
+ """), sqlQueries.joined(separator: "\n"))
+
+ XCTAssertEqual(row, ["id": 1, "name": "Arthur", "score": 1000])
+
+ XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0)
+
+ XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0)
+ }
+
+ do {
+ let partialPlayer = PartialPlayer(id: 1, name: "Arthur")
+ try partialPlayer.delete(db)
+ clearSQLQueries()
+ let row = try partialPlayer.saveAndFetch(db, selection: [.allColumns]) { (statement: Statement) in
+ try Row.fetchOne(statement)
+ }
+
+ XCTAssert(sqlQueries.contains("""
+ UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING *
+ """), sqlQueries.joined(separator: "\n"))
+ XCTAssert(sqlQueries.contains("""
+ INSERT INTO "player" ("id", "name") VALUES (1,'Arthur') RETURNING *
+ """), sqlQueries.joined(separator: "\n"))
+
+ XCTAssertEqual(row, ["id": 1, "name": "Arthur", "score": 1000])
+
+ XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0)
+
+ XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 1)
+ }
+
+ do {
+ clearSQLQueries()
+ let partialPlayer = PartialPlayer(id: 1, name: "Arthur")
+ let row = try partialPlayer.saveAndFetch(db, selection: [.allColumns]) { (statement: Statement) in
+ try Row.fetchOne(statement)
+ }
+
+ XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") })
+ XCTAssert(sqlQueries.contains("""
+ UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING *
+ """), sqlQueries.joined(separator: "\n"))
+
+ XCTAssertEqual(row, ["id": 1, "name": "Arthur", "score": 1000])
+
+ XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 0)
+
+ XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0)
+ }
+ }
+ }
+
+ func test_saveAndFetch_selection_fetch_allColumns_excluding() 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
+ do {
+ clearSQLQueries()
+ let partialPlayer = PartialPlayer(name: "Arthur")
+ let row = try partialPlayer.saveAndFetch(db, selection: [.allColumns(excluding: ["score"])]) { (
+ statement: Statement
+ ) in
+ try Row.fetchOne(statement)
+ }
+
+ XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") })
+ XCTAssert(sqlQueries.contains("""
+ INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "id", "name"
+ """), sqlQueries.joined(separator: "\n"))
+
+ XCTAssertEqual(row, ["id": 1, "name": "Arthur"])
+
+ XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0)
+
+ XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0)
+ }
+
+ do {
+ let partialPlayer = PartialPlayer(id: 1, name: "Arthur")
+ try partialPlayer.delete(db)
+ clearSQLQueries()
+ let row = try partialPlayer.saveAndFetch(db, selection: [.allColumns(excluding: ["score"])]) { (statement: Statement) in
+ try Row.fetchOne(statement)
+ }
+
+ XCTAssert(sqlQueries.contains("""
+ UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING "id", "name"
+ """), sqlQueries.joined(separator: "\n"))
+ XCTAssert(sqlQueries.contains("""
+ INSERT INTO "player" ("id", "name") VALUES (1,'Arthur') RETURNING "id", "name"
+ """), sqlQueries.joined(separator: "\n"))
+
+ XCTAssertEqual(row, ["id": 1, "name": "Arthur"])
+
+ XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0)
+
+ XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 1)
+ }
+
+ do {
+ clearSQLQueries()
+ let partialPlayer = PartialPlayer(id: 1, name: "Arthur")
+ let row = try partialPlayer.saveAndFetch(db, selection: [.allColumns(excluding: ["score"])]) { (statement: Statement) in
+ try Row.fetchOne(statement)
+ }
+
+ XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") })
+ XCTAssert(sqlQueries.contains("""
+ UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING "id", "name"
+ """), sqlQueries.joined(separator: "\n"))
+
+ XCTAssertEqual(row, ["id": 1, "name": "Arthur"])
+
+ XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 0)
+
+ XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
+ XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
+
+ XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0)
+ XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0)
+ }
+ }
+ }
}
// MARK: - Upsert
diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift
index 7a5c0d7ba..e059b4a66 100644
--- a/Tests/GRDBTests/SQLLiteralTests.swift
+++ b/Tests/GRDBTests/SQLLiteralTests.swift
@@ -309,10 +309,22 @@ extension SQLLiteralTests {
try makeDatabaseQueue().inDatabase { db in
struct Player: TableRecord { }
struct AltPlayer: TableRecord {
+ static let databaseTableName: String = "player"
static var databaseSelection: [any SQLSelectable] {
[Column("id"), Column("name")]
}
}
+ struct RestrictedPlayer: TableRecord {
+ static let databaseTableName: String = "player"
+ static var databaseSelection: [any SQLSelectable] {
+ [.allColumns(excluding: ["name"])]
+ }
+ }
+ try db.create(table: "player") { t in
+ t.autoIncrementedPrimaryKey("id")
+ t.column("name", .text)
+ t.column("score", .integer)
+ }
do {
let query: SQL = """
SELECT \(columnsOf: Player.self)
@@ -347,7 +359,7 @@ extension SQLLiteralTests {
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
- SELECT "altPlayer"."id", "altPlayer"."name"
+ SELECT "player"."id", "player"."name"
FROM player
""")
XCTAssert(arguments.isEmpty)
@@ -365,6 +377,32 @@ extension SQLLiteralTests {
""")
XCTAssert(arguments.isEmpty)
}
+ do {
+ let query: SQL = """
+ SELECT \(columnsOf: RestrictedPlayer.self)
+ FROM player
+ """
+
+ let (sql, arguments) = try query.build(db)
+ XCTAssertEqual(sql, """
+ SELECT "player"."id", "player"."score"
+ FROM player
+ """)
+ XCTAssert(arguments.isEmpty)
+ }
+ do {
+ let query: SQL = """
+ SELECT \(columnsOf: RestrictedPlayer.self, tableAlias: "p")
+ FROM player p
+ """
+
+ let (sql, arguments) = try query.build(db)
+ XCTAssertEqual(sql, """
+ SELECT "p"."id", "p"."score"
+ FROM player p
+ """)
+ XCTAssert(arguments.isEmpty)
+ }
}
}
diff --git a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift
index e803c3733..a20b3be99 100644
--- a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift
+++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift
@@ -71,6 +71,32 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase {
XCTAssertEqual(try Reader.select(max(Col.age)).group(Col.name).fetchCount(db), 0)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT MAX(\"age\") FROM \"readers\" GROUP BY \"name\")")
+
+ XCTAssertEqual(try Reader.select(.allColumns(excluding: [] as [String])).fetchCount(db), 0)
+ XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"")
+
+ XCTAssertEqual(try Reader.select(.allColumns(excluding: [] as [String])).distinct().fetchCount(db), 0)
+ XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT * FROM \"readers\")")
+
+ XCTAssertEqual(try Reader.select(.allColumns(excluding: ["name"])).fetchCount(db), 0)
+ XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"")
+
+ XCTAssertEqual(try Reader.select(.allColumns(excluding: ["name"])).distinct().fetchCount(db), 0)
+ XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT \"id\", \"age\" FROM \"readers\")")
+
+ XCTAssertEqual(try Reader.select(.allColumns(excluding: ["id", "name"])).fetchCount(db), 0)
+ XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"")
+
+ XCTAssertEqual(try Reader.select(.allColumns(excluding: ["id", "name"])).distinct().fetchCount(db), 0)
+ // This test tests for a missed optimization, because
+ // SELECT COUNT(DISTINCT age) FROM readers would be correct as well.
+ XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT \"age\" FROM \"readers\")")
+
+ XCTAssertEqual(try Reader.select(.allColumns(excluding: ["unknown"])).fetchCount(db), 0)
+ XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"")
+
+ XCTAssertEqual(try Reader.select(.allColumns(excluding: ["unknown"])).distinct().fetchCount(db), 0)
+ XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT * FROM \"readers\")")
}
}
diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift
index dc0656dad..264daac7a 100644
--- a/Tests/GRDBTests/TableRecordDeleteTests.swift
+++ b/Tests/GRDBTests/TableRecordDeleteTests.swift
@@ -238,10 +238,24 @@ class TableRecordDeleteTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
- let request = Person.all()
- let statement = try request.deleteAndFetchStatement(db, selection: [AllColumns()])
- XCTAssertEqual(statement.sql, "DELETE FROM \"persons\" RETURNING *")
- XCTAssertEqual(statement.columnNames, ["id", "name", "email"])
+ do {
+ let request = Person.all()
+ let statement = try request.deleteAndFetchStatement(db, selection: [Column("name")])
+ XCTAssertEqual(statement.sql, "DELETE FROM \"persons\" RETURNING \"name\"")
+ XCTAssertEqual(statement.columnNames, ["name"])
+ }
+ do {
+ let request = Person.all()
+ let statement = try request.deleteAndFetchStatement(db, selection: [.allColumns])
+ XCTAssertEqual(statement.sql, "DELETE FROM \"persons\" RETURNING *")
+ XCTAssertEqual(statement.columnNames, ["id", "name", "email"])
+ }
+ do {
+ let request = Person.all()
+ let statement = try request.deleteAndFetchStatement(db, selection: [.allColumns(excluding: ["name"])])
+ XCTAssertEqual(statement.sql, "DELETE FROM \"persons\" RETURNING \"id\", \"email\"")
+ XCTAssertEqual(statement.columnNames, ["id", "email"])
+ }
}
}
diff --git a/Tests/GRDBTests/TableRecordTests.swift b/Tests/GRDBTests/TableRecordTests.swift
index e5ad72156..c28a92512 100644
--- a/Tests/GRDBTests/TableRecordTests.swift
+++ b/Tests/GRDBTests/TableRecordTests.swift
@@ -128,6 +128,21 @@ class TableRecordTests: GRDBTestCase {
}
}
+ func testRestrictedDatabaseSelectionWithAllColumnsExcluding() throws {
+ struct Record: TableRecord {
+ static let databaseTableName = "t1"
+ static var databaseSelection: [any SQLSelectable] {
+ [.allColumns(excluding: ["C"])]
+ }
+ }
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.inDatabase { db in
+ try db.execute(sql: "CREATE TABLE t1(a,b,c)")
+ _ = try Row.fetchAll(db, Record.all())
+ XCTAssertEqual(lastSQLQuery, "SELECT \"a\", \"b\" FROM \"t1\"")
+ }
+ }
+
func testRecordInAttachedDatabase() throws {
#if GRDBCIPHER_USE_ENCRYPTION
// Avoid error due to key not being provided:
diff --git a/Tests/GRDBTests/TableRecordUpdateTests.swift b/Tests/GRDBTests/TableRecordUpdateTests.swift
index 44982695a..ce2d9d2ed 100644
--- a/Tests/GRDBTests/TableRecordUpdateTests.swift
+++ b/Tests/GRDBTests/TableRecordUpdateTests.swift
@@ -129,11 +129,27 @@ class TableRecordUpdateTests: GRDBTestCase {
try Player.createTable(db)
let assignment = Columns.score.set(to: 0)
- let request = Player.all()
- let statement = try request.updateAndFetchStatement(db, [assignment], selection: [AllColumns()])
- XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING *")
- XCTAssertEqual(statement.arguments, [0])
- XCTAssertEqual(statement.columnNames, ["id", "name", "score", "bonus"])
+ do {
+ let request = Player.all()
+ let statement = try request.updateAndFetchStatement(db, [assignment], selection: [Column("score")])
+ XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING \"score\"")
+ XCTAssertEqual(statement.arguments, [0])
+ XCTAssertEqual(statement.columnNames, ["score"])
+ }
+ do {
+ let request = Player.all()
+ let statement = try request.updateAndFetchStatement(db, [assignment], selection: [.allColumns])
+ XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING *")
+ XCTAssertEqual(statement.arguments, [0])
+ XCTAssertEqual(statement.columnNames, ["id", "name", "score", "bonus"])
+ }
+ do {
+ let request = Player.all()
+ let statement = try request.updateAndFetchStatement(db, [assignment], selection: [.allColumns(excluding: ["name"])])
+ XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING \"id\", \"score\", \"bonus\"")
+ XCTAssertEqual(statement.arguments, [0])
+ XCTAssertEqual(statement.columnNames, ["id", "score", "bonus"])
+ }
}
}
From 96c9eb5699d6074f043681255bc86d18de2cb7e4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 19 Jan 2025 15:48:48 +0100
Subject: [PATCH 15/18] Enhance documentation of generated columns
---
.../Schema/ColumnDefinition.swift | 28 +++++++++++++------
1 file changed, 20 insertions(+), 8 deletions(-)
diff --git a/GRDB/QueryInterface/Schema/ColumnDefinition.swift b/GRDB/QueryInterface/Schema/ColumnDefinition.swift
index c398ed11e..18ee6a983 100644
--- a/GRDB/QueryInterface/Schema/ColumnDefinition.swift
+++ b/GRDB/QueryInterface/Schema/ColumnDefinition.swift
@@ -370,8 +370,8 @@ public final class ColumnDefinition {
/// }
/// ```
///
- /// When you want to ignore generated columns in record types, instruct
- /// GRDB not to select them:
+ /// To remove the generated columns from the selection of record types,
+ /// define their `databaseSelection`:
///
/// ```swift
/// struct Player: Codable {
@@ -383,6 +383,9 @@ public final class ColumnDefinition {
///
/// extension Player: FetchableRecord, PersistableRecord {
/// static var databaseSelection: [any SQLSelectable] {
+ /// // Option 1
+ /// [Column("id"), Column("score"), Column("bonus")]
+ /// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
@@ -432,8 +435,8 @@ public final class ColumnDefinition {
/// }
/// ```
///
- /// When you want to ignore generated columns in record types, instruct
- /// GRDB not to select them:
+ /// To remove the generated columns from the selection of record types,
+ /// define their `databaseSelection`:
///
/// ```swift
/// struct Player: Codable {
@@ -445,6 +448,9 @@ public final class ColumnDefinition {
///
/// extension Player: FetchableRecord, PersistableRecord {
/// static var databaseSelection: [any SQLSelectable] {
+ /// // Option 1
+ /// [Column("id"), Column("score"), Column("bonus")]
+ /// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
@@ -493,8 +499,8 @@ public final class ColumnDefinition {
/// }
/// ```
///
- /// When you want to ignore generated columns in record types, instruct
- /// GRDB not to select them:
+ /// To remove the generated columns from the selection of record types,
+ /// define their `databaseSelection`:
///
/// ```swift
/// struct Player: Codable {
@@ -506,6 +512,9 @@ public final class ColumnDefinition {
///
/// extension Player: FetchableRecord, PersistableRecord {
/// static var databaseSelection: [any SQLSelectable] {
+ /// // Option 1
+ /// [Column("id"), Column("score"), Column("bonus")]
+ /// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
@@ -556,8 +565,8 @@ public final class ColumnDefinition {
/// }
/// ```
///
- /// When you want to ignore generated columns in record types, instruct
- /// GRDB not to select them:
+ /// To remove the generated columns from the selection of record types,
+ /// define their `databaseSelection`:
///
/// ```swift
/// struct Player: Codable {
@@ -569,6 +578,9 @@ public final class ColumnDefinition {
///
/// extension Player: FetchableRecord, PersistableRecord {
/// static var databaseSelection: [any SQLSelectable] {
+ /// // Option 1
+ /// [Column("id"), Column("score"), Column("bonus")]
+ /// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
From 37ea21eb9671b3cb2298b4a6ad57fb3af3accda4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 19 Jan 2025 15:58:23 +0100
Subject: [PATCH 16/18] Test AllColumnsExcluding and Table
---
Tests/GRDBTests/TableTests.swift | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/Tests/GRDBTests/TableTests.swift b/Tests/GRDBTests/TableTests.swift
index 780fab6ee..a41b80b03 100644
--- a/Tests/GRDBTests/TableTests.swift
+++ b/Tests/GRDBTests/TableTests.swift
@@ -44,6 +44,12 @@ class TableTests: GRDBTestCase {
try assertEqualSQL(db, t.select([Column("id"), Column("name")]), """
SELECT "id", "name" FROM "player"
""")
+ try assertEqualSQL(db, t.select(.allColumns), """
+ SELECT * FROM "player"
+ """)
+ try assertEqualSQL(db, t.select(.allColumns(excluding: ["name"])), """
+ SELECT "id" FROM "player"
+ """)
try assertEqualSQL(db, t.select(sql: "id, ?", arguments: ["O'Brien"]), """
SELECT id, 'O''Brien' FROM "player"
""")
From 2c85bc2cfc33dad68500227f4a1d8c2c54ce6db2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 19 Jan 2025 16:57:34 +0100
Subject: [PATCH 17/18] CHANGELOG
---
CHANGELOG.md | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 641f49245..fa3cd565f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -131,6 +131,16 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
+## Next Release
+
+- **New**: Select all columns from a table, but a few ones by [@groue](https://github.com/groue) in [#1700](https://github.com/groue/GRDB.swift/pull/1700)
+- **Fixed**: Fix typo in Readme.md by [@kevinlg](https://github.com/kevinlg) in [#1697](https://github.com/groue/GRDB.swift/pull/1697)
+- **New**: Bump custom SQLite to 3.47.2 by [@groue](https://github.com/groue) in [#1696](https://github.com/groue/GRDB.swift/pull/1696)
+- **Fixed**: Update LICENSE, fix copyright license year by [@JasonnnW3000](https://github.com/JasonnnW3000) in [#1695](https://github.com/groue/GRDB.swift/pull/1695)
+- **Fixed**: Core: import `ucrt` on Windows for `strcmp` by [@compnerd](https://github.com/compnerd) in [#1662](https://github.com/groue/GRDB.swift/pull/1662)
+- **Fixed**: Foundation: elide extensions on Windows to match Linux by [@compnerd](https://github.com/compnerd) in [#1661](https://github.com/groue/GRDB.swift/pull/1661)
+- **Fixed**: Docs: fixes typos "FST"->"FTS" by [@nylki](https://github.com/nylki) in [#1660](https://github.com/groue/GRDB.swift/pull/1660)
+
## 7.0.0-beta.6
Released October 13, 2024
From 442b8b058937ae54c54c16b71ed83adecea3127c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 19 Jan 2025 17:30:17 +0100
Subject: [PATCH 18/18] 7.0.0-beta.7
---
CHANGELOG.md | 8 +++++---
Documentation/GRDB7MigrationGuide.md | 8 ++++----
GRDB.swift.podspec | 2 +-
README.md | 10 +++++-----
Support/Info.plist | 2 +-
5 files changed, 16 insertions(+), 14 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fa3cd565f..b0822a244 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,7 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
-- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.0.0-beta.3](#700-beta3) - [7.0.0-beta.4](#700-beta4) - [7.0.0-beta.5](#700-beta5) - [7.0.0-beta.6](#700-beta6)
+- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.0.0-beta.3](#700-beta3) - [7.0.0-beta.4](#700-beta4) - [7.0.0-beta.5](#700-beta5) - [7.0.0-beta.6](#700-beta6) - [7.0.0-beta.7](#700-beta7)
#### 6.x Releases
@@ -131,7 +131,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
-## Next Release
+## 7.0.0-beta.7
+
+Released January 19, 2025
- **New**: Select all columns from a table, but a few ones by [@groue](https://github.com/groue) in [#1700](https://github.com/groue/GRDB.swift/pull/1700)
- **Fixed**: Fix typo in Readme.md by [@kevinlg](https://github.com/kevinlg) in [#1697](https://github.com/groue/GRDB.swift/pull/1697)
@@ -182,7 +184,7 @@ Released September 29, 2024
[Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) describes in detail how to bump the GRDB version in your application.
-The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency.
+The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.7/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency.
The [demo app](Documentation/DemoApps/) was rewritten from scratch in a brand new Xcode 16 project.
diff --git a/Documentation/GRDB7MigrationGuide.md b/Documentation/GRDB7MigrationGuide.md
index 937354310..931d8279e 100644
--- a/Documentation/GRDB7MigrationGuide.md
+++ b/Documentation/GRDB7MigrationGuide.md
@@ -228,7 +228,7 @@ Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/grdb.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide
-[Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databasesharing
-[Transaction Kinds]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/transactions#Transaction-Kinds
-[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/swiftconcurrency
-[Record]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/record
+[Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.7/documentation/grdb/databasesharing
+[Transaction Kinds]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.7/documentation/grdb/transactions#Transaction-Kinds
+[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.7/documentation/grdb/swiftconcurrency
+[Record]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.7/documentation/grdb/record
diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec
index 5000d20c6..c5b39cba8 100644
--- a/GRDB.swift.podspec
+++ b/GRDB.swift.podspec
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
- s.version = '7.0.0-beta.6'
+ s.version = '7.0.0-beta.7'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
diff --git a/README.md b/README.md
index aacabce0a..ca93ddd56 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@
-**Latest release**: October 13, 2024 • [version 7.0.0-beta.6](https://github.com/groue/GRDB.swift/tree/v7.0.0-beta.6) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
+**Latest release**: January 19, 2025 • [version 7.0.0-beta.7](https://github.com/groue/GRDB.swift/tree/v7.0.0-beta.7) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ • SQLite 3.20.0+ • Swift 6+ / Xcode 16+
@@ -295,7 +295,7 @@ Documentation
#### Records and the Query Interface
- [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies
-- [Query Interface](#the-query-interface): A swift way to generate SQL • [create tables, indexes, etc](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databaseschema) • [requests](#requests) • [associations between record types](Documentation/AssociationsBasics.md)
+- [Query Interface](#the-query-interface): A swift way to generate SQL • [create tables, indexes, etc](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.7/documentation/grdb/databaseschema) • [requests](#requests) • [associations between record types](Documentation/AssociationsBasics.md)
#### Application Tools
@@ -441,7 +441,7 @@ Advanced topics:
- [Prepared Statements]
- [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates)
-- [Database Schema Introspection](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databaseschemaintrospection)
+- [Database Schema Introspection](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.7/documentation/grdb/databaseschemaintrospection)
- [Row Adapters](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter)
- [Raw SQLite Pointers](#raw-sqlite-pointers)
@@ -1643,7 +1643,7 @@ try dbQueue.write { db in
}
```
-Of course, you need to open a [database connection], and [create database tables](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databaseschema) first.
+Of course, you need to open a [database connection], and [create database tables](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.7/documentation/grdb/databaseschema) first.
To define a record type, define a type and extend it with protocols that come with focused sets of features.
@@ -3250,7 +3250,7 @@ So don't miss the [SQL API](#sqlite-api).
> **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output.
-- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databaseschema)
+- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.7/documentation/grdb/databaseschema)
- [Requests](#requests)
- [Expressions](#expressions)
- [SQL Operators](#sql-operators)
diff --git a/Support/Info.plist b/Support/Info.plist
index 77d0ffb68..876f81873 100644
--- a/Support/Info.plist
+++ b/Support/Info.plist
@@ -15,7 +15,7 @@
CFBundlePackageType
FMWK
CFBundleShortVersionString
- 7.0.0-beta.6
+ 7.0.0-beta.7
CFBundleSignature
????
CFBundleVersion