Compare commits

..
19 changed files with 263 additions and 779 deletions

No files matched your search

+8
View File
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
- `7.4.x` Releases - [7.4.0](#740)
- `7.3.x` Releases - [7.3.0](#730)
- `7.2.x` Releases - [7.2.0](#720)
- `7.1.x` Releases - [7.1.0](#710)
@@ -135,6 +136,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 7.4.0
Released March 22, 2025
- **New**: Add the MIN and MAX multi-argument SQL functions to the query interface by [@groue](https://github.com/groue) in [#1745](https://github.com/groue/GRDB.swift/pull/1745)
- **Fixed**: Transaction observers are not impacted by Task Cancellation by [@groue](https://github.com/groue) in [#1747](https://github.com/groue/GRDB.swift/pull/1747). This fixes unexpected `ValueObservation` failures in applications that perform asynchronous writes.
## 7.3.0
Released February 23, 2025
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '7.3.0'
s.version = '7.4.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+3 -5
View File
@@ -494,11 +494,9 @@ extension Database {
switch ResultCode(rawValue: resultCode) {
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
if suspensionMutex.load().isCancelled {
// The only error that a user sees when a Task is cancelled
// is CancellationError.
throw CancellationError()
}
// The only error that a user sees when a Task is cancelled
// is CancellationError.
try suspensionMutex.load().checkCancellation()
default:
break
}
+33 -3
View File
@@ -341,10 +341,22 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// If true, the database access has been cancelled.
var isCancelled: Bool
/// If true, the database throws an error when it is cancelled.
var interruptsWhenCancelled: Bool
func checkCancellation() throws {
if isCancelled, interruptsWhenCancelled {
throw CancellationError()
}
}
}
/// Support for `checkForSuspensionViolation(from:)`
let suspensionMutex = Mutex(Suspension(isSuspended: false, isCancelled: false))
let suspensionMutex = Mutex(Suspension(
isSuspended: false,
isCancelled: false,
interruptsWhenCancelled: true))
// MARK: - Transaction Date
@@ -1222,7 +1234,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
suspension.isCancelled = true
return true
return suspension.interruptsWhenCancelled
}
if needsInterrupt {
@@ -1237,6 +1249,24 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// Within the given closure, Task cancellation does not interrupt
/// database accesses.
func ignoringCancellation<T>(_ value: () throws -> T) rethrows -> T {
let previous = suspensionMutex.withLock {
let previous = $0.interruptsWhenCancelled
$0.interruptsWhenCancelled = false
return previous
}
defer {
suspensionMutex.withLock {
$0.interruptsWhenCancelled = previous
}
}
return try value()
}
/// Support for `checkForSuspensionViolation(from:)`
private func journalMode() throws -> String {
if let journalMode = journalModeCache {
@@ -1303,7 +1333,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
let interrupt: Interrupt? = try suspensionMutex.withLock { suspension in
// Check for cancellation first, so that the only error that
// a user sees when a Task is cancelled is CancellationError.
if suspension.isCancelled {
if suspension.isCancelled, suspension.interruptsWhenCancelled {
return .cancel
}
-5
View File
@@ -172,11 +172,6 @@ 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)
+14 -4
View File
@@ -549,8 +549,12 @@ class DatabaseObservationBroker {
savepointStack.clear()
if !database.isReadOnly {
for observation in transactionObservations {
observation.databaseDidCommit(database)
// Observers must be able to access the database, even if the
// task that has performed the commit is cancelled.
database.ignoringCancellation {
for observation in transactionObservations {
observation.databaseDidCommit(database)
}
}
}
@@ -609,12 +613,18 @@ class DatabaseObservationBroker {
// Called from statementDidExecute or statementDidFail
private func databaseDidRollback(notifyTransactionObservers: Bool) {
#warning("TODO")
savepointStack.clear()
if notifyTransactionObservers {
assert(!database.isReadOnly, "Read-only transactions are not notified")
for observation in transactionObservations {
observation.databaseDidRollback(database)
// Observers must be able to access the database, even if the
// task that has performed the commit is cancelled.
database.ignoringCancellation {
for observation in transactionObservations {
observation.databaseDidRollback(database)
}
}
}
databaseDidEndTransaction()
+47 -7
View File
@@ -94,6 +94,26 @@ migrator.registerMigration("Create authors") { db in
}
```
#### How to Rename a Foreign Key
When a migration **renames a foreign key**, make sure the migration runs with `.immediate` foreign key checks, in order to avoid database integrity problems:
```swift
// IMPORTANT: rename foreign keys with immediate foreign key checks.
migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in
try db.rename(table: "team", to: "guild")
try db.alter(table: "player") { t in
// Rename a foreign key
t.rename(column: "teamId", to: "guildId")
}
}
```
Note: migrations that run with `.immediate` foreign key checks can not be used to recreated database tables, as described below. When needed, define two migrations instead of one.
#### How to Recreate a Database Table
When you need to modify a table in a way that is not directly supported by SQLite, or not available on your target operating system, you will need to recreate the database table.
For example:
@@ -113,19 +133,39 @@ migrator.registerMigration("Add NOT NULL check on author.name") { db in
The detailed sequence of operations for recreating a database table from a migration is:
1. When relevant, remember the format of all indexes, triggers, and views associated with table X. This information will be needed in steps 6 and 7 below. One way to do this is to run a query like the following: `SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'`.
1. When relevant, remember the format of all indexes, triggers, and views associated with table `X`. This information will be needed in steps 6 below. One way to do this is to run the following statement and examine the output in the console:
2. Use `CREATE TABLE` to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course.
```swift
try db.dumpSQL("SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'")
```
3. Transfer content from X into new_X using a statement like: `INSERT INTO new_X SELECT ... FROM X`.
2. Construct a new table `new_X` that is in the desired revised format of table `X`. Make sure that the name `new_X` does not collide with any existing table name, of course.
4. Drop the old table X: `DROP TABLE X`.
```swift
try db.create(table: "new_X") { t in ... }
```
5. Change the name of new_X to X using: `ALTER TABLE new_X RENAME TO X`.
3. Transfer content from `X` into `new_X` using a statement like:
6. When relevant, use `CREATE INDEX`, `CREATE TRIGGER`, and `CREATE VIEW` to reconstruct indexes, triggers, and views associated with table X. Perhaps use the old format of the triggers, indexes, and views saved from step 3 above as a guide, making changes as appropriate for the alteration.
```swift
try db.execute(sql: "INSERT INTO new_X SELECT ... FROM X")
```
7. If any views refer to table X in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
4. Drop the old table `X`:
```swift
try db.drop(table: "X")
```
5. Change the name of `new_X` to `X` using:
```swift
try db.rename(table: "new_X", to: "X")
```
6. When relevant, reconstruct indexes, triggers, and views associated with table `X`.
7. If any views refer to table `X` in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
> Important: When recreating a table, be sure to follow the above procedure exactly, in the given order, or you might corrupt triggers, views, and foreign key constraints.
>
@@ -281,12 +281,6 @@ 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
@@ -1518,7 +1518,7 @@ private func prefetch(
fatalError("Not implemented: prefetch association without any foreign key")
case let .foreignKey(pivotForeignKey):
let originTable = originRelation.source.associationOriginTable ?? originRelation.source.tableName
let originTable = originRelation.source.tableName
let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable)
let pivotColumns = pivotMapping.map(\.right)
let leftColumns = pivotMapping.map(\.left)
@@ -1651,7 +1651,7 @@ func makePrefetchRequest(
// Author.including(all: Author.books)
let pivotAlias = TableAlias()
var prefetchRelation = association
let prefetchRelation = association
.with {
$0.pivot.relation = $0.pivot.relation
.aliased(pivotAlias)
@@ -1660,52 +1660,7 @@ func makePrefetchRequest(
.destinationRelation()
.annotated(with: pivotColumns.map { pivotAlias[$0].forKey("grdb_\($0)") })
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)
}
return QueryInterfaceRequest<Row>(relation: prefetchRelation)
}
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
@@ -2209,8 +2209,10 @@ extension SQLExpressible where Self == Column {
/// - ``localizedLowercased``
/// - ``localizedUppercased``
/// - ``lowercased``
/// - ``min(_:_:_:)``
/// - ``min(_:)``
/// - ``min(_:filter:)``
/// - ``max(_:_:_:)``
/// - ``max(_:)``
/// - ``max(_:filter:)``
/// - ``sum(_:)``
+47 -15
View File
@@ -11,7 +11,7 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `AVG` SQL function.
/// The `AVG` SQL aggregate function.
///
/// For example:
///
@@ -26,7 +26,7 @@ public func average(
.aggregateFunction("AVG", [value.sqlExpression], filter: filter?.sqlExpression)
}
#else
/// The `AVG` SQL function.
/// The `AVG` SQL aggregate function.
///
/// For example:
///
@@ -44,7 +44,7 @@ public func average(
filter: filter.sqlExpression)
}
/// The `AVG` SQL function.
/// The `AVG` SQL aggregate function.
///
/// For example:
///
@@ -147,8 +147,24 @@ public func length(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("LENGTH", [value.sqlExpression])
}
/// The `MAX` SQL multi-argument function.
///
/// For example:
///
/// ```swift
/// // MAX(score, 1000)
/// max(Column("score"), 1000)
/// ```
public func max(
_ value1: any SQLSpecificExpressible,
_ value2: any SQLExpressible,
_ values: any SQLExpressible...
) -> SQLExpression {
.simpleFunction("MAX", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `MAX` SQL function.
/// The `MAX` SQL aggregate function.
///
/// For example:
///
@@ -163,7 +179,7 @@ public func max(
.aggregateFunction("MAX", [value.sqlExpression], filter: filter?.sqlExpression)
}
#else
/// The `MAX` SQL function.
/// The `MAX` SQL aggregate function.
///
/// For example:
///
@@ -179,7 +195,7 @@ public func max(
.aggregateFunction("MAX", [value.sqlExpression], filter: filter.sqlExpression)
}
/// The `MAX` SQL function.
/// The `MAX` SQL aggregate function.
///
/// For example:
///
@@ -192,8 +208,24 @@ public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
}
#endif
/// The `MIN` SQL multi-argument function.
///
/// For example:
///
/// ```swift
/// // MIN(score, 1000)
/// min(Column("score"), 1000)
/// ```
public func min(
_ value1: any SQLSpecificExpressible,
_ value2: any SQLExpressible,
_ values: any SQLExpressible...
) -> SQLExpression {
.simpleFunction("MIN", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `MIN` SQL function.
/// The `MIN` SQL aggregate function.
///
/// For example:
///
@@ -208,7 +240,7 @@ public func min(
.aggregateFunction("MIN", [value.sqlExpression], filter: filter?.sqlExpression)
}
#else
/// The `MIN` SQL function.
/// The `MIN` SQL aggregate function.
///
/// For example:
///
@@ -224,7 +256,7 @@ public func min(
.aggregateFunction("MIN", [value.sqlExpression], filter: filter.sqlExpression)
}
/// The `MIN` SQL function.
/// The `MIN` SQL aggregate function.
///
/// For example:
///
@@ -238,7 +270,7 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
#endif
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `SUM` SQL function.
/// The `SUM` SQL aggregate function.
///
/// For example:
///
@@ -262,7 +294,7 @@ public func sum(
filter: filter?.sqlExpression)
}
#else
/// The `SUM` SQL function.
/// The `SUM` SQL aggregate function.
///
/// For example:
///
@@ -284,7 +316,7 @@ public func sum(
filter: filter.sqlExpression)
}
/// The `SUM` SQL function.
/// The `SUM` SQL aggregate function.
///
/// For example:
///
@@ -302,7 +334,7 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
#endif
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `TOTAL` SQL function.
/// The `TOTAL` SQL aggregate function.
///
/// For example:
///
@@ -326,7 +358,7 @@ public func total(
filter: filter?.sqlExpression)
}
#else
/// The `TOTAL` SQL function.
/// The `TOTAL` SQL aggregate function.
///
/// For example:
///
@@ -348,7 +380,7 @@ public func total(
filter: filter.sqlExpression)
}
/// The `TOTAL` SQL function.
/// The `TOTAL` SQL aggregate function.
///
/// For example:
///
-53
View File
@@ -282,12 +282,6 @@ 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
@@ -661,47 +655,6 @@ 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 {
@@ -720,15 +673,9 @@ 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)
@@ -138,7 +138,7 @@ struct SQLQueryGenerator: Refinable {
let region = try prefetchedRegion(
db,
associations: prefetchedAssociations,
from: relation.source.associationOriginTable ?? relation.source.tableName)
from: relation.source.tableName)
statement.databaseRegion.formUnion(region)
}
@@ -741,15 +741,9 @@ 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)
}
@@ -125,6 +125,28 @@ public final class TableAlteration {
/// }
/// ```
///
/// Take care, when you rename **foreign keys** in <doc:Migrations>,
/// to run the migration with the ``DatabaseMigrator/ForeignKeyChecks/immediate``
/// foreign key checks, in order to avoid integrity failures:
///
/// ```swift
/// // RECOMMENDED: rename foreign keys with immediate foreign key checks.
/// migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in
/// try db.rename(table: "team", to: "guild")
/// try db.alter(table: "player") { t in
/// t.rename(column: "teamId", to: "guildId")
/// }
/// }
///
/// // NOT RECOMMENDED: rename foreign keys with disabled foreign keys.
/// migrator.registerMigration("Guilds") { db in
/// try db.rename(table: "team", to: "guild")
/// try db.alter(table: "player") { t in
/// t.rename(column: "teamId", to: "guildId")
/// }
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
///
/// - parameter name: the old name of the column.
+1 -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**: 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)
**Latest release**: March 22, 2025 • [version 7.4.0](https://github.com/groue/GRDB.swift/tree/v7.4.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+
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>7.3.0</string>
<string>7.4.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -157,110 +157,6 @@ 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
@@ -292,42 +188,6 @@ 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()
@@ -444,141 +304,6 @@ 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
@@ -730,218 +455,6 @@ 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
@@ -1217,138 +730,6 @@ 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
@@ -1559,7 +1559,18 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
"SELECT LENGTH(\"name\") FROM \"readers\"")
}
func testMinExpression() throws {
func testMultiArgumentMinExpression() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.select(min(Col.age, 1000))),
"SELECT MIN(\"age\", 1000) FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(min(Col.age, 1000, Col.id))),
"SELECT MIN(\"age\", 1000, \"id\") FROM \"readers\"")
}
func testAggregateMinExpression() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
@@ -1570,7 +1581,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
"SELECT MIN(\"age\" / 2) FROM \"readers\"")
}
func testMinExpression_filter() throws {
func testAggregateMinExpression_filter() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Prevent SQLCipher failures
guard Database.sqliteLibVersionNumber >= 3030000 else {
@@ -1592,7 +1603,18 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
"SELECT MIN(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"")
}
func testMaxExpression() throws {
func testMultiArgumentMaxExpression() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.select(max(Col.age, 1000))),
"SELECT MAX(\"age\", 1000) FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(max(Col.age, 1000, Col.id))),
"SELECT MAX(\"age\", 1000, \"id\") FROM \"readers\"")
}
func testAggregateMaxExpression() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
@@ -1603,7 +1625,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
"SELECT MAX(\"age\" / 2) FROM \"readers\"")
}
func testMaxExpression_filter() throws {
func testAggregateMaxExpression_filter() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Prevent SQLCipher failures
guard Database.sqliteLibVersionNumber >= 3030000 else {
@@ -1352,4 +1352,58 @@ class ValueObservationTests: GRDBTestCase {
XCTAssertEqual(value, true)
})
}
// Regression test for <https://github.com/groue/GRDB.swift/discussions/1746>
@MainActor func testIssue1746() async throws {
let dbQueue = try makeDatabaseQueue()
try await dbQueue.write { db in
try db.execute(sql: "CREATE TABLE test (id INTEGER PRIMARY KEY)")
}
// Start a task that waits for writeContinuation before it writes.
let (writeStream, writeContinuation) = AsyncStream.makeStream(of: Void.self)
let task = Task {
for await _ in writeStream { }
try? await dbQueue.write { db in
XCTAssertFalse(Task.isCancelled) // Required for the test to be meaningful
try db.execute(sql: "INSERT INTO test DEFAULT VALUES")
}
}
// A transaction observer that cancels a Task after commit.
class CancelObserver: TransactionObserver {
let task: Task<Void, Never>
init(task: Task<Void, Never>) {
self.task = task
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true }
func databaseDidChange(with event: DatabaseEvent) { }
func databaseDidRollback(_ db: Database) { }
func databaseDidCommit(_ db: Database) {
task.cancel()
}
}
// Register CancelObserver first, so no other observer could access
// the database before the task is cancelled.
dbQueue.add(transactionObserver: CancelObserver(task: task), extent: .databaseLifetime)
// Start observing.
// We expect to see 0, then 1.
let values = ValueObservation
.tracking(Table("test").fetchCount)
.values(in: dbQueue)
for try await value in values {
if value == 0 {
// Perform the write.
writeContinuation.finish()
} else if value == 1 {
// Test passes
break
} else {
XCTFail("Unexpected value \(value)")
break
}
}
}
}