Merge pull request #885 from groue/dev/cte+871

Robustness of eager loading of to-many associations based on compound foreign keys
This commit is contained in:
Gwendal Roué authored and GitHub committed 2020-12-12 13:31:28 +01:00
commit eb0e0d4cdd
18 files changed
+470 -98

No files matched your search

+3
View File
@@ -73,7 +73,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- **New**: [#880](https://github.com/groue/GRDB.swift/pull/880): Common Table Expressions
- **Fixed**: [#881](https://github.com/groue/GRDB.swift/pull/881) by [@felixscheinost](https://github.com/felixscheinost) and [#883](https://github.com/groue/GRDB.swift/pull/883) by [@professordeng](https://github.com/professordeng): Documentation improvements
- **Fixed**: [#885](https://github.com/groue/GRDB.swift/pull/885): Robustness of eager loading of to-many associations based on compound foreign keys
- **Documentation update**: A new guide: [Common Table Expressions](https://github.com/groue/GRDB.swift/blob/master/Documentation/CommonTableExpressions.md)
- **Documentation update**: The [Foreign Keys](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#foreign-keys) chapter of the Associations Guide clarifies the behavior of SQLite and GRDB regarding the presence of NULL if compound foreign keys.
## 5.2.0
+4 -24
View File
@@ -697,7 +697,7 @@ See [Foreign Keys] for more information.
**Associations can automatically infer the foreign keys that define how two database tables are linked together.**
In the example below, the `book.authorId` column is automatically used to link a book to its author:
In the example below, the `book.authorId` column is automatically used to link a book to its author, because the database schema defines a foreign key between the book and author database tables (see [Convention for the BelongsTo Association]).
![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/master/Documentation/Images/Associations2/BelongsToSchema.svg)
@@ -711,7 +711,9 @@ struct Author: TableRecord {
}
```
But this requires the database schema to define a foreign key between the book and author database tables (see [Convention for the BelongsTo Association]).
> :point_up: **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns.
>
> :warning: **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either.
Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another.
@@ -941,24 +943,6 @@ The pattern is always the same: you start from a base request, that you extend w
Finally, readers who speak SQL may compare `optional` with left joins, and `required` with inner joins.
> :warning: **Warning**: You will get a database error with code [`SQLITE_ERROR`](https://www.sqlite.org/rescode.html#error) (1) "Expression tree is too large", when the following conditions are met:
>
> - You use the `including(all:)` method (say: `Parent.including(all: children)`).
> - The association is based on a compound foreign key (made of two columns or more).
> - The request fetches a lot of parent records. The exact threshold depends on [SQLITE_LIMIT_EXPR_DEPTH](https://www.sqlite.org/limits.html). It is around 1000 parents in recent iOS and macOS systems. To get an exact figure, run:
>
> ```swift
> let limit = try dbQueue.read { db in
> sqlite3_limit(db.sqliteConnection, SQLITE_LIMIT_EXPR_DEPTH, -1)
> }
> ```
>
> Possible workarounds are:
>
> - Refactor the database schema so that you do not depend on a compound foreign key.
> - Prefetch children with your own code, without using `including(all:)`.
>
> For more information about this caveat, see [issue #871](https://github.com/groue/GRDB.swift/issues/871).
## Combining Associations
@@ -2395,10 +2379,6 @@ See [Good Practices for Designing Record Types] for more information.
.including(all: Country.passports
.including(required: Passport.citizen))
```
- **The `including(all:)` method may fail with a database error of code [`SQLITE_ERROR`](https://www.sqlite.org/rescode.html#error) (1) "Expression tree is too large" when you use a compound foreign key and there are a lot of parent records.**
See [Joining And Prefetching Associated Records] for more information about this error.
Come [discuss](http://twitter.com/groue) for more information, or if you wish to help turning those missing features into reality.
+4
View File
@@ -1,6 +1,10 @@
Common Table Expressions
========================
[**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features)
---
**Common table expressions** (CTEs) can generally be seen as *SQL views that you define on the fly*.
A certain level of familiarity with SQL databases is helpful before you dive into this guide. The starting point is obviously the [SQLite documentation](https://sqlite.org/lang_with.html). Many CTE tutorials exist online as well, including [this good one](https://blog.expensify.com/2015/09/25/the-simplest-sqlite-common-table-expression-tutorial/).
+1 -1
View File
@@ -188,7 +188,7 @@ See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for
This will avoid https://github.com/sqlcipher/sqlcipher/issues/255.
2. [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features) In each process that wants to write in the database:
2. [**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features) In each process that wants to write in the database:
Set the `observesSuspensionNotifications` configuration flag:
+10
View File
@@ -821,6 +821,10 @@
56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
56D8B3FF257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; };
56D8B400257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; };
56D8B401257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; };
56D8B402257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; };
56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; };
56D91AA32205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; };
56D91AA42205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; };
@@ -1621,6 +1625,7 @@
56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = "<group>"; };
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = "<group>"; };
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRowValue.swift; sourceTree = "<group>"; };
56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
56D91AA82205F2F000770D8D /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = "<group>"; };
56D91AAF2205F8AC00770D8D /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = "<group>"; };
@@ -2125,6 +2130,7 @@
56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */,
56D91AAF2205F8AC00770D8D /* SQLQuery.swift */,
56D91AA12205E03700770D8D /* SQLRelation.swift */,
56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */,
56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */,
566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */,
56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */,
@@ -3063,6 +3069,7 @@
565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */,
565490B81D5AE236005622CB /* DatabaseError.swift in Sources */,
56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */,
56D8B401257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */,
5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
56A2FA3C24424F4800E97D23 /* Export.swift in Sources */,
@@ -3210,6 +3217,7 @@
5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */,
566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
56D8B400257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */,
5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
56FBFED92210731A00945324 /* SQLRequest.swift in Sources */,
5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
@@ -3808,6 +3816,7 @@
AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */,
AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */,
AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */,
56D8B402257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */,
AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */,
AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */,
AAA4DCD7230F1E0600C74B15 /* DatabaseValueConversion.swift in Sources */,
@@ -4180,6 +4189,7 @@
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */,
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */,
56D8B3FF257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */,
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */,
5605F1651C672E4000235C62 /* NSNull.swift in Sources */,
56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
+1 -6
View File
@@ -123,12 +123,7 @@ public struct _SQLAssociation {
// children are useless:
let relation = step.relation
.selectOnly([])
.filteringChildren({
switch $0.kind {
case .allPrefetched, .allNotPrefetched: return false
case .oneRequired, .oneOptional: return true
}
})
.removingChildrenForPrefetchedAssociations()
// Don't interfere with user-defined keys that could be added later
let key = step.key.map(\.baseName) { "grdb_\($0)" }
@@ -3,6 +3,8 @@ public protocol _SQLExpressionVisitor: _FetchRequestVisitor {
mutating func visit(_ dbValue: DatabaseValue) throws
mutating func visit<Column: ColumnExpression>(_ column: Column) throws
mutating func visit(_ column: _SQLQualifiedColumn) throws
/// - precondition: expr.expressions.count > 1
mutating func visit(_ expr: _SQLRowValue) throws
mutating func visit(_ expr: _SQLExpressionBetween) throws
mutating func visit(_ expr: _SQLExpressionBinary) throws
/// - precondition: expr.expressions.count > 1
+19 -15
View File
@@ -365,6 +365,15 @@ extension SQLRelation {
func filteringChildren(_ included: (Child) throws -> Bool) rethrows -> Self {
try map(\.children) { try $0.filter { try included($1) } }
}
func removingChildrenForPrefetchedAssociations() -> Self {
filteringChildren {
switch $0.kind {
case .allPrefetched, .allNotPrefetched: return false
case .oneRequired, .oneOptional: return true
}
}
}
}
extension SQLRelation: _JoinableRequest {
@@ -588,7 +597,7 @@ extension JoinMapping {
// We could return `false.sqlExpression`.
//
// But we need to take care of database observation, and generate
// SQL that involves all used columns. Consider using a `NullRow`.
// SQL that involves all used columns. Consider using a `DummyRow`.
fatalError("Provide at least one left row, or this method can't generate SQL that can be observed.")
}
@@ -609,16 +618,10 @@ extension JoinMapping {
// Unique database values and filter out NULL:
let leftIndex = mapping.leftIndex
var dbValues = Set(leftRows.map { $0.databaseValue(at: leftIndex) })
dbValues.remove(.null)
if dbValues.isEmpty {
// null was removed from dbValues
return mapping.rightColumn == nil
} else {
// table.a IN (1, 2, 3, ...)
// Sort database values for nicer output.
return dbValues.sorted(by: <).contains(mapping.rightColumn)
}
dbValues.remove(.null) // SQLite doesn't match foreign keys on NULL
// table.a IN (1, 2, 3, ...)
// Sort database values for nicer output.
return dbValues.sorted(by: <).contains(mapping.rightColumn)
} else {
// Join on a multiple columns.
// ((table.a = 1) AND (table.b = 2)) OR ((table.a = 3) AND (table.b = 4)) ...
@@ -628,7 +631,8 @@ extension JoinMapping {
mappings
.map({ mapping -> SQLExpression in
let leftValue = leftRow.databaseValue(at: mapping.leftIndex)
return mapping.rightColumn == leftValue
// Force `=` operator, because SQLite doesn't match foreign keys on NULL
return _SQLExpressionEqual(.equal, mapping.rightColumn, leftValue)
})
.joined(operator: .and)
})
@@ -660,12 +664,12 @@ protocol ColumnAddressable {
func databaseValue(at index: ColumnIndex) -> DatabaseValue
}
/// A "row" that contains null values for all columns
struct NullRow: ColumnAddressable {
/// A "row" that contains a dummy value for all columns
struct DummyRow: ColumnAddressable {
struct DummyIndex { }
func index(forColumn column: String) -> DummyIndex? { DummyIndex() }
@inline(__always)
func databaseValue(at index: DummyIndex) -> DatabaseValue { .null }
func databaseValue(at index: DummyIndex) -> DatabaseValue { DatabaseValue(storage: .int64(1)) }
}
/// Row has columns
+28
View File
@@ -0,0 +1,28 @@
/// A [row value](https://www.sqlite.org/rowvalue.html).
///
/// :nodoc:
public struct _SQLRowValue: SQLExpression {
let expressions: [SQLExpression]
/// SQLite row values were shipped in SQLite 3.15:
/// https://www.sqlite.org/releaselog/3_15_0.html
static let isAvailable = (sqlite3_libversion_number() >= 3015000)
/// - precondition: `expressions` is not empty
init(_ expressions: [SQLExpression]) {
assert(!expressions.isEmpty)
self.expressions = expressions
}
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression {
_SQLRowValue(expressions.map { $0._qualifiedExpression(with: alias) })
}
public func _accept<Visitor: _SQLExpressionVisitor>(_ visitor: inout Visitor) throws {
if let expression = expressions.first, expressions.count == 1 {
try expression._accept(&visitor)
} else {
try visitor.visit(self)
}
}
}
@@ -41,6 +41,13 @@ private struct SQLExpressionGenerator: _SQLExpressionVisitor {
resultSQL += column.name.quotedDatabaseIdentifier
}
mutating func visit(_ expr: _SQLRowValue) throws {
let values = try expr
.expressions
.map { try $0.expressionSQL(context, wrappedInParenthesis: false) }
resultSQL = "(\(values.joined(separator: ", ")))"
}
mutating func visit(_ expr: _SQLExpressionBetween) throws {
resultSQL = try """
\(expr.expression.expressionSQL(context, wrappedInParenthesis: true)) \
@@ -36,7 +36,7 @@ private struct SQLOrderingGenerator: _SQLOrderingTermVisitor {
mutating func visit(_ ordering: _SQLOrderingLiteral) throws {
resultSQL = try ordering.sqlLiteral.sql(context)
}
// MARK: - _SQLExpressionVisitor
mutating func visit(_ expr: DatabaseValue) throws {
@@ -51,6 +51,10 @@ private struct SQLOrderingGenerator: _SQLOrderingTermVisitor {
resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false)
}
mutating func visit(_ expr: _SQLRowValue) throws {
resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false)
}
mutating func visit(_ expr: _SQLExpressionBetween) throws {
resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false)
}
@@ -87,7 +87,7 @@ private struct SQLPreparedRequestGenerator: _FetchRequestVisitor {
if associations.isEmpty == false {
// Eager loading of prefetched associations
preparedRequest = preparedRequest.with(\.supplementaryFetch) { db, rows in
try prefetch(db, associations: associations, in: rows)
try prefetch(db, associations: associations, into: rows, from: request)
}
}
self.preparedRequest = preparedRequest
@@ -135,8 +135,23 @@ private struct SQLRequestCounter: _FetchRequestVisitor {
// MARK: - Eager loading of hasMany associations
// CAUTION: Keep this code in sync with prefetchedRegion(_:_:)
/// Append rows from prefetched associations into the argument rows.
private func prefetch(_ db: Database, associations: [_SQLAssociation], in rows: [Row]) throws {
/// Append rows from prefetched associations into the `baseRows` argument.
///
/// - parameter db: A database connection.
/// - parameter associations: Prefetched associations.
/// - parameter baseRows: The rows that need to be extended with prefetched rows.
/// - parameter baseRequest: The request that was used to fetch `baseRows`.
private func prefetch<RowDecoder>(
_ db: Database,
associations: [_SQLAssociation],
into baseRows: [Row],
from baseRequest: QueryInterfaceRequest<RowDecoder>) throws
{
guard let firstBaseRow = baseRows.first else {
// No rows -> no prefetch
return
}
for association in associations {
switch association.pivot.condition {
case .expression:
@@ -148,24 +163,120 @@ private func prefetch(_ db: Database, associations: [_SQLAssociation], in rows:
let pivotMapping = try foreignKeyRequest
.fetchForeignKeyMapping(db)
.joinMapping(originIsLeft: originIsLeft)
try prefetch(db, association: association, pivotMapping: pivotMapping, in: rows)
let pivotColumns = pivotMapping.map(\.right)
let leftColumns = pivotMapping.map(\.left)
// We want to avoid the "Expression tree is too large" SQLite error
// when the foreign key contains several columns, and there are many
// base rows that overflow SQLITE_LIMIT_EXPR_DEPTH:
// https://github.com/groue/GRDB.swift/issues/871
//
// -- May be too complex for the SQLite engine
// SELECT * FROM child
// WHERE (a = ? AND b = ?)
// OR (a = ? AND b = ?)
// OR ...
//
// Instead, we do not inject any value from the base rows in
// the prefetch request. Instead, we directly inject the base
// request as a common table expression (CTE):
//
// WITH grdb_base AS (SELECT a, b FROM parent)
// SELECT * FROM child
// WHERE (a, b) IN grdb_base
//
// This technique works well, but there is one precondition: row
// values must be available (https://www.sqlite.org/rowvalue.html).
// This is the case of almost all our target platforms.
//
// Otherwise, we fallback to the `(a = ? AND b = ?) OR ...`
// condition (the one that may fail if there are too many
// base rows).
let usesCommonTableExpression = pivotMapping.count > 1 && _SQLRowValue.isAvailable
let prefetchRequest: QueryInterfaceRequest<Row>
if usesCommonTableExpression {
// HasMany: Author.including(all: Author.books)
//
// WITH grdb_base AS (SELECT a, b FROM author)
// SELECT book.*, book.authorId AS grdb_authorId
// FROM book
// WHERE (book.a, book.b) IN grdb_base
//
// HasManyThrough: Citizen.including(all: Citizen.countries)
//
// WITH grdb_base AS (SELECT a, b FROM citizen)
// SELECT country.*, passport.citizenId AS grdb_citizenId
// FROM country
// JOIN passport ON passport.countryCode = country.code
// AND (passport.a, passport.b) IN grdb_base
let baseRequest = baseRequest.map(\.query.relation) { baseRelation in
// Ordering and including(all:) children are
// useless, and we only need pivoting columns:
baseRelation
.unordered()
.removingChildrenForPrefetchedAssociations()
.selectOnly(leftColumns.map(Column.init))
}
let baseCTE = CommonTableExpression<Void>(
named: "grdb_base",
request: baseRequest)
let pivotRowValue = _SQLRowValue(pivotColumns.map(Column.init))
let pivotFilter = SQLLiteral("\(pivotRowValue) IN grdb_base").sqlExpression
prefetchRequest = makePrefetchRequest(
for: association,
filteringPivotWith: pivotFilter,
annotatedWith: pivotColumns)
.with(baseCTE)
} else {
// HasMany: Author.including(all: Author.books)
//
// SELECT *, authorId AS grdb_authorId
// FROM book
// WHERE authorId IN (1, 2, 3)
//
// HasManyThrough: Citizen.including(all: Citizen.countries)
//
// SELECT country.*, passport.citizenId AS grdb_citizenId
// FROM country
// JOIN passport ON passport.countryCode = country.code
// AND passport.citizenId IN (1, 2, 3)
let pivotFilter = pivotMapping.joinExpression(leftRows: baseRows)
prefetchRequest = makePrefetchRequest(
for: association,
filteringPivotWith: pivotFilter,
annotatedWith: pivotColumns)
}
let prefetchedRows = try prefetchRequest.fetchAll(db)
let prefetchedGroups = prefetchedRows.grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" })
let groupingIndexes = firstBaseRow.indexes(forColumns: leftColumns)
for row in baseRows {
let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
let prefetchedRows = prefetchedGroups[groupingKey, default: []]
row.prefetchedRows.setRows(prefetchedRows, forKeyPath: association.keyPath)
}
}
}
}
// CAUTION: Keep this code in sync with prefetchedRegion(_:_:)
private func prefetch(
_ db: Database,
association: _SQLAssociation,
pivotMapping: JoinMapping,
in rows: [Row]) throws
/// Returns a request for prefetched rows.
///
/// - parameter assocciation: The prefetched association.
/// - parameter pivotFilter: The expression that filters the pivot of
/// the association.
/// - parameter pivotColumns: The pivot columns that annotate the
/// returned request.
func makePrefetchRequest(
for association: _SQLAssociation,
filteringPivotWith pivotFilter: SQLExpression,
annotatedWith pivotColumns: [String])
-> QueryInterfaceRequest<Row>
{
guard let firstRow = rows.first else {
// No rows -> no prefetch
return
}
// Annotate prefetched rows with pivot columns, so that we can
// We annotate prefetched rows with pivot columns, so that we can
// group them.
//
// Those pivot columns are necessary when we prefetch
@@ -186,32 +297,14 @@ private func prefetch(
// // FROM book
// // WHERE authorId IN (1, 2, 3)
// Author.including(all: Author.books)
let pivotFilter = pivotMapping.joinExpression(leftRows: rows)
let pivotColumns = pivotMapping.map(\.right)
let pivotAlias = TableAlias()
let prefetchRelation = association
.map(\.pivot.relation, { $0.qualified(with: pivotAlias).filter(pivotFilter) })
.destinationRelation()
// Annotate with the pivot columns that allow grouping
.annotated(with: pivotColumns.map { pivotAlias[$0].forKey("grdb_\($0)") })
let prefetchRequest = QueryInterfaceRequest<Row>(relation: prefetchRelation)
let prefetchedRows = try prefetchRequest.fetchAll(db)
let prefetchedGroups = prefetchedRows.grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" })
let groupingIndexes = firstRow.indexes(forColumns: pivotMapping.map(\.left))
for row in rows {
let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
let prefetchedRows = prefetchedGroups[groupingKey, default: []]
row.prefetchedRows.setRows(prefetchedRows, forKeyPath: association.keyPath)
}
return QueryInterfaceRequest<Row>(relation: prefetchRelation)
}
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
@@ -241,12 +334,12 @@ func prefetchedRegion(
pivotMapping: JoinMapping)
throws -> DatabaseRegion
{
// Filter the pivot on a `NullRow` in order to make sure all join
// Filter the pivot on a `DummyRow` in order to make sure all join
// condition columns are made visible to SQLite, and present in the
// selected region:
// ... JOIN right ON right.leftId IS NULL
// ^ content of the NullRow
let pivotFilter = pivotMapping.joinExpression(leftRows: [NullRow()])
// ... JOIN right ON right.leftId = ?
// ^ content of the DummyRow
let pivotFilter = pivotMapping.joinExpression(leftRows: [DummyRow()])
let prefetchRelation = association
.map(\.pivot.relation) { $0.filter(pivotFilter) }
@@ -870,6 +870,10 @@ private struct SQLExpressionIsTrue: _SQLExpressionVisitor {
try setFalse()
}
mutating func visit(_ expr: _SQLRowValue) throws {
try setFalse()
}
mutating func visit(_ expr: _SQLExpressionBetween) throws {
try setFalse()
}
@@ -995,6 +999,12 @@ private struct SQLExpressionIsConstantInRequest: _SQLExpressionVisitor {
try setNotConstant()
}
mutating func visit(_ expr: _SQLRowValue) throws {
for expression in expr.expressions {
try expression._accept(&self)
}
}
mutating func visit(_ expr: _SQLExpressionBetween) throws {
try expr.expression._accept(&self)
try expr.lowerBound._accept(&self)
@@ -1139,6 +1149,8 @@ private struct SQLTableColumnVisitor: _SQLExpressionVisitor {
}
}
mutating func visit(_ expr: _SQLRowValue) throws { }
mutating func visit(_ expr: _SQLExpressionBetween) throws { }
mutating func visit(_ expr: _SQLExpressionBinary) throws {
@@ -1230,6 +1242,10 @@ extension SQLExpression {
/// WHERE a = 1 OR a = 2 -- []
/// WHERE a > 1 -- []
///
/// TODO: deal with row values:
/// WHERE (a, b) = (1, 2) -- ["a", "b"]
/// WHERE (a, b) IN (SELECT ...) -- ["a", "b"]
///
/// Support for `SQLQueryGenerator.expectsSingleResult()`
func identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set<String> {
var visitor = SQLIdentifyingColumns(db: db, alias: alias)
@@ -1256,6 +1272,8 @@ private struct SQLIdentifyingColumns: _SQLExpressionVisitor {
mutating func visit(_ column: _SQLQualifiedColumn) throws { }
mutating func visit(_ expr: _SQLRowValue) throws { }
mutating func visit(_ expr: _SQLExpressionBetween) throws { }
mutating func visit(_ expr: _SQLExpressionBinary) throws { }
@@ -1345,6 +1363,8 @@ extension SQLExpression {
/// WHERE id IN (1, 2) OR rowid IN (2, 3) -- [1, 2, 3]
/// WHERE id > 1 -- nil
///
/// TODO: deal with row values:
/// WHERE (id, a) = (1, 2) -- 1
/// Support for `SQLQueryGenerator.optimizedSelectedRegion()`
func identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set<Int64>? {
var visitor = SQLIdentifyingRowIDs(db: db, alias: alias)
@@ -1369,6 +1389,8 @@ private struct SQLIdentifyingRowIDs: _SQLExpressionVisitor {
mutating func visit(_ column: _SQLQualifiedColumn) throws { }
mutating func visit(_ expr: _SQLRowValue) throws { }
mutating func visit(_ expr: _SQLExpressionBetween) throws { }
mutating func visit(_ expr: _SQLExpressionBinary) throws { }
@@ -1525,6 +1547,12 @@ private struct SQLSelectableIsAggregate: _SQLSelectableVisitor {
mutating func visit(_ selectable: _SQLQualifiedAllColumns) throws { }
mutating func visit(_ expr: _SQLRowValue) throws {
for expression in expr.expressions {
try expression._accept(&self)
}
}
mutating func visit(_ selectable: _SQLSelectionLiteral) throws {
// Don't know - assume not an aggregate
}
@@ -60,6 +60,10 @@ private struct SQLSelectableCountGenerator: _SQLSelectableVisitor {
resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false)
}
mutating func visit(_ expr: _SQLRowValue) throws {
resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false)
}
mutating func visit(_ expr: _SQLExpressionBetween) throws {
resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false)
}
@@ -59,6 +59,10 @@ private struct SQLSelectableResultColumnGenerator: _SQLSelectableVisitor {
resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false)
}
mutating func visit(_ expr: _SQLRowValue) throws {
resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false)
}
mutating func visit(_ expr: _SQLExpressionBetween) throws {
resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false)
}
+6
View File
@@ -487,6 +487,8 @@
56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; };
56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
56D8B40D257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */; };
56D8B40E257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */; };
56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
56DAA2D91DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; };
@@ -1105,6 +1107,7 @@
56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = "<group>"; };
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = "<group>"; };
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRowValue.swift; sourceTree = "<group>"; };
56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = "<group>"; };
56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = "<group>"; };
56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = "<group>"; };
@@ -1604,6 +1607,7 @@
56F34FE524B0E94C007513FC /* SQLOrderingTermVisitor.swift */,
5656A8502295BD56001FF3FF /* SQLQuery.swift */,
5656A84E2295BD56001FF3FF /* SQLRelation.swift */,
56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */,
5656A8492295BD56001FF3FF /* SQLSelectable.swift */,
5656A84F2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift */,
56F34FCD24B0DE0B007513FC /* SQLSelectableVisitor.swift */,
@@ -2415,6 +2419,7 @@
F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */,
5656A8802295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */,
56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
56D8B40E257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */,
561408A1221596A100DAD589 /* GRDB-5.0.swift in Sources */,
F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */,
56FBFED72210731100945324 /* SQLRequest.swift in Sources */,
@@ -2787,6 +2792,7 @@
F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */,
5656A87F2295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */,
56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
56D8B40D257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */,
561408A0221596A100DAD589 /* GRDB-5.0.swift in Sources */,
F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */,
56FBFED62210731100945324 /* SQLRequest.swift in Sources */,
@@ -1138,4 +1138,53 @@ class AssociationPrefetchingRowTests: GRDBTestCase {
XCTAssertEqual(row3.prefetchedRows["bs"], [])
}
}
// Regression test for https://github.com/groue/GRDB.swift/issues/871
func testCompoundColumnLimit() throws {
struct Parent: Encodable, PersistableRecord {
let a: Int
let b: Int
static let children = hasMany(Child.self)
}
struct Child: Encodable, PersistableRecord {
let a: Int
let b: Int
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
t.column("a", .integer).notNull()
t.column("b", .integer).notNull()
t.primaryKey(["a", "b"])
}
try db.create(table: "child") { t in
t.column("a", .integer).notNull()
t.column("b", .integer).notNull()
t.foreignKey(["a", "b"], references: "parent")
}
let count = Int(sqlite3_limit(db.sqliteConnection, SQLITE_LIMIT_EXPR_DEPTH, -1))
for index in 0..<count {
try Parent(a: index, b: 1).insert(db)
try Child(a: index, b: 1).insert(db)
}
let request = Parent
.including(all: Parent.children)
.asRequest(of: Row.self)
let rows = try request.fetchAll(db)
for (index, row) in rows.enumerated() {
XCTAssertEqual(row.unscoped, ["a": index, "b": 1])
XCTAssertEqual(row.prefetchedRows.keys, ["children"])
XCTAssertEqual(row.prefetchedRows["children"]!.count, 1)
XCTAssertEqual(
row.prefetchedRows["children"]![0],
["a": index, "b": 1, "grdb_a": index, "grdb_b": 1])
}
}
}
}
@@ -158,6 +158,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
func testIncludingAllHasManyWithCompoundForeignKey() throws {
// We can use the CTE technique
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "parent") { t in
@@ -166,17 +167,17 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
t.primaryKey(["parentA", "parentB"])
}
try db.create(table: "child") { t in
t.column("parentA", .text)
t.column("parentB", .text)
t.column("pA", .text)
t.column("pB", .text)
t.column("name", .text)
t.foreignKey(["parentA", "parentB"], references: "parent")
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 (parentA, parentB, name) VALUES ('foo', 'bar', 'foobar1');
INSERT INTO child (parentA, parentB, name) VALUES ('foo', 'bar', 'foobar2');
INSERT INTO child (parentA, parentB, name) VALUES ('baz', 'qux', 'bazqux1');
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 { }
@@ -198,9 +199,9 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
SELECT * FROM "parent" ORDER BY "parentA", "parentB"
""",
"""
SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \
FROM "child" \
WHERE (("parentA" = 'baz') AND ("parentB" = 'qux')) OR (("parentA" = 'foo') AND ("parentB" = 'bar'))
WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \
FROM "child" WHERE ("pA", "pB") IN grdb_base
"""])
}
@@ -240,13 +241,15 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
SELECT * FROM "parent" WHERE "parentA" = 'foo' ORDER BY "parentA", "parentB"
""",
"""
SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \
FROM "child" WHERE ("name" = 'foo') AND (("parentA" = 'foo') AND ("parentB" = 'bar'))
WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "parentA" = 'foo') \
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \
FROM "child" \
WHERE ("name" = 'foo') AND (("pA", "pB") IN grdb_base)
"""])
}
}
}
func testIncludingAllHasManyIncludingAllHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
@@ -398,6 +401,154 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testIncludingAllHasManyIncludingAllHasManyWithCompoundForeignKey() throws {
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.column("name", .text)
t.primaryKey(["parentA", "parentB"])
}
try db.create(table: "child") { t in
t.column("childA", .text)
t.column("childB", .text)
t.column("pA", .text)
t.column("pB", .text)
t.column("name", .text)
t.primaryKey(["childA", "childB"])
t.foreignKey(["pA", "pB"], references: "parent")
}
try db.create(table: "grandchild") { t in
t.column("cA", .text)
t.column("cB", .text)
t.column("name", .text)
t.foreignKey(["cA", "cB"], references: "child")
}
try db.execute(sql: """
INSERT INTO parent (parentA, parentB, name) VALUES ('foo', 'bar', 'foo');
INSERT INTO parent (parentA, parentB, name) VALUES ('baz', 'qux', 'foo');
INSERT INTO child (childA, childB, pA, pB, name) VALUES ('a', 'b', 'foo', 'bar', 'blue');
INSERT INTO child (childA, childB, pA, pB, name) VALUES ('c', 'd', 'foo', 'bar', 'pink');
INSERT INTO child (childA, childB, pA, pB, name) VALUES ('e', 'f', 'baz', 'qux', 'blue');
INSERT INTO grandchild (cA, cB, name) VALUES ('a', 'b', 'dog');
INSERT INTO grandchild (cA, cB, name) VALUES ('a', 'b', 'cat');
INSERT INTO grandchild (cA, cB, name) VALUES ('c', 'd', 'cat');
INSERT INTO grandchild (cA, cB, name) VALUES ('e', 'f', 'dog');
""")
struct Parent: TableRecord { }
struct Child: TableRecord { }
struct GrandChild: TableRecord { }
// Plain request
do {
let request = Parent
.including(all: Parent.hasMany(Child.self)
.including(all: Child.hasMany(GrandChild.self)))
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "parent" ORDER BY "parentA", "parentB"
""",
"""
WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \
FROM "child" WHERE ("pA", "pB") IN grdb_base
""",
"""
WITH "grdb_base" AS (\
WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \
SELECT "childA", "childB" FROM "child" \
WHERE ("pA", "pB") IN grdb_base\
) \
SELECT *, "cA" AS "grdb_cA", "cB" AS "grdb_cB" \
FROM "grandChild" WHERE ("cA", "cB") IN grdb_base
"""])
}
// Request with avoided prefetch
do {
let request = Parent
.none()
.including(all: Parent.hasMany(Child.self)
.including(all: Child.hasMany(GrandChild.self)))
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "parent" WHERE 0 ORDER BY "parentA", "parentB"
"""])
}
do {
let request = Parent
.including(all: Parent.hasMany(Child.self)
.none()
.including(all: Child.hasMany(GrandChild.self)))
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "parent" ORDER BY "parentA", "parentB"
""",
"""
WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \
FROM "child" \
WHERE 0 AND (("pA", "pB") IN grdb_base)
"""])
}
// Request with filters
do {
let request = Parent
.including(all: Parent.hasMany(Child.self)
.including(all: Child.hasMany(GrandChild.self)
.filter(Column("name") == "dog"))
.filter(Column("name") == "blue"))
.filter(Column("name") == "foo")
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "parent" WHERE "name" = 'foo' ORDER BY "parentA", "parentB"
""",
"""
WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "name" = 'foo') \
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \
FROM "child" WHERE ("name" = 'blue') AND (("pA", "pB") IN grdb_base)
""",
"""
WITH "grdb_base" AS (\
WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "name" = 'foo') \
SELECT "childA", "childB" FROM "child" \
WHERE ("name" = 'blue') AND (("pA", "pB") IN grdb_base)\
) \
SELECT *, "cA" AS "grdb_cA", "cB" AS "grdb_cB" \
FROM "grandChild" \
WHERE ("name" = 'dog') AND (("cA", "cB") IN grdb_base)
"""])
}
}
}
func testIncludingAllHasManyIncludingRequiredOrOptionalHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in