Group prefetched rows

This commit is contained in:
Gwendal Roué committed 2019-05-04 22:29:07 +02:00
1 parent 217b7eee9f
commit 91ec3bada3
3 files changed
+28 -11

No files matched your search

@@ -119,8 +119,7 @@ extension TableRecord where Self: EncodableRecord {
let destinationRelation = association.sqlAssociation.destinationRelation(fromOriginRows: { db in
try [Row(PersistenceContainer(db, self))]
})
let query = SQLSelectQuery(relation: destinationRelation)
return QueryInterfaceRequest<A.RowDecoder>(query: query)
return QueryInterfaceRequest<A.RowDecoder>(relation: destinationRelation)
}
}
@@ -31,6 +31,14 @@
public struct QueryInterfaceRequest<T> {
var query: SQLSelectQuery
init(query: SQLSelectQuery) {
self.query = query
}
init(relation: SQLRelation) {
self.init(query: SQLSelectQuery(relation: relation))
}
@usableFromInline
var needsPrefetch: Bool {
return query.relation.needsPrefetch
@@ -375,8 +383,7 @@ extension TableRecord {
let relation = SQLRelation(
source: .table(tableName: databaseTableName, alias: nil),
selection: databaseSelection)
let query = SQLSelectQuery(relation: relation)
return QueryInterfaceRequest(query: query)
return QueryInterfaceRequest(relation: relation)
}
/// Creates a request which fetches no record.
+18 -7
View File
@@ -69,19 +69,30 @@ extension Row {
let prefetchedAssociations = query.relation.prefetchedAssociations()
for prefetchedAssociation in prefetchedAssociations {
let pivotAlias = TableAlias()
let pivotColumnMapping = try prefetchedAssociation.pivotCondition.columnMapping(db)
let pivotRightColumns = pivotColumnMapping.map { $0.right }
let groupingAlias = TableAlias()
let groupingColumns = try prefetchedAssociation.pivotCondition.columnMapping(db).map { $0.right }
let prefetchedRelation = prefetchedAssociation
.mapPivotRelation { $0.qualified(with: pivotAlias) }
.mapPivotRelation { $0.qualified(with: groupingAlias) }
.destinationRelation(fromOriginRows: { _ in rows })
.annotated(with: pivotRightColumns.map { pivotAlias[Column($0)].aliased("grdb_\($0)") })
let prefetchedQuery = SQLSelectQuery(relation: prefetchedRelation)
let prefetchedRequest = QueryInterfaceRequest<Row>(query: prefetchedQuery)
.annotated(with: groupingColumns.map { groupingAlias[Column($0)].aliased("grdb_\($0)") })
let prefetchedRequest = QueryInterfaceRequest<Row>(relation: prefetchedRelation)
let prefetchedRows = try prefetchedRequest.fetchAll(db)
let groupedRows = group(prefetchedRows, on: groupingColumns.map { "grdb_\($0)" })
}
return rows
}
/// - precondition: Columns all exist in all rows. All rows have the same
/// columnns, in the same order.
private static func group(_ rows: [Row], on columns: [String]) -> [[DatabaseValue]: [Row]] {
guard let firstRow = rows.first else {
return [:]
}
let indexes: [Int] = columns.map { firstRow.index(ofColumn: $0)! }
return Dictionary(grouping: rows, by: { row in
indexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
})
}
}
extension QueryInterfaceRequest where RowDecoder == Row {