mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-05 05:18:44 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63590ede60 |
No files matched your search
@@ -7,7 +7,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 7.x Releases
|
||||
|
||||
- `7.4.x` Releases - [7.4.0](#740) - [7.4.1](#741)
|
||||
- `7.3.x` Releases - [7.3.0](#730)
|
||||
- `7.2.x` Releases - [7.2.0](#720)
|
||||
- `7.1.x` Releases - [7.1.0](#710)
|
||||
@@ -136,19 +135,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 7.4.1
|
||||
|
||||
Released March 28, 2025
|
||||
|
||||
- Removed a compiler warning
|
||||
|
||||
## 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
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '7.4.1'
|
||||
s.version = '7.3.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -494,9 +494,11 @@ extension Database {
|
||||
|
||||
switch ResultCode(rawValue: resultCode) {
|
||||
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
|
||||
// The only error that a user sees when a Task is cancelled
|
||||
// is CancellationError.
|
||||
try suspensionMutex.load().checkCancellation()
|
||||
if suspensionMutex.load().isCancelled {
|
||||
// The only error that a user sees when a Task is cancelled
|
||||
// is CancellationError.
|
||||
throw CancellationError()
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
@@ -341,22 +341,10 @@ 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,
|
||||
interruptsWhenCancelled: true))
|
||||
let suspensionMutex = Mutex(Suspension(isSuspended: false, isCancelled: false))
|
||||
|
||||
// MARK: - Transaction Date
|
||||
|
||||
@@ -1234,7 +1222,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
|
||||
suspension.isCancelled = true
|
||||
return suspension.interruptsWhenCancelled
|
||||
return true
|
||||
}
|
||||
|
||||
if needsInterrupt {
|
||||
@@ -1249,24 +1237,6 @@ 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 {
|
||||
@@ -1333,7 +1303,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, suspension.interruptsWhenCancelled {
|
||||
if suspension.isCancelled {
|
||||
return .cancel
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -549,12 +549,8 @@ class DatabaseObservationBroker {
|
||||
savepointStack.clear()
|
||||
|
||||
if !database.isReadOnly {
|
||||
// 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)
|
||||
}
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidCommit(database)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -617,13 +613,8 @@ class DatabaseObservationBroker {
|
||||
|
||||
if notifyTransactionObservers {
|
||||
assert(!database.isReadOnly, "Read-only transactions are not notified")
|
||||
|
||||
// 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)
|
||||
}
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidRollback(database)
|
||||
}
|
||||
}
|
||||
databaseDidEndTransaction()
|
||||
|
||||
@@ -94,26 +94,6 @@ 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:
|
||||
@@ -133,39 +113,19 @@ 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 below. One way to do this is to run the following statement and examine the output in the console:
|
||||
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'`.
|
||||
|
||||
```swift
|
||||
try db.dumpSQL("SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'")
|
||||
```
|
||||
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.
|
||||
|
||||
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.
|
||||
3. Transfer content from X into new_X using a statement like: `INSERT INTO new_X SELECT ... FROM X`.
|
||||
|
||||
```swift
|
||||
try db.create(table: "new_X") { t in ... }
|
||||
```
|
||||
4. Drop the old table X: `DROP TABLE X`.
|
||||
|
||||
3. Transfer content from `X` into `new_X` using a statement like:
|
||||
5. Change the name of new_X to X using: `ALTER TABLE new_X RENAME TO X`.
|
||||
|
||||
```swift
|
||||
try db.execute(sql: "INSERT INTO new_X SELECT ... FROM X")
|
||||
```
|
||||
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.
|
||||
|
||||
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`.
|
||||
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,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
|
||||
|
||||
@@ -1518,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)
|
||||
@@ -1651,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)
|
||||
@@ -1660,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:)
|
||||
|
||||
@@ -2209,10 +2209,8 @@ extension SQLExpressible where Self == Column {
|
||||
/// - ``localizedLowercased``
|
||||
/// - ``localizedUppercased``
|
||||
/// - ``lowercased``
|
||||
/// - ``min(_:_:_:)``
|
||||
/// - ``min(_:)``
|
||||
/// - ``min(_:filter:)``
|
||||
/// - ``max(_:_:_:)``
|
||||
/// - ``max(_:)``
|
||||
/// - ``max(_:filter:)``
|
||||
/// - ``sum(_:)``
|
||||
|
||||
@@ -11,7 +11,7 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `AVG` SQL aggregate function.
|
||||
/// The `AVG` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -26,7 +26,7 @@ public func average(
|
||||
.aggregateFunction("AVG", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `AVG` SQL aggregate function.
|
||||
/// The `AVG` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -44,7 +44,7 @@ public func average(
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `AVG` SQL aggregate function.
|
||||
/// The `AVG` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -147,24 +147,8 @@ 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 aggregate function.
|
||||
/// The `MAX` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -179,7 +163,7 @@ public func max(
|
||||
.aggregateFunction("MAX", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `MAX` SQL aggregate function.
|
||||
/// The `MAX` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -195,7 +179,7 @@ public func max(
|
||||
.aggregateFunction("MAX", [value.sqlExpression], filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `MAX` SQL aggregate function.
|
||||
/// The `MAX` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -208,24 +192,8 @@ 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 aggregate function.
|
||||
/// The `MIN` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -240,7 +208,7 @@ public func min(
|
||||
.aggregateFunction("MIN", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `MIN` SQL aggregate function.
|
||||
/// The `MIN` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -256,7 +224,7 @@ public func min(
|
||||
.aggregateFunction("MIN", [value.sqlExpression], filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `MIN` SQL aggregate function.
|
||||
/// The `MIN` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -270,7 +238,7 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
#endif
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `SUM` SQL aggregate function.
|
||||
/// The `SUM` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -294,7 +262,7 @@ public func sum(
|
||||
filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `SUM` SQL aggregate function.
|
||||
/// The `SUM` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -316,7 +284,7 @@ public func sum(
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `SUM` SQL aggregate function.
|
||||
/// The `SUM` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -334,7 +302,7 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
#endif
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `TOTAL` SQL aggregate function.
|
||||
/// The `TOTAL` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -358,7 +326,7 @@ public func total(
|
||||
filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `TOTAL` SQL aggregate function.
|
||||
/// The `TOTAL` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -380,7 +348,7 @@ public func total(
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `TOTAL` SQL aggregate function.
|
||||
/// The `TOTAL` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -125,28 +125,6 @@ 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.
|
||||
|
||||
@@ -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**: March 28, 2025 • [version 7.4.1](https://github.com/groue/GRDB.swift/tree/v7.4.1) • [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+ • SQLite 3.20.0+ • Swift 6+ / Xcode 16+
|
||||
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>7.4.1</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
|
||||
|
||||
@@ -1559,18 +1559,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
"SELECT LENGTH(\"name\") FROM \"readers\"")
|
||||
}
|
||||
|
||||
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 {
|
||||
func testMinExpression() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
@@ -1581,7 +1570,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
"SELECT MIN(\"age\" / 2) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testAggregateMinExpression_filter() throws {
|
||||
func testMinExpression_filter() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Prevent SQLCipher failures
|
||||
guard Database.sqliteLibVersionNumber >= 3030000 else {
|
||||
@@ -1603,18 +1592,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
"SELECT MIN(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
}
|
||||
|
||||
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 {
|
||||
func testMaxExpression() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
@@ -1625,7 +1603,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
"SELECT MAX(\"age\" / 2) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testAggregateMaxExpression_filter() throws {
|
||||
func testMaxExpression_filter() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Prevent SQLCipher failures
|
||||
guard Database.sqliteLibVersionNumber >= 3030000 else {
|
||||
|
||||
@@ -1352,58 +1352,4 @@ 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user