Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2025-01-19 18:20:47 +01:00
commit bbf39353b5
47 files changed
+1349 -256

No files matched your search

+1 -1
View File
@@ -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
+14 -2
View File
@@ -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,6 +131,18 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 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)
- **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
@@ -172,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.
+1 -1
View File
@@ -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).
+2 -2
View File
@@ -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.
+1 -1
View File
@@ -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).
+4 -4
View File
@@ -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
+2 -2
View File
@@ -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"))
+1 -1
View File
@@ -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.'
+2
View File
@@ -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
+1 -1
View File
@@ -1,4 +1,4 @@
#if !os(Linux)
#if !os(Linux) && !os(Windows)
import Foundation
private let integerRoundingBehavior = NSDecimalNumberHandler(
+1 -1
View File
@@ -1,6 +1,6 @@
import Foundation
#if !os(Linux)
#if !os(Linux) && !os(Windows)
/// NSURL stores its absoluteString in the database.
extension NSURL: DatabaseValueConvertible {
+1 -1
View File
@@ -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.
@@ -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
+63 -92
View File
@@ -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.
- <doc:SwiftConcurrency#Non-Sendable-Record-Types>
- <doc:SwiftConcurrency#Shorthand-Closure-Notation>
- <doc:SwiftConcurrency#Non-Sendable-Configuration-of-Record-Types>
- <doc:SwiftConcurrency#Non-Sendable-Record-Types>
- <doc:SwiftConcurrency#Choosing-between-Synchronous-and-Asynchronous-Database-Accesses>
### 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.
+7
View File
@@ -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 }
}
+8 -1
View File
@@ -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 }
}
+1 -1
View File
@@ -636,7 +636,7 @@ extension SQLRelation {
}
// <https://github.com/groue/GRDB.swift/issues/1357>
guard selection.allSatisfy(\.isTriviallyCountable) else {
if selection.contains(where: \.requiresTrivialCount) {
return try fetchTrivialCount(db)
}
+211 -45
View File
@@ -26,6 +26,12 @@ public struct SQLSelection: Sendable {
/// All columns, qualified: `player.*`
case qualifiedAllColumns(TableAlias)
/// All columns but the specified ones
case allColumnsExcluding(Set<CaseInsensitiveIdentifier>)
/// All columns but the specified ones, qualified.
case qualifiedAllColumnsExcluding(TableAlias, Set<CaseInsensitiveIdentifier>)
/// 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<CaseInsensitiveIdentifier>) -> 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<CaseInsensitiveIdentifier>) -> 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),
@@ -126,41 +166,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:
@@ -179,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)
@@ -228,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))
@@ -245,15 +280,27 @@ extension SQLSelection {
}
}
/// Returns whether this selection MUST be counted with a "trivial"
/// count: `SELECT COUNT(*) FROM (SELECT ...)`.
///
/// Supports SQLRelation.fetchCount.
///
/// See <https://github.com/groue/GRDB.swift/issues/1357>
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 .allColumnsExcluding, .qualifiedAllColumnsExcluding:
return false
case .expression:
return false
}
}
}
@@ -297,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")
@@ -319,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.
@@ -334,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: ["generatedColumn"])]
/// }
/// }
///
/// // SELECT id, name, score FROM player
/// Player.fetchAll(db)
/// ```
public struct AllColumnsExcluding: Sendable {
var excludedColumns: Set<CaseInsensitiveIdentifier>
public init(_ excludedColumns: some Collection<String>) {
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: ["generatedColumn"])]
/// }
/// }
///
/// // SELECT id, name, score FROM player
/// Player.fetchAll(db)
/// ```
public static func allColumns(excluding excludedColumns: some Collection<String>) -> 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("generatedColumn")])]
/// }
/// }
///
/// // SELECT id, name, score FROM player
/// Player.fetchAll(db)
/// ```
public static func allColumns(excluding excludedColumns: some Collection<any ColumnExpression>) -> Self {
AllColumnsExcluding(excludedColumns.map(\.name))
}
}
@@ -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<CaseInsensitiveIdentifier>
) 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)
}
}
}
@@ -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)
@@ -67,7 +67,12 @@ extension SQLInterpolation {
/// let player: Player = ...
/// let request: SQLRequest<Player> = "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<Player> = """
/// 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<Player> = """
/// SELECT \(AllColumns()) FROM player
/// SELECT \(.allColumns) FROM player
/// """
@_disfavoredOverload
public mutating func appendInterpolation(_ selection: (any SQLSelectable)?) {
@@ -370,6 +370,32 @@ public final class ColumnDefinition {
/// }
/// ```
///
/// To remove the generated columns from the selection of record types,
/// define their `databaseSelection`:
///
/// ```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] {
/// // Option 1
/// [Column("id"), Column("score"), Column("bonus")]
/// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
///
/// // SELECT id, score, bonus FROM player
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(db)
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
@@ -409,6 +435,32 @@ public final class ColumnDefinition {
/// }
/// ```
///
/// To remove the generated columns from the selection of record types,
/// define their `databaseSelection`:
///
/// ```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] {
/// // Option 1
/// [Column("id"), Column("score"), Column("bonus")]
/// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
///
/// // SELECT id, score, bonus FROM player
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(db)
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
@@ -447,6 +499,32 @@ public final class ColumnDefinition {
/// }
/// ```
///
/// To remove the generated columns from the selection of record types,
/// define their `databaseSelection`:
///
/// ```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] {
/// // Option 1
/// [Column("id"), Column("score"), Column("bonus")]
/// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
///
/// // SELECT id, score, bonus FROM player
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(db)
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
@@ -487,6 +565,32 @@ public final class ColumnDefinition {
/// }
/// ```
///
/// To remove the generated columns from the selection of record types,
/// define their `databaseSelection`:
///
/// ```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] {
/// // Option 1
/// [Column("id"), Column("score"), Column("bonus")]
/// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
///
/// // SELECT id, score, bonus FROM player
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(db)
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
@@ -249,12 +249,17 @@ final class DAO<Record: MutablePersistableRecord> {
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)
+1 -1
View File
@@ -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.
+14 -4
View File
@@ -134,8 +134,9 @@ public protocol TableRecord {
///
/// ```swift
/// struct Player: TableRecord {
/// // This is the default
/// static var databaseSelection: [any SQLSelectable] {
/// [AllColumns()]
/// [.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
@@ -168,7 +178,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 +225,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]
}
}
+1 -1
View File
@@ -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:
+34 -14
View File
@@ -15,7 +15,7 @@
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
</p>
**Latest release**: 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+ &bull; SQLite 3.20.0+ &bull; 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 &bull; [create tables, indexes, etc](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databaseschema) &bull; [requests](#requests) • [associations between record types](Documentation/AssociationsBasics.md)
- [Query Interface](#the-query-interface): A swift way to generate SQL &bull; [create tables, indexes, etc](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.7/documentation/grdb/databaseschema) &bull; [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,14 +1643,14 @@ 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.
For example:
```
struct Player: {
```swift
struct Player {
var id: Int64
var name: String
var score: Int
@@ -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)
@@ -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()
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>7.0.0-beta.6</string>
<string>7.0.0-beta.7</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -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()
@@ -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,14 +15,19 @@ 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(), Column.rowID] }
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
}
/// Test SQL generation
@@ -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"
@@ -76,8 +87,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" \
@@ -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" \
@@ -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
@@ -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,14 +15,19 @@ 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(), Column.rowID] }
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
}
/// Test SQL generation
@@ -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" \
@@ -76,8 +87,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" \
@@ -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" \
@@ -4,27 +4,34 @@ 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(), Column.rowID] }
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
}
/// Test SQL generation
@@ -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" \
@@ -87,8 +100,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" \
+4 -4
View File
@@ -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"))
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
@@ -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])
+350 -2
View File
@@ -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
@@ -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 {
+43 -5
View File
@@ -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)
}
}
}
@@ -640,7 +678,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 +692,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 +706,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 +720,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"])
@@ -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\")")
}
}
+20 -6
View File
@@ -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"])
}
}
}
@@ -479,7 +493,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 +525,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" \
+16 -1
View File
@@ -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
@@ -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:
+21 -5
View File
@@ -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"])
}
}
}
+6
View File
@@ -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"
""")