Compare commits

...
Author SHA1 Message Date
Gwendal Roué 63590ede60 Association limit WIP 2025-03-01 13:20:23 +01:00
Gwendal Roué 6eba24d169 Merge branch 'development' 2025-02-23 19:53:59 +01:00
Gwendal Roué bd3ac9ef75 v7.3.0 2025-02-23 18:44:22 +01:00
Gwendal Roué 392137c357 XCTestExpectation is Sendable starting Xcode 16.3 beta 2025-02-23 18:43:45 +01:00
Gwendal Roué b48a56ae03 Revert "Merge pull request #1732 from groue/dev/sending-closures"
This reverts commit bbd1eab402, reversing
changes made to 9b09c5342e.
2025-02-23 18:43:45 +01:00
Gwendal Roué bbd1eab402 Merge pull request #1732 from groue/dev/sending-closures
Async database accesses no longer require Sendable closures.
2025-02-23 15:33:54 +01:00
Gwendal Roué 53c9d12d29 Async database access no longer require Sendable closures. 2025-02-23 15:16:36 +01:00
Gwendal Roué 9b09c5342e Merge pull request #1731 from groue/dev/virtual-table-options
Support for temporary virtual tables
2025-02-23 13:59:48 +01:00
Gwendal Roué aed22fe0bc Support for temporary virtual tables. 2025-02-23 13:45:46 +01:00
Gwendal Roué eec220b652 Merge pull request #1730 from groue/dev/issue-1728
Undeprecate Date coding strategies based on DateFormatter
2025-02-23 11:13:02 +01:00
Gwendal Roué 79a782038e Undeprecate Date coding strategies based on DateFormatter
https://github.com/swiftlang/swift/issues/78635#issuecomment-2676324549
> DateFormatter is indeed thread safe and its conformance to Sendable is correct
2025-02-23 11:12:24 +01:00
Gwendal Roué 618e72d153 Merge pull request #1729 from groue/dev/issue-1728
Deprecate Date coding strategies based on DateFormatter
2025-02-22 14:29:08 +01:00
Gwendal Roué 824100990f Deprecate Date coding strategies based on DateFormatter
Fix #1728
2025-02-22 13:45:42 +01:00
Gwendal Roué c7205b172f Merge branch 'development' 2025-02-12 08:49:02 +01:00
Gwendal Roué 49d14e6b66 v7.2.0 2025-02-12 08:48:52 +01:00
Gwendal Roué 54ed7ec611 Merge pull request #1719 from groue/dev/selectID
Select ids with selectID()
2025-02-12 08:46:40 +01:00
Gwendal Roué 68e17351ff CI: iPhone 15 Pro simulator is no longer available 2025-02-12 08:31:34 +01:00
Gwendal Roué 494e697e94 Warn against selectID() when the ID type is an optional. 2025-02-12 08:25:27 +01:00
Gwendal Roué 87b236dfe0 selectID
This reverts 7ffc332327

At the time, selectID was replaced with selectPrimaryKey(as:) because:

> Since Optional is a database value like others, selectID would be a request of optionals for records with an optional ID type:
>
>     struct Player: Identifiable, MutablePersistableRecord {
>         var id: Int64?
>     }
>
>     Player.selectID() // QueryInterface<Int64?>
>
> This is not good, because primary keys are not null. And those requests would fetch impractical types such as [Int64?], Set<Int64?>, Int64??.

This problem is reintroduced, but we now recommend against optional ids in https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices. And record with optional ids can use selectPrimaryKey(as:).
2025-02-11 20:47:49 +01:00
Gwendal Roué ea6d8e0123 Merge branch 'development' 2025-02-05 15:34:18 +01:00
Gwendal Roué 073209f1dc v7.1.0 2025-02-05 15:34:09 +01:00
Gwendal Roué 430530f5f1 CHANGELOG 2025-02-05 14:08:28 +01:00
Gwendal Roué a716915280 Merge pull request #1717 from groue/dev/RxGRDB
Allow RxGRDB to compile without warning
2025-02-05 13:58:25 +01:00
Gwendal Roué ef36727d9a 🎵 Whatever Lola wants, Lola gets
Address https://github.com/RxSwiftCommunity/RxGRDB/issues/72

Based on https://github.com/swiftlang/swift-evolution/blob/main/proposals/0337-support-incremental-migration-to-concurrency-checking.md#preconcurrency-attribute-on-nominal-declarations

See also https://www.massicotte.org/preconcurrency#working-with-swift-5

"Whatever Lola wants, Lola gets" because the Swift language is a blind and cruel mistress.
2025-02-05 13:38:19 +01:00
Gwendal Roué 78b2796f46 CHANGELOG 2025-02-05 08:00:29 +01:00
Gwendal Roué 3535a42c53 Merge pull request #1716 from groue/dev/issue-1715
Fix: DatabaseQueue restores its read/write abilities when an async read-only database access is cancelled.
2025-02-04 20:51:58 +01:00
Gwendal Roué 5a4d9b5cb9 Let PRAGMA QUERY_ONLY statements run from a cancelled database access
Fix #1715
2025-02-04 19:35:39 +01:00
Gwendal Roué a64b09d121 Failing test for #1715 2025-02-04 19:35:39 +01:00
38 changed files with 1289 additions and 69 deletions

No files matched your search

+1 -1
View File
@@ -46,7 +46,7 @@ jobs:
name: "macOS"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
destination: "OS=18.1,name=iPhone 15 Pro"
destination: "OS=18.1,name=iPhone 16 Pro"
name: "iOS"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
+24
View File
@@ -7,6 +7,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
- `7.3.x` Releases - [7.3.0](#730)
- `7.2.x` Releases - [7.2.0](#720)
- `7.1.x` Releases - [7.1.0](#710)
- `7.0.x` Releases - [7.0.0](#700)
- `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)
@@ -132,6 +135,27 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 7.3.0
Released February 23, 2025
- **New**: Support for temporary virtual tables by [@groue](https://github.com/groue) in [#1731](https://github.com/groue/GRDB.swift/pull/1731)
- Fixed a compiler error in Xcode 16.3 beta ([#1729](https://github.com/groue/GRDB.swift/pull/1729), [#1730](https://github.com/groue/GRDB.swift/pull/1730))
## 7.2.0
Released February 12, 2025
- **New**: Select ids with selectID() by [@groue](https://github.com/groue) in [#1719](https://github.com/groue/GRDB.swift/pull/1719)
## 7.1.0
Released February 5, 2025
- **New**: Expose `sqlite3_libversion_number` as `Database.sqliteLibVersionNumber` by [@groue](https://github.com/groue) in [#1713](https://github.com/groue/GRDB.swift/pull/1713)
- **Fixed**: DatabaseQueue restores its read/write abilities when an async read-only database access is cancelled by [@groue](https://github.com/groue) in [#1716](https://github.com/groue/GRDB.swift/pull/1716)
- **New**: Allow RxGRDB to compile without warning by [@groue](https://github.com/groue) in [#1717](https://github.com/groue/GRDB.swift/pull/1717)
## 7.0.0
Released January 26, 2025
+2 -2
View File
@@ -91,7 +91,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
**FTS3 and FTS4 full-text tables store and index textual content.**
Create tables with the `create(virtualTable:using:)` method:
Create tables with the `create(virtualTable:options:using:_:)` method:
```swift
// CREATE VIRTUAL TABLE document USING fts3(content)
@@ -326,7 +326,7 @@ let documents = try Document.filter(Column("content").match(pattern)).fetchAll(d
To use FTS5, you'll need a [custom SQLite build] that activates the `SQLITE_ENABLE_FTS5` compilation option.
Create FTS5 tables with the `create(virtualTable:using:)` method:
Create FTS5 tables with the `create(virtualTable:options:using:_:)` method:
```swift
// CREATE VIRTUAL TABLE document USING fts5(content)
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '7.0.0'
s.version = '7.3.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+6
View File
@@ -1288,6 +1288,12 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
return
}
// Suspension should not prevent adjusting the read-only mode.
// See <https://github.com/groue/GRDB.swift/issues/1715>.
if statement.isQueryOnlyPragma {
return
}
// How should we interrupt the statement?
enum Interrupt {
case abort // Rollback and throw SQLITE_ABORT
@@ -83,6 +83,7 @@ extension DatabaseRegionObservation {
/// - parameter onChange: The closure to execute when a transaction has
/// modified the observed region.
/// - returns: A DatabaseCancellable that can stop the observation.
@preconcurrency // For RxGRDB, see <https://github.com/RxSwiftCommunity/RxGRDB/issues/72#issuecomment-2631125658>
public func start(
in writer: any DatabaseWriter,
onError: @escaping @Sendable (Error) -> Void,
+5
View File
@@ -172,6 +172,11 @@ public struct SQL: Sendable {
self.init(elements: [.expression(expression.sqlExpression)])
}
/// Creates an `SQL` literal from an SQL ordering term.
public init(_ ordering: some SQLOrderingTerm) {
self.init(elements: [.ordering(ordering.sqlOrdering)])
}
/// Returns true if this literal generates an empty SQL string
public var isEmpty: Bool {
elements.allSatisfy(\.isEmpty)
+4
View File
@@ -92,6 +92,9 @@ public final class Statement {
/// The effects on the database (reported by `sqlite3_set_authorizer`).
private(set) var authorizerEventKinds: [DatabaseEventKind] = []
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
private(set) var isQueryOnlyPragma = false
/// A boolean value indicating if the prepared statement makes no direct
/// changes to the content of the database file.
///
@@ -160,6 +163,7 @@ public final class Statement {
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
self.transactionEffect = authorizer.transactionEffect
self.authorizerEventKinds = authorizer.databaseEventKinds
self.isQueryOnlyPragma = authorizer.isQueryOnlyPragma
}
deinit {
+9
View File
@@ -41,6 +41,9 @@ final class StatementAuthorizer {
/// savepoint statement.
var transactionEffect: Statement.TransactionEffect?
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
var isQueryOnlyPragma = false
private var isDropStatement = false
init(_ database: Database) {
@@ -67,6 +70,7 @@ final class StatementAuthorizer {
databaseEventKinds = []
invalidatesDatabaseSchemaCache = false
transactionEffect = nil
isQueryOnlyPragma = false
isDropStatement = false
}
@@ -192,6 +196,11 @@ final class StatementAuthorizer {
}
return SQLITE_OK
case SQLITE_PRAGMA:
if let cString1 {
isQueryOnlyPragma = sqlite3_stricmp(cString1, "query_only") == 0
}
return SQLITE_OK
default:
return SQLITE_OK
}
@@ -252,8 +252,8 @@ Unique constraints and unique indexes are somewhat different: don't miss the tip
- ``Database/alter(table:body:)``
- ``Database/create(table:options:body:)``
- ``Database/create(virtualTable:ifNotExists:using:)``
- ``Database/create(virtualTable:ifNotExists:using:_:)``
- ``Database/create(virtualTable:options:using:)``
- ``Database/create(virtualTable:options:using:_:)``
- ``Database/drop(table:)``
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
@@ -265,6 +265,7 @@ Unique constraints and unique indexes are somewhat different: don't miss the tip
- ``TableDefinition``
- ``TableOptions``
- ``VirtualTableModule``
- ``VirtualTableOptions``
### Database Views
@@ -288,3 +289,5 @@ Those are legacy interfaces that are preserved for backwards compatibility. Thei
- ``Database/create(index:on:columns:unique:ifNotExists:condition:)``
- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)``
- ``Database/create(virtualTable:ifNotExists:using:)``
- ``Database/create(virtualTable:ifNotExists:using:_:)``
@@ -393,16 +393,16 @@ Extensions to the `DerivableRequest` protocol can not change the type of request
```swift
extension QueryInterfaceRequest<Author> {
// Selects author ids
func selectId() -> QueryInterfaceRequest<Int64> {
selectPrimaryKey(as: Int64.self)
// Selects authors' name
func selectName() -> QueryInterfaceRequest<String> {
select(Author.Columns.name)
}
}
// The ids of Japanese authors
let ids: Set<Int64> = try Author.all()
// The names of Japanese authors
let names: Set<String> = try Author.all()
.filter(countryCode: "JP")
.selectId()
.selectName()
.fetchSet(db)
```
+3 -3
View File
@@ -1,7 +1,7 @@
/// The virtual table module for the FTS3 full-text engine.
///
/// To create FTS3 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
/// ``Database/create(virtualTable:options:using:_:)``:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts3(content)
@@ -63,7 +63,7 @@ public struct FTS3 {
/// }
/// ```
///
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
/// See ``Database/create(virtualTable:options:using:_:)``
public init() { }
/// Returns an array of tokens found in the string argument.
@@ -143,7 +143,7 @@ extension FTS3: VirtualTableModule {
/// virtual table.
///
/// You don't create instances of this class. Instead, you use the `Database`
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
/// ``Database/create(virtualTable:options:using:_:)`` method:
///
/// ```swift
/// try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition
+2 -2
View File
@@ -106,13 +106,13 @@ public struct FTS3TokenizerDescriptor: Sendable {
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
arguments.append("separators=" + separators.sorted().map { String($0) }.joined())
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined())
}
return FTS3TokenizerDescriptor("unicode61", arguments: arguments)
+13 -3
View File
@@ -1,7 +1,7 @@
/// The virtual table module for the FTS4 full-text engine.
///
/// To create FTS4 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
/// ``Database/create(virtualTable:options:using:_:)``:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts4(content)
@@ -31,7 +31,7 @@ public struct FTS4 {
/// }
/// ```
///
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
/// See ``Database/create(virtualTable:options:using:_:)``
public init() { }
}
@@ -102,6 +102,16 @@ extension FTS4: VirtualTableModule {
case .synchronized(let contentTable):
// https://www.sqlite.org/fts3.html#_external_content_fts4_tables_
if definition.configuration.temporary {
// SQLite can't rebuild the index of temporary tables:
//
// sqlite> CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
// sqlite> CREATE VIRTUAL TABLE temp.ft USING fts4(content="t", b, c);
// sqlite> INSERT INTO ft(ft) VALUES('rebuild');
// Runtime error: SQL logic error
fatalError("Temporary external content FTS4 tables are not supported.")
}
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
let ftsTable = tableName.quotedDatabaseIdentifier
let content = contentTable.quotedDatabaseIdentifier
@@ -149,7 +159,7 @@ extension FTS4: VirtualTableModule {
/// virtual table.
///
/// You don't create instances of this class. Instead, you use the `Database`
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
/// ``Database/create(virtualTable:options:using:_:)`` method:
///
/// ```swift
/// try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition
+15 -5
View File
@@ -13,7 +13,7 @@ import Foundation
/// The virtual table module for the FTS5 full-text engine.
///
/// To create FTS5 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
/// ``Database/create(virtualTable:options:using:_:)``:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts5(content)
@@ -85,7 +85,7 @@ public struct FTS5 {
/// }
/// ```
///
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
/// See ``Database/create(virtualTable:options:using:_:)``
public init() { }
// Support for FTS5Pattern initializers. Don't make public. Users tokenize
@@ -143,7 +143,7 @@ extension FTS5: VirtualTableModule {
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
/// See Database.create(virtualTable:options:using:_:)
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS5TableDefinition {
FTS5TableDefinition(configuration: configuration)
}
@@ -219,7 +219,7 @@ extension FTS5: VirtualTableModule {
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
/// See Database.create(virtualTable:options:using:_:)
public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws {
switch definition.contentMode {
case .raw:
@@ -227,6 +227,16 @@ extension FTS5: VirtualTableModule {
case .synchronized(let contentTable):
// https://sqlite.org/fts5.html#external_content_tables
if definition.configuration.temporary {
// SQLite can't rebuild the index of temporary tables:
//
// sqlite> CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
// sqlite> CREATE VIRTUAL TABLE temp.ft USING fts5(content="t",content_rowid="a",b,c);
// sqlite> INSERT INTO ft(ft) VALUES('rebuild');
// Runtime error: SQL logic error
fatalError("Temporary external content FTS5 tables are not supported.")
}
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
let ftsTable = tableName.quotedDatabaseIdentifier
let content = contentTable.quotedDatabaseIdentifier
@@ -274,7 +284,7 @@ extension FTS5: VirtualTableModule {
/// virtual table.
///
/// You don't create instances of this class. Instead, you use the `Database`
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
/// ``Database/create(virtualTable:options:using:_:)`` method:
///
/// ```swift
/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
+4 -4
View File
@@ -112,14 +112,14 @@ public struct FTS5TokenizerDescriptor: Sendable {
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
components.append("separators")
components.append(separators.sorted().map { String($0) }.joined())
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
components.append("tokenchars")
components.append(tokenCharacters.sorted().map { String($0) }.joined())
}
@@ -197,14 +197,14 @@ public struct FTS5TokenizerDescriptor: Sendable {
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
components.append("separators")
components.append(separators.sorted().map { String($0) }.joined())
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
components.append("tokenchars")
components.append(tokenCharacters.sorted().map { String($0) }.joined())
}
@@ -281,6 +281,12 @@ extension Association {
relation.ctes[cte.tableName] = cte.cte
}
}
public func limit(_ limit: Int, offset: Int? = nil) -> Self {
withDestinationRelation { relation in
relation.limit = SQLLimit(limit: limit, offset: offset)
}
}
}
// MARK: - AssociationToOne
@@ -56,6 +56,7 @@
/// - ``select(_:as:)-3o8qw``
/// - ``select(literal:as:)``
/// - ``select(sql:arguments:as:)``
/// - ``selectID()``
/// - ``selectPrimaryKey(as:)``
///
/// ### Batch Delete
@@ -237,7 +238,7 @@ extension QueryInterfaceRequest: SelectionRequest {
select(sqlLiteral, as: type)
}
/// Selects the primary key.
/// Returns a request that selects the primary key.
///
/// All primary keys are supported:
///
@@ -281,6 +282,46 @@ extension QueryInterfaceRequest: SelectionRequest {
.asRequest(of: PrimaryKey.self)
}
/// Returns a request that selects the primary key.
///
/// For example:
///
/// ```swift
/// // SELECT id FROM player WHERE ...
/// let request = try Player.filter(...).selectID()
/// ```
///
/// **Important**: if the record type has an `ID` type that is an
/// optional, such as `Int64?`, it is recommended to prefer
/// ``selectPrimaryKey(as:)`` instead:
///
/// ```swift
/// struct Player: Identifiable {
/// var id: Int64?
/// }
///
/// // NOT RECOMMENDED: Set<Int64?>
/// let ids = try Player.filter(...)
/// .selectID()
/// .fetchSet(db)
///
/// // BETTER: Set<Int64>
/// let ids = try Player.filter(...)
/// .selectPrimaryKey(as: Int64.self)
/// .fetchSet(db)
/// ```
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable
{
selectWhenConnected { db in
let primaryKey = try db.primaryKey(self.databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"selectID requires a single-column primary key in the table \(self.databaseTableName)")
return [Column(primaryKey.columns[0])]
}.asRequest(of: RowDecoder.ID.self)
}
public func annotatedWhenConnected(
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
@@ -1477,7 +1518,7 @@ private func prefetch(
fatalError("Not implemented: prefetch association without any foreign key")
case let .foreignKey(pivotForeignKey):
let originTable = originRelation.source.tableName
let originTable = originRelation.source.associationOriginTable ?? originRelation.source.tableName
let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable)
let pivotColumns = pivotMapping.map(\.right)
let leftColumns = pivotMapping.map(\.left)
@@ -1610,7 +1651,7 @@ func makePrefetchRequest(
// Author.including(all: Author.books)
let pivotAlias = TableAlias()
let prefetchRelation = association
var prefetchRelation = association
.with {
$0.pivot.relation = $0.pivot.relation
.aliased(pivotAlias)
@@ -1619,7 +1660,52 @@ func makePrefetchRequest(
.destinationRelation()
.annotated(with: pivotColumns.map { pivotAlias[$0].forKey("grdb_\($0)") })
return QueryInterfaceRequest<Row>(relation: prefetchRelation)
if let limit = prefetchRelation.limit {
let baseName = "grdb_" + association.destination.key.name(singular: true)
let cteName = baseName + "_limited"
let rowNumberName = "rowNumber"
let ordering = prefetchRelation.ordering
let rowNumberFilter: SQLExpression
if let offset = limit.offset {
rowNumberFilter = ((offset + 1)..<(offset + 1 + limit.limit)).contains(Column(rowNumberName)).sqlExpression
} else {
rowNumberFilter = (Column(rowNumberName) <= limit.limit).sqlExpression
}
#warning("TODO: the order clause may refer to stuff inside the CTE.")
var limitedPrefetchRelation = prefetchRelation
// Annotate with the row number
.annotatedWhenConnected { db in
var sql: SQL = "ROW_NUMBER() OVER (PARTITION BY "
sql.append(literal: pivotColumns
.map { SQL(Column($0)) }
.joined(separator: ", "))
let orderings = try ordering.resolve(db)
if !orderings.isEmpty {
sql.append(sql: " ORDER BY ")
sql.append(literal: orderings
.map { SQL($0) }
.joined(separator: ", "))
}
sql.append(sql: ")")
return [sql.forKey(rowNumberName)]
}
// Limit is applied below, with the rowNumber filter
.unlimited()
// Turn into a CTE so that we can filter by rowNumber
.asCommonTableExpression(named: cteName)
// Reapply order
.orderWhenConnected { try ordering.resolve($0) }
// Turnt the limit into a rowNumber filter
.filter(rowNumberFilter)
return QueryInterfaceRequest<Row>(relation: limitedPrefetchRelation)
} else {
return QueryInterfaceRequest<Row>(relation: prefetchRelation)
}
}
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
+53
View File
@@ -282,6 +282,12 @@ extension SQLRelation: Refinable {
}
}
func unlimited() -> Self {
with {
$0.limit = nil
}
}
func withStableOrder() -> Self {
with { relation in
relation.ordering = relation.ordering.appending(Ordering(orderings: { [relation] db in
@@ -655,6 +661,47 @@ extension SQLRelation {
}
}
extension SQLRelation {
#warning("TODO: the order clause may refer to stuff inside the CTE.")
#warning("TODO: Try to leave the ordering inside the CTE")
func asCommonTableExpression(named tableName: String) -> Self {
with { relation in
GRDBPrecondition(ctes[tableName] == nil, """
Can't turn relation into a Common Table Expression because \
CTE '\(tableName)' is already defined. Please file a bug \
at https://github.com/groue/GRDB.swift/issues/new
""")
relation.ctes[tableName] = SQLCTE(
tableName: tableName,
columns: nil,
sqlSubquery: .relation(
self
.unorderedUnlessLimited() // only preserve ordering in the CTE if limited
.removingPrefetchedAssociations()),
isRecursive: false)
relation.source = SQLSource(
tableName: tableName,
associationOriginTable: relation.source.associationOriginTable ?? relation.source.tableName)
relation.selectionPromise = DatabasePromise { _ in [.allColumns] }
relation.filterPromise = nil
relation.isDistinct = false
relation.groupPromise = nil
relation.havingExpressionPromise = nil
relation.limit = nil
relation = relation.filteringChildren { child in
switch child.kind {
case .all, .bridge: true
case .oneOptional, .oneRequired: false
}
}
}
}
}
// MARK: - SQLLimit
struct SQLLimit {
@@ -673,9 +720,15 @@ struct SQLLimit {
// MARK: - SQLSource
struct SQLSource: Sendable {
/// The name of a database table to select from.
var tableName: String
var alias: TableAlias?
/// When not nil, use this table name instead of `tableName` when looking
/// for foreign keys on this source. This string is not nil when an
/// `SQLRelation` has been turned into a common table expression.
var associationOriginTable: String?
func aliased(_ alias: TableAlias) -> SQLSource {
if let sourceAlias = self.alias {
alias.becomeProxy(of: sourceAlias)
+35
View File
@@ -94,6 +94,7 @@
/// - ``select(literal:as:)``
/// - ``select(sql:arguments:)``
/// - ``select(sql:arguments:as:)``
/// - ``selectID()``
/// - ``selectPrimaryKey(as:)``
/// - ``with(_:)``
///
@@ -424,6 +425,40 @@ extension Table {
all().selectPrimaryKey(as: type)
}
/// Returns a request that selects the primary key.
///
/// For example:
///
/// ```swift
/// let table = Table<Player>("player")
///
/// // SELECT id FROM player
/// let request = try table.selectID()
/// ```
///
/// **Important**: if the record type has an `ID` type that is an
/// optional, such as `Int64?`, it is recommended to prefer
/// ``selectPrimaryKey(as:)`` instead:
///
/// ```swift
/// struct Player: Identifiable {
/// var id: Int64?
/// }
///
/// let table = Table<Player>("player")
///
/// // NOT RECOMMENDED: Set<Int64?>
/// let ids = try table.selectID().fetchSet(db)
///
/// // BETTER: Set<Int64>
/// let ids = try table.selectPrimaryKey(as: Int64.self).fetchSet(db)
/// ```
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable
{
all().selectID()
}
/// Returns a request with the provided result columns appended to the
/// table columns.
///
@@ -138,7 +138,7 @@ struct SQLQueryGenerator: Refinable {
let region = try prefetchedRegion(
db,
associations: prefetchedAssociations,
from: relation.source.tableName)
from: relation.source.associationOriginTable ?? relation.source.tableName)
statement.databaseRegion.formUnion(region)
}
@@ -741,9 +741,15 @@ private struct SQLQualifiedSource {
var tableName: String
var alias: TableAlias
/// When not nil, use this table name instead of `tableName` when looking
/// for foreign keys on this source. This string is not nil when an
/// `SQLRelation` has been turned into a common table expression.
var associationOriginTable: String?
init(_ source: SQLSource) {
self.tableName = source.tableName
self.alias = source.alias ?? TableAlias(tableName: source.tableName)
self.associationOriginTable = source.associationOriginTable
assert(alias.tableName == tableName)
}
@@ -1,7 +1,7 @@
/// The protocol for SQLite virtual table modules.
///
/// The protocol can define a DSL for the
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` `Database` method:
/// ``Database/create(virtualTable:options:using:_:)`` `Database` method:
///
/// ```swift
/// let module = ...
@@ -20,7 +20,7 @@
/// - ``VirtualTableConfiguration``
public protocol VirtualTableModule {
/// The type of the argument in the
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` closure.
/// ``Database/create(virtualTable:options:using:_:)`` closure.
///
/// For example:
///
@@ -35,7 +35,7 @@ public protocol VirtualTableModule {
var moduleName: String { get }
/// Returns a table definition that is passed as the argument in the
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` closure.
/// ``Database/create(virtualTable:options:using:_:)`` closure.
///
/// For example:
///
@@ -54,10 +54,29 @@ public protocol VirtualTableModule {
func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws
}
// TODO: Question the existence of this API. VirtualTableConfiguration was
// never able to be used by user-defined VirtualTableModule types, because
// `ifNotExists` has never been public.
public struct VirtualTableConfiguration {
/// If true, existing objects must not be replaced, or generate any error
/// (even if they do not match the objects that would be created otherwise.)
var ifNotExists: Bool
/// If true, new objects must be created in the temp schema.
var temporary: Bool
}
/// Virtual table creation options.
public struct VirtualTableOptions: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
/// Only creates the table if it does not already exist.
public static let ifNotExists = VirtualTableOptions(rawValue: 1 << 0)
/// Creates a temporary table.
public static let temporary = VirtualTableOptions(rawValue: 1 << 1)
}
extension Database {
@@ -77,18 +96,24 @@ extension Database {
///
/// - parameters:
/// - name: The table name.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - options: Table creation options.
/// - module: The name of an SQLite virtual table module.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws {
public func create(
virtualTable name: String,
options: VirtualTableOptions = [],
using module: String
) throws {
var chunks: [String] = []
chunks.append("CREATE VIRTUAL TABLE")
if ifNotExists {
if options.contains(.ifNotExists) {
chunks.append("IF NOT EXISTS")
}
chunks.append(name.quotedDatabaseIdentifier)
if options.contains(.temporary) {
chunks.append("temp.\(name.quotedDatabaseIdentifier)")
} else {
chunks.append(name.quotedDatabaseIdentifier)
}
chunks.append("USING")
chunks.append(module)
let sql = chunks.joined(separator: " ")
@@ -114,21 +139,21 @@ extension Database {
///
/// - parameters:
/// - tableName: The table name.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - options: Table creation options.
/// - module: a virtual module.
/// - body: An optional closure that defines the virtual table.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create<Module: VirtualTableModule>(
virtualTable tableName: String,
ifNotExists: Bool = false,
options: VirtualTableOptions = [],
using module: Module,
_ body: ((Module.TableDefinition) throws -> Void)? = nil)
throws
{
// Define virtual table
let configuration = VirtualTableConfiguration(ifNotExists: ifNotExists)
let configuration = VirtualTableConfiguration(
ifNotExists: options.contains(.ifNotExists),
temporary: options.contains(.temporary))
let definition = module.makeTableDefinition(configuration: configuration)
if let body {
try body(definition)
@@ -137,10 +162,14 @@ extension Database {
// Create virtual table
var chunks: [String] = []
chunks.append("CREATE VIRTUAL TABLE")
if ifNotExists {
if options.contains(.ifNotExists) {
chunks.append("IF NOT EXISTS")
}
chunks.append(tableName.quotedDatabaseIdentifier)
if options.contains(.temporary) {
chunks.append("temp.\(tableName.quotedDatabaseIdentifier)")
} else {
chunks.append(tableName.quotedDatabaseIdentifier)
}
chunks.append("USING")
let arguments = try module.moduleArguments(for: definition, in: self)
if arguments.isEmpty {
@@ -156,4 +185,78 @@ extension Database {
return .commit
}
}
/// Creates a virtual database table.
///
/// For example:
///
/// ```swift
/// // CREATE VIRTUAL TABLE vocabulary USING spellfix1
/// try db.create(virtualTable: "vocabulary", using: "spellfix1")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html>
///
/// - warning: This is a legacy interface that is preserved for backwards
/// compatibility. Use of this interface is not recommended: prefer
/// ``create(virtualTable:options:using:)`` instead.
///
/// - parameters:
/// - name: The table name.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - module: The name of an SQLite virtual table module.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@_disfavoredOverload
public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws {
try create(
virtualTable: name,
options: ifNotExists ? .ifNotExists : [],
using: module)
}
/// Creates a virtual database table.
///
/// The type of the argument of the `body` function depends on the type of
/// the `module` argument: refer to this module's documentation.
///
/// You can use this method to create full-text virtual tables:
///
/// ```swift
/// try db.create(virtualTable: "book", using: FTS4()) { t in
/// t.column("title")
/// t.column("author")
/// t.column("body")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html>
///
/// - warning: This is a legacy interface that is preserved for backwards
/// compatibility. Use of this interface is not recommended: prefer
/// ``create(virtualTable:options:using:_:)`` instead.
///
/// - parameters:
/// - tableName: The table name.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - module: a virtual module.
/// - body: An optional closure that defines the virtual table.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@_disfavoredOverload
public func create<Module: VirtualTableModule>(
virtualTable tableName: String,
ifNotExists: Bool = false,
using module: Module,
_ body: ((Module.TableDefinition) throws -> Void)? = nil)
throws
{
try create(
virtualTable: tableName,
options: ifNotExists ? .ifNotExists : [],
using: module,
body)
}
}
@@ -251,6 +251,36 @@ extension TableRecord {
all().selectPrimaryKey(as: type)
}
/// Returns a request that selects the primary key.
///
/// For example:
///
/// ```swift
/// // SELECT id FROM player
/// let request = try Player.selectID()
/// ```
///
/// **Important**: if the record type has an `ID` type that is an
/// optional, such as `Int64?`, it is recommended to prefer
/// ``selectPrimaryKey(as:)`` instead:
///
/// ```swift
/// struct Player: Identifiable {
/// var id: Int64?
/// }
///
/// // NOT RECOMMENDED: Set<Int64?>
/// let ids = try Player.selectID().fetchSet(db)
///
/// // BETTER: Set<Int64>
/// let ids = try Player.selectPrimaryKey(as: Int64.self).fetchSet(db)
/// ```
public static func selectID() -> QueryInterfaceRequest<Self.ID>
where Self: Identifiable
{
all().selectID()
}
/// Returns a request with the provided result columns appended to the
/// record selection.
///
+6 -1
View File
@@ -524,7 +524,12 @@ public enum DatabaseDataEncodingStrategy: Sendable {
/// var creationDate: Date
/// }
/// ```
public enum DatabaseDateEncodingStrategy: Sendable {
public enum DatabaseDateEncodingStrategy: @unchecked Sendable {
// @unchecked Sendable because of `DateFormatter`, which lost its
// `Sendable` conformance with Xcode 16.3 beta. See
// <https://github.com/swiftlang/swift/issues/78635>.
// TODO: remove @unchecked when the compiler issue is fixed.
/// The strategy that uses formatting from the Date structure.
///
/// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the
+6 -1
View File
@@ -929,7 +929,12 @@ public enum DatabaseDataDecodingStrategy: Sendable {
/// var name: String
/// var registrationDate: Date // decoded from epoch timestamp
/// }
public enum DatabaseDateDecodingStrategy: Sendable {
public enum DatabaseDateDecodingStrategy: @unchecked Sendable {
// @unchecked Sendable because of `DateFormatter`, which lost its
// `Sendable` conformance with Xcode 16.3 beta. See
// <https://github.com/swiftlang/swift/issues/78635>.
// TODO: remove @unchecked when the compiler issue is fixed.
/// The strategy that uses formatting from the Date structure.
///
/// It decodes numeric values as a number of seconds since Epoch
+1
View File
@@ -98,6 +98,7 @@ import Foundation
/// - ``select(literal:as:)``
/// - ``select(sql:arguments:)``
/// - ``select(sql:arguments:as:)``
/// - ``selectID()``
/// - ``selectPrimaryKey(as:)``
/// - ``with(_:)``
///
+11 -1
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**: January 26, 2025 • [version 7.0.0](https://github.com/groue/GRDB.swift/tree/v7.0.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Latest release**: February 23, 2025 • [version 7.3.0](https://github.com/groue/GRDB.swift/tree/v7.3.0) • [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+
@@ -3341,6 +3341,16 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Player.select(nameColumn, as: String.self)
```
- [`selectID()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest/selectID()) is available on [Identifiable Records]. It supports all tables that have a single-column primary key:
```swift
// SELECT id FROM player
Player.selectID()
// SELECT id FROM player WHERE name IS NOT NULL
Player.filter(nameColumn != nil).selectID()
```
- [`annotated(with: expression...)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/selectionrequest/annotated(with:)-6ehs4) extends the selection.
```swift
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>7.0.0</string>
<string>7.3.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -157,6 +157,110 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testIncludingAllHasMany_limit() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(B.self)
.orderByPrimaryKey()
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
WITH "grdb_bs_limited" AS (\
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
FROM "b" \
WHERE "colb2" IN (1, 2, 3)\
) \
SELECT * FROM "grdb_bs_limited" \
WHERE "rowNumber" <= 3 \
ORDER BY "colb1"
"""])
}
// Request with avoided prefetch
do {
let request = A
.none()
.including(all: A
.hasMany(B.self)
.orderByPrimaryKey()
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM \"a\" WHERE 0 ORDER BY \"cola1\"
"""])
}
// Request with filters
do {
let request = A
.filter(Column("cola1") != 3)
.including(all: A
.hasMany(B.self)
.filter(Column("colb1") == 4)
.orderByPrimaryKey()
.forKey("bs1")
.limit(3))
.including(all: A
.hasMany(B.self)
.filter(Column("colb1") != 4)
.orderByPrimaryKey()
.forKey("bs2")
.limit(5, offset: 2))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" \
WHERE "cola1" <> 3 \
ORDER BY "cola1"
""",
"""
WITH "grdb_bs1_limited" AS (\
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
FROM "b" \
WHERE ("colb1" = 4) AND ("colb2" IN (1, 2))\
) \
SELECT * FROM "grdb_bs1_limited" \
WHERE "rowNumber" <= 3 \
ORDER BY "colb1"
""",
"""
WITH "grdb_bs2_limited" AS (\
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
FROM "b" \
WHERE ("colb1" <> 4) AND ("colb2" IN (1, 2))\
) \
SELECT * FROM "grdb_bs2_limited" \
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8) \
ORDER BY "colb1"
"""])
}
}
}
func testIncludingAllHasManyScalar() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
@@ -188,6 +292,42 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testIncludingAllHasManyScalar_limit() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(B.self)
.select(Column("colb2"))
.distinct()
.order(Column("colb2"))
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
WITH "grdb_bs_limited" AS (\
SELECT DISTINCT "colb2", "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb2") AS "rowNumber" \
FROM "b" \
WHERE "colb2" IN (1, 2, 3)\
) \
SELECT * FROM "grdb_bs_limited" \
WHERE "rowNumber" <= 3 \
ORDER BY "colb2"
"""])
}
}
}
func testIncludingAllHasManyWithCompoundForeignKey() throws {
// We can use the CTE technique
let dbQueue = try makeDatabaseQueue()
@@ -304,6 +444,141 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testIncludingAllHasManyWithCompoundForeignKey_limit() throws {
// We can use the CTE technique
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "parent") { t in
t.column("parentA", .text)
t.column("parentB", .text)
t.primaryKey(["parentA", "parentB"])
}
try db.create(table: "child") { t in
t.column("pA", .text)
t.column("pB", .text)
t.column("name", .text)
t.foreignKey(["pA", "pB"], references: "parent")
}
try db.execute(sql: """
INSERT INTO parent (parentA, parentB) VALUES ('foo', 'bar');
INSERT INTO parent (parentA, parentB) VALUES ('baz', 'qux');
INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar1');
INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar2');
INSERT INTO child (pA, pB, name) VALUES ('baz', 'qux', 'bazqux1');
""")
struct Parent: TableRecord { }
struct Child: TableRecord { }
// Plain request
do {
let request = Parent
.including(all: Parent
.hasMany(Child.self)
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "parent" ORDER BY "parentA", "parentB"
""",
"""
WITH "grdb_children_limited" AS (\
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
FROM "child" \
WHERE ("pA", "pB") IN "grdb_base"\
), \
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \
SELECT * \
FROM "grdb_children_limited" \
WHERE "rowNumber" <= 3
"""])
}
// Request with avoided prefetch
do {
let request = Parent
.none()
.including(all: Parent
.hasMany(Child.self)
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "parent" WHERE 0 ORDER BY "parentA", "parentB"
"""])
}
// Request with filters
do {
let request = Parent
.including(all: Parent
.hasMany(Child.self)
.filter(Column("name") == "foo")
.limit(3))
.filter(Column("parentA") == "foo")
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "parent" WHERE "parentA" = 'foo' ORDER BY "parentA", "parentB"
""",
"""
WITH "grdb_children_limited" AS (\
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
FROM "child" \
WHERE ("name" = 'foo') AND (("pA", "pB") IN "grdb_base")\
), \
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "parentA" = 'foo') \
SELECT * \
FROM "grdb_children_limited" \
WHERE "rowNumber" <= 3
"""])
}
// Limited ordered request (preserve both ordering and limit in the CTE)
do {
let request = Parent
.including(all: Parent
.hasMany(Child.self)
.limit(5, offset: 2))
.orderByPrimaryKey()
.limit(1)
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "parent" ORDER BY "parentA", "parentB" LIMIT 1
""",
"""
WITH "grdb_children_limited" AS (\
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
FROM "child" WHERE ("pA", "pB") IN "grdb_base"\
), \
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" ORDER BY "parentA", "parentB" LIMIT 1) \
SELECT * FROM "grdb_children_limited" \
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8)
"""])
}
}
}
func testIncludingAllHasManyIncludingAllHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
@@ -455,6 +730,218 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testIncludingAllHasManyIncludingAllHasMany_limit() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(C.self)
.including(all: C
.hasMany(D.self)
.orderByPrimaryKey()
.limit(5, offset: 2))
.orderByPrimaryKey()
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
WITH "grdb_cs_limited" AS (\
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" ORDER BY "colc1") AS "rowNumber" \
FROM "c" \
WHERE "colc2" IN (1, 2, 3)\
) \
SELECT * \
FROM "grdb_cs_limited" \
WHERE "rowNumber" <= 3 \
ORDER BY "colc1"
""",
"""
WITH "grdb_ds_limited" AS (\
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" ORDER BY "cold1") AS "rowNumber" \
FROM "d" \
WHERE "cold2" IN (7, 8, 9)\
) \
SELECT * \
FROM "grdb_ds_limited" \
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8) \
ORDER BY "cold1"
"""])
}
// Request with avoided second-level prefetch
do {
let request = A
.including(all: A
.hasMany(C.self)
.none()
.including(all: C
.hasMany(D.self)
.orderByPrimaryKey()
.limit(5, offset: 2))
.orderByPrimaryKey()
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
WITH "grdb_cs_limited" AS (\
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" ORDER BY "colc1") AS "rowNumber" \
FROM "c" \
WHERE 0 AND ("colc2" IN (1, 2, 3))\
) \
SELECT * \
FROM "grdb_cs_limited" \
WHERE "rowNumber" <= 3 \
ORDER BY "colc1"
"""])
}
// Request with filters
do {
let request = A
.filter(Column("cola1") != 3)
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") > 7)
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.limit(1)
.forKey("ds1"))
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.limit(2)
.forKey("ds2"))
.orderByPrimaryKey()
.limit(3)
.forKey("cs1"))
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") < 9)
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.limit(3)
.forKey("ds1"))
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.limit(4)
.forKey("ds2"))
.orderByPrimaryKey()
.limit(5)
.forKey("cs2"))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * \
FROM "a" \
WHERE "cola1" <> 3 \
ORDER BY "cola1"
""",
"""
WITH "grdb_cs1_limited" AS (\
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" \
ORDER BY "colc1") AS "rowNumber" \
FROM "c" \
WHERE ("colc1" > 7) AND ("colc2" IN (1, 2))\
) \
SELECT * \
FROM "grdb_cs1_limited" \
WHERE "rowNumber" <= 3 \
ORDER BY "colc1"
""",
"""
WITH "grdb_ds1_limited" AS (\
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
ORDER BY "cold1") AS "rowNumber" \
FROM "d" \
WHERE ("cold1" = 11) AND ("cold2" IN (8, 9))\
) \
SELECT * \
FROM "grdb_ds1_limited" \
WHERE "rowNumber" <= 1 \
ORDER BY "cold1"
""",
"""
WITH "grdb_ds2_limited" AS (\
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
ORDER BY "cold1") AS "rowNumber" \
FROM "d" \
WHERE ("cold1" <> 11) AND ("cold2" IN (8, 9))\
) \
SELECT * \
FROM "grdb_ds2_limited" \
WHERE "rowNumber" <= 2 \
ORDER BY "cold1"
""",
"""
WITH "grdb_cs2_limited" AS (\
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" \
ORDER BY "colc1") AS "rowNumber" \
FROM "c" \
WHERE ("colc1" < 9) AND ("colc2" IN (1, 2))\
) \
SELECT * \
FROM "grdb_cs2_limited" \
WHERE "rowNumber" <= 5 \
ORDER BY "colc1"
""",
"""
WITH "grdb_ds1_limited" AS (\
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
ORDER BY "cold1") AS "rowNumber" \
FROM "d" \
WHERE ("cold1" = 11) AND ("cold2" IN (7, 8))\
) \
SELECT * \
FROM "grdb_ds1_limited" \
WHERE "rowNumber" <= 3 \
ORDER BY "cold1"
""",
"""
WITH "grdb_ds2_limited" AS (\
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
ORDER BY "cold1") AS "rowNumber" \
FROM "d" \
WHERE ("cold1" <> 11) AND ("cold2" IN (7, 8))\
) \
SELECT * \
FROM "grdb_ds2_limited" \
WHERE "rowNumber" <= 4 \
ORDER BY "cold1"
""",
])}
}
}
func testIncludingAllHasManyIncludingAllHasManyWithCompoundForeignKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
@@ -730,6 +1217,138 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testIncludingAllHasManyIncludingRequiredOrOptionalHasMany_limit() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(C.self)
.including(required: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey()
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
#warning("TODO: ordering on D is lost")
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d".* \
FROM "c" \
JOIN "d" ON "d"."cold2" = "c"."colc1" \
WHERE "c"."colc2" IN (1, 2, 3) \
ORDER BY "c"."colc1", "d"."cold1"
"""])
}
// Request with avoided prefetch
do {
let request = A
.including(all: A
.hasMany(C.self)
.none()
.including(required: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey()
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d".* \
FROM "c" \
JOIN "d" ON "d"."cold2" = "c"."colc1" \
WHERE 0 AND ("c"."colc2" IN (1, 2, 3)) \
ORDER BY "c"."colc1", "d"."cold1"
"""])
}
// Request with filters
do {
let request = A
.filter(Column("cola1") != 3)
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") > 7)
.including(optional: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d1"))
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.orderByPrimaryKey()
.limit(3)
.forKey("cs1"))
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") < 9)
.including(optional: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d1"))
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.orderByPrimaryKey()
.limit(3)
.forKey("cs2"))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * \
FROM "a" \
WHERE "cola1" <> 3 \
ORDER BY "cola1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d1".*, "d2".* \
FROM "c" \
LEFT JOIN "d" "d1" ON ("d1"."cold2" = "c"."colc1") AND ("d1"."cold1" = 11) \
JOIN "d" "d2" ON ("d2"."cold2" = "c"."colc1") AND ("d2"."cold1" <> 11) \
WHERE ("c"."colc1" > 7) AND ("c"."colc2" IN (1, 2)) \
ORDER BY "c"."colc1", "d1"."cold1", "d2"."cold1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d1".*, "d2".* \
FROM "c" \
LEFT JOIN "d" "d1" ON ("d1"."cold2" = "c"."colc1") AND ("d1"."cold1" = 11) \
JOIN "d" "d2" ON ("d2"."cold2" = "c"."colc1") AND ("d2"."cold1" <> 11) \
WHERE ("c"."colc1" < 9) AND ("c"."colc2" IN (1, 2)) \
ORDER BY "c"."colc1", "d1"."cold1", "d2"."cold1"
"""])
}
}
}
func testIncludingAllHasManyThroughHasManyUsingHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
+51
View File
@@ -415,6 +415,57 @@ class DatabaseWriterTests : GRDBTestCase {
// MARK: - Task Cancellation
// Regression test for <https://github.com/groue/GRDB.swift/issues/1715>.
func test_write_is_possible_after_read_cancelled_after_database_access() async throws {
// When a read access is cancelled, DatabaseQueue needs to execute
// `PRAGMA query_only=0` in order to restore the read/write access.
//
// Here we test that this pragma can run from a cancelled read.
//
// Small difficulty: some SQLite versions (seen with 3.43.2) execute
// the `query_only` pragma at compile time, not only at execution
// time (yeah, that's an SQLite bug). The problem of this bug is
// that even if the `PRAGMA query_only=0` is not executed due to
// Task cancellation, its side effect is still executed when it is
// compiled, unintentionally. A cancelled `PRAGMA query_only=0`
// still works!
//
// To avoid this SQLite bug from messing with our test, we perform
// two reads: one that compiles and cache `PRAGMA query_only`
// statements, and a second read that we cancel. This time the
// `PRAGMA query_only=0` triggers its side effect if and only if it
// is actually executed (the behavior we are testing).
func test(_ dbWriter: some DatabaseWriter) async throws {
let semaphore = AsyncSemaphore(value: 0)
let cancelledTaskMutex = Mutex<Task<Void, any Error>?>(nil)
let task = Task {
await semaphore.wait()
// First read, not cancelled, so that all `query_only`
// pragma statements are compiled (see above).
try await dbWriter.read { db in }
// Second read, cancelled.
try await dbWriter.read { db in
try XCTUnwrap(cancelledTaskMutex.load()).cancel()
}
}
cancelledTaskMutex.store(task)
semaphore.signal()
// Wait until reads are completed
try? await task.value
// Write access is restored after read cancellation (no error is thrown)
try await dbWriter.write { db in
try db.execute(sql: "CREATE TABLE test(a)")
}
}
try await test(makeDatabaseQueue())
try await test(makeDatabasePool())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
func test_writeWithoutTransaction_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws {
func test(_ dbWriter: some DatabaseWriter) async throws {
let semaphore = AsyncSemaphore(value: 0)
+23 -1
View File
@@ -13,7 +13,29 @@ class FTS3TableBuilderTests: GRDBTestCase {
}
}
func testOptions() throws {
func test_option_ifNotExists() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", options: .ifNotExists, using: FTS3())
assertDidExecute(sql: "CREATE VIRTUAL TABLE IF NOT EXISTS \"documents\" USING fts3")
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
}
}
func test_option_temporary() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", options: .temporary, using: FTS3())
assertDidExecute(sql: "CREATE VIRTUAL TABLE temp.\"documents\" USING fts3")
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
}
}
func testLegacyOptions() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", ifNotExists: true, using: FTS3())
+27 -5
View File
@@ -13,7 +13,29 @@ class FTS4TableBuilderTests: GRDBTestCase {
}
}
func testOptions() throws {
func test_option_ifNotExists() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", options: .ifNotExists, using: FTS4())
assertDidExecute(sql: "CREATE VIRTUAL TABLE IF NOT EXISTS \"documents\" USING fts4")
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
}
}
func test_option_temporary() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", options: .temporary, using: FTS4())
assertDidExecute(sql: "CREATE VIRTUAL TABLE temp.\"documents\" USING fts4")
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
}
}
func testLegacyOptions() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", ifNotExists: true, using: FTS4())
@@ -193,8 +215,8 @@ class FTS4TableBuilderTests: GRDBTestCase {
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["bar"])!, 1)
}
}
func testFTS4SynchronizationIfNotExists() throws {
func testFTS4Synchronization_with_ifNotExists_option() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.writeWithoutTransaction { db in
try db.create(table: "documents") { t in
@@ -202,7 +224,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
t.column("content", .text)
}
assertDidExecute(sql: "CREATE TABLE \"documents\" (\"id\" INTEGER PRIMARY KEY, \"content\" TEXT)")
try db.create(virtualTable: "ft_documents", ifNotExists: true, using: FTS4()) { t in
try db.create(virtualTable: "ft_documents", options: .ifNotExists, using: FTS4()) { t in
t.synchronize(withTable: "documents")
t.column("content")
}
@@ -210,7 +232,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
assertDidExecute(sql: "CREATE TRIGGER IF NOT EXISTS \"__ft_documents_bu\" BEFORE UPDATE ON \"documents\" BEGIN\n DELETE FROM \"ft_documents\" WHERE docid=old.\"id\";\nEND")
}
}
func testFTS4SynchronizationCleanup() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
+30 -4
View File
@@ -16,7 +16,33 @@ class FTS5TableBuilderTests: GRDBTestCase {
}
}
func testOptions() throws {
func test_option_ifNotExists() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", options: .ifNotExists, using: FTS5()) { t in
t.column("content")
}
assertDidExecute(sql: "CREATE VIRTUAL TABLE IF NOT EXISTS \"documents\" USING fts5(content)")
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
}
}
func test_option_temporary() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", options: .temporary, using: FTS5()) { t in
t.column("content")
}
assertDidExecute(sql: "CREATE VIRTUAL TABLE temp.\"documents\" USING fts5(content)")
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
}
}
func testLegacyOptions() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", ifNotExists: true, using: FTS5()) { t in
@@ -251,8 +277,8 @@ class FTS5TableBuilderTests: GRDBTestCase {
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["bar"])!, 1)
}
}
func testFTS5SynchronizationIfNotExists() throws {
func testFTS5Synchronization_with_ifNotExists_option() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.writeWithoutTransaction { db in
try db.create(table: "documents") { t in
@@ -260,7 +286,7 @@ class FTS5TableBuilderTests: GRDBTestCase {
t.column("content", .text)
}
assertDidExecute(sql: "CREATE TABLE \"documents\" (\"id\" INTEGER PRIMARY KEY, \"content\" TEXT)")
try db.create(virtualTable: "ft_documents", ifNotExists: true, using: FTS5()) { t in
try db.create(virtualTable: "ft_documents", options: .ifNotExists, using: FTS5()) { t in
t.synchronize(withTable: "documents")
t.column("content")
}
+3 -1
View File
@@ -269,5 +269,7 @@ struct AnyValueReducerFetcher<Fetched>: _ValueReducerFetcher {
}
}
// Assume this is correct :-/
#if compiler(<6.1)
// XCTestExpectation is Sendable starting Xcode 16.3 beta.
extension XCTestExpectation: @unchecked Sendable { }
#endif
@@ -800,6 +800,16 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase {
}
}
func test_static_selectID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalNonOptionalPrimaryKeySingle(id: "theUUID")
try record.insert(db)
let ids: [String] = try MinimalSingle.selectID().fetchAll(db)
XCTAssertEqual(ids, ["theUUID"])
}
}
func test_request_selectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -811,4 +821,14 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase {
XCTAssertEqual(rows, [["id": "theUUID"]])
}
}
func test_request_selectID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalNonOptionalPrimaryKeySingle(id: "theUUID")
try record.insert(db)
let ids: [String] = try MinimalSingle.all().selectID().fetchAll(db)
XCTAssertEqual(ids, ["theUUID"])
}
}
}
@@ -844,6 +844,16 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
func test_static_selectID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalRowID()
try record.insert(db)
let ids: [Int64?] = try MinimalRowID.selectID().fetchAll(db)
XCTAssertEqual(ids, [1])
}
}
func test_request_selectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -855,4 +865,14 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
XCTAssertEqual(rows, [["id": 1]])
}
}
func test_request_selectID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalRowID()
try record.insert(db)
let ids: [Int64?] = try MinimalRowID.all().selectID().fetchAll(db)
XCTAssertEqual(ids, [1])
}
}
}
@@ -375,7 +375,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'")
}
}
// MARK: - Fetch With Key Request
@@ -661,7 +661,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
_ = try MinimalSingle.find(db, key: id)
XCTFail("Expected RecordError")
} catch RecordError.recordNotFound(databaseTableName: "minimalSingles", key: ["UUID": .null]) { }
do {
let fetchedRecord = try MinimalSingle.find(db, key: record.UUID)
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
@@ -680,7 +680,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
}
// MARK: - Fetch With Primary Key Request
@@ -861,7 +861,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
// MARK: Select PrimaryKey
func test_static_selectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -875,6 +875,17 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
func test_static_selectID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
let ids: [String] = try MinimalSingle.selectID().fetchAll(db)
XCTAssertEqual(ids, ["theUUID"])
}
}
func test_request_selectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -887,4 +898,15 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
XCTAssertEqual(rows, [["UUID": "theUUID"]])
}
}
func test_request_selectID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
let ids: [String] = try MinimalSingle.all().selectID().fetchAll(db)
XCTAssertEqual(ids, ["theUUID"])
}
}
}
+4
View File
@@ -133,6 +133,8 @@ class TableTests: GRDBTestCase {
try assertEqualSQL(db, t.filter(ids: [1, 2, 3]), """
SELECT * FROM "player" WHERE "id" IN (1, 2, 3)
""")
try XCTAssertEqual(t.selectID().fetchOne(db), 1)
}
do {
@@ -148,6 +150,8 @@ class TableTests: GRDBTestCase {
try assertEqualSQL(db, t.filter(ids: [1, 2, 3]), """
SELECT * FROM "player" WHERE "id" IN (1, 2, 3)
""")
try XCTAssertEqual(t.selectID().fetchOne(db), 1)
}
}
}