This commit is contained in:
Gwendal Roué committed 2020-05-25 09:34:11 +02:00
1 parent 0929fe72b8
commit 2bb53026ef
2 files changed
+37 -35

No files matched your search

@@ -6,6 +6,8 @@ struct SQLQueryGenerator: Refinable {
private let havingExpressionsPromise: DatabasePromise<[SQLExpression]>
private let limit: SQLLimit?
private let singleResult: Bool
// For database region
private let prefetchedAssociations: [SQLAssociation]
/// Creates an SQL query generator.
///
@@ -57,6 +59,7 @@ struct SQLQueryGenerator: Refinable {
limit = query.limit
isDistinct = query.isDistinct
self.singleResult = singleResult
prefetchedAssociations = query.relation.prefetchedAssociations
}
func requestSQL(_ context: SQLGenerationContext) throws -> String {
@@ -155,6 +158,39 @@ struct SQLQueryGenerator: Refinable {
// Optimize databaseRegion
statement.selectedRegion = try optimizedSelectedRegion(db, statement.selectedRegion)
// Append region of prefetched associations
var fifo = prefetchedAssociations
while !fifo.isEmpty {
let association = fifo.removeFirst()
// Build the query for prefetched rows.
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
let pivotMappings = try association.pivot.condition.columnMappings(db)
let pivotColumns = pivotMappings.map(\.right)
let pivotAlias = TableAlias()
let prefetchedRelation = association
.map(\.pivot.relation, { $0.qualified(with: pivotAlias) })
// Use a `NullRow` 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
.destinationRelation(fromOriginRows: { _ in [NullRow()] })
.annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") })
let prefetchedQuery = SQLQuery(relation: prefetchedRelation)
// Union prefetched region
let prefetchedRegion = try SQLQueryGenerator(query: prefetchedQuery)
.makeSelectStatement(db)
.selectedRegion
statement.selectedRegion.formUnion(prefetchedRegion)
// Append nested prefetched associations (support for
// A.including(all: A.bs.including(all: B.cs))
fifo.append(contentsOf: prefetchedRelation.prefetchedAssociations)
}
return statement
}