From 268a45a635d53f87483951d0bc588a370a7b6615 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 2 Jul 2020 08:29:49 +0200 Subject: [PATCH] Prepare for different kinds of SQLAssociationCondition --- .../Association/BelongsToAssociation.swift | 4 +- .../Association/HasManyAssociation.swift | 4 +- .../Association/HasOneAssociation.swift | 4 +- .../Request/QueryInterfaceRequest.swift | 73 ++++++++++++------ GRDB/QueryInterface/SQL/SQLAssociation.swift | 69 ++--------------- .../SQL/SQLForeignKeyRequest.swift | 24 +++++- GRDB/QueryInterface/SQL/SQLRelation.swift | 76 ++++++++----------- .../SQLGeneration/SQLQueryGenerator.swift | 17 +++-- .../TableRecord+Association.swift | 32 +++++--- 9 files changed, 148 insertions(+), 155 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift index c46840432..3cf1df3ea 100644 --- a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift @@ -82,8 +82,8 @@ public struct BelongsToAssociation: destinationTable: Origin.databaseTableName, foreignKey: foreignKey) - let condition = SQLAssociationCondition( - foreignKeyRequest: foreignKeyRequest, + let condition = SQLAssociationCondition.foreignKey( + request: foreignKeyRequest, originIsLeft: false) let associationKey: SQLAssociationKey diff --git a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift index 5b94c4f51..8ccfe8cb4 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift @@ -84,8 +84,8 @@ public struct HasOneAssociation: destinationTable: Origin.databaseTableName, foreignKey: foreignKey) - let condition = SQLAssociationCondition( - foreignKeyRequest: foreignKeyRequest, + let condition = SQLAssociationCondition.foreignKey( + request: foreignKeyRequest, originIsLeft: false) let associationKey: SQLAssociationKey diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index fb763ed10..8a3a12205 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -475,10 +475,11 @@ private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [ // CAUTION: Keep this code in sync with prefetchedRegion(_:_:) for association in associations { - let pivotMappings = try association.pivot.condition.columnMappings(db) + let prefetchedGroups: [[DatabaseValue] : [Row]] + let groupingIndexes: [Int] - let prefetchedRows: [[DatabaseValue] : [Row]] - do { + switch association.pivot.condition { + case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): // Annotate prefetched rows with pivot columns, so that we can // group them. // @@ -500,22 +501,35 @@ private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [ // // FROM book // // WHERE authorId IN (1, 2, 3) // Author.including(all: Author.books) - let pivotColumns = pivotMappings.map(\.right) + let pivotMapping = try foreignKeyRequest + .fetchForeignKeyMapping(db) + .joinMapping(originIsLeft: originIsLeft) + let pivotFilter = pivotMapping.joinExpression(leftRows: rows) + let pivotColumns = pivotMapping.map(\.right) let pivotAlias = TableAlias() + let prefetchedRelation = association - .map(\.pivot.relation, { $0.qualified(with: pivotAlias) }) - .destinationRelation(fromOriginRows: { _ in rows }) + .map(\.pivot.relation, { pivotRelation in + pivotRelation + .qualified(with: pivotAlias) + .filter { _ in pivotFilter } + }) + .destinationRelation() + // Annotate with the pivot columns that allow grouping .annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") }) - prefetchedRows = try QueryInterfaceRequest(relation: prefetchedRelation) + + prefetchedGroups = try QueryInterfaceRequest(relation: prefetchedRelation) .fetchAll(db) .grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" }) - // TODO: can we remove those grdb_ columns now that grouping has been done? + // TODO: can we remove those grdb_ columns from user's sight, + // now that grouping has been done? + + groupingIndexes = firstRow.indexes(forColumns: pivotMapping.map(\.left)) } - let groupingIndexes = firstRow.indexes(forColumns: pivotMappings.map(\.left)) for row in rows { let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) } - let prefetchedRows = prefetchedRows[groupingKey, default: []] + let prefetchedRows = prefetchedGroups[groupingKey, default: []] row.prefetchedRows.setRows(prefetchedRows, forKeyPath: association.keyPath) } } @@ -525,24 +539,33 @@ private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [ func prefetchedRegion(_ db: Database, associations: [SQLAssociation]) throws -> DatabaseRegion { try associations.reduce(into: DatabaseRegion()) { (region, association) in // 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 + let prefetchedRegion: DatabaseRegion + + switch association.pivot.condition { + case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): + // Filter the pivot on 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) - .databaseRegion // contains region of nested associations + let pivotFilter = try foreignKeyRequest + .fetchForeignKeyMapping(db) + .joinMapping(originIsLeft: originIsLeft) + .joinExpression(leftRows: [NullRow()]) + + let prefetchedRelation = association + .map(\.pivot.relation, { pivotRelation in + pivotRelation.filter { _ in pivotFilter } + }) + .destinationRelation() + + let prefetchedQuery = SQLQuery(relation: prefetchedRelation) + + // Union prefetched region + prefetchedRegion = try SQLQueryGenerator(query: prefetchedQuery) + .makeSelectStatement(db) + .databaseRegion // contains region of nested associations + } region.formUnion(prefetchedRegion) } } diff --git a/GRDB/QueryInterface/SQL/SQLAssociation.swift b/GRDB/QueryInterface/SQL/SQLAssociation.swift index bf2064db7..e2184c060 100644 --- a/GRDB/QueryInterface/SQL/SQLAssociation.swift +++ b/GRDB/QueryInterface/SQL/SQLAssociation.swift @@ -95,68 +95,14 @@ public /* TODO: internal */ struct SQLAssociation { SQLAssociation(steps: other.steps + steps) } - /// Given an origin alias and rows, returns the destination of the - /// association as a relation. + /// Returns the destination of the association, reversing the association + /// up to the pivot. /// - /// This method provides support for association methods such - /// as `request(for:)`: - /// - /// struct Destination: TableRecord { } - /// struct Origin: TableRecord, EncodableRecord { - /// static let destinations = hasMany(Destination.self) - /// var destinations: QueryInterface { - /// return request(for: Origin.destinations) - /// } - /// } - /// - /// // SELECT destination.* - /// // FROM destination - /// // WHERE destination.originId = 1 - /// let origin = Origin(id: 1) - /// let destinations = origin.destinations.fetchAll(db) - /// - /// At low-level, this gives: - /// - /// let origin = Origin(id: 1) - /// let originAlias = TableAlias(tableName: Origin.databaseTableName) - /// let sqlAssociation = Origin.destination.sqlAssociation - /// let destinationRelation = sqlAssociation.destinationRelation( - /// from: originAlias, - /// rows: { db in try [Row(PersistenceContainer(db, origin))] }) - /// let query = SQLQuery(relation: destinationRelation) - /// let generator = SQLQueryGenerator(query) - /// let statement, _ = try generator.prepare(db) - /// print(statement.sql) - /// // SELECT destination.* - /// // FROM destination - /// // WHERE destination.originId = 1 - /// - /// This method works for simple direct associations such as BelongsTo or - /// HasMany in the above examples, but also for indirect associations such - /// as HasManyThrough, which have any number of pivot relations between the - /// origin and the destination. - func destinationRelation( - fromOriginRows originRows: @escaping (Database) throws -> [Row]) - -> SQLRelation - where Row: ColumnAddressable - { - // Filter the pivot: `pivot.originId = 123` or `pivot.originId IN (1, 2, 3)` - let pivot = self.pivot - let filteredPivotRelation = pivot.relation.filter { db in - try pivot.condition.filteringExpression(db, leftRows: originRows(db)) - } - + /// This method feeds `TableRecord.request(for:)`, and allows + /// `including(all:)` to prefetch associated records. + func destinationRelation() -> SQLRelation { if steps.count == 1 { - // This is a direct join from origin to destination, without - // intermediate step. - // - // SELECT destination.* - // FROM destination - // WHERE destination.originId = 1 - // - // let association = Origin.hasMany(Destination.self) - // Origin(id: 1).request(for: association) - return filteredPivotRelation + return destination.relation } // This is an indirect join from origin to destination, through @@ -171,8 +117,7 @@ public /* TODO: internal */ struct SQLAssociation { // through: Origin.hasMany(Pivot.self), // via: Pivot.belongsTo(Destination.self)) // Origin(id: 1).request(for: association) - let filteredSteps = steps.with(\.[0].relation, filteredPivotRelation) - let reversedSteps = zip(filteredSteps, filteredSteps.dropFirst()) + let reversedSteps = zip(steps, steps.dropFirst()) .map({ (step, nextStep) -> SQLAssociationStep in // Intermediate steps are not selected, and including(all:) // children are useless: diff --git a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift index 18ffe5187..46725c635 100644 --- a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift +++ b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift @@ -1,10 +1,11 @@ /// SQLForeignKeyRequest looks for the foreign keys associations need to /// join tables. /// -/// Mappings come from foreign keys, when they exist in the database schema. +/// Columns mapping come from foreign keys, when they exist in the +/// database schema. /// /// When the schema does not define any foreign key, we can still infer complete -/// mappings from partial information and primary keys. +/// mapping from partial information and primary keys. struct SQLForeignKeyRequest: Equatable { let originTable: String let destinationTable: String @@ -20,7 +21,7 @@ struct SQLForeignKeyRequest: Equatable { } /// The (origin, destination) column pairs that join a left table to a right table. - func fetchMapping(_ db: Database) throws -> [(origin: String, destination: String)] { + func fetchForeignKeyMapping(_ db: Database) throws -> ForeignKeyMapping { if let originColumns = originColumns, let destinationColumns = destinationColumns { // Total information: no need to query the database schema. GRDBPrecondition(originColumns.count == destinationColumns.count, "Number of columns don't match") @@ -78,3 +79,20 @@ struct SQLForeignKeyRequest: Equatable { fatalError("Could not infer foreign key from \(originTable) to \(destinationTable)") } } + +// Foreign key columns mapping +typealias ForeignKeyMapping = [(origin: String, destination: String)] + +// Join columns mapping +typealias JoinMapping = [(left: String, right: String)] + +extension ForeignKeyMapping { + /// Orient the foreign key mapping for a SQL join. + func joinMapping(originIsLeft: Bool) -> JoinMapping { + if originIsLeft { + return map { (left: $0.origin, right: $0.destination) } + } else { + return map { (left: $0.destination, right: $0.origin) } + } + } +} diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 2f19e5d3b..2f05c9912 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -523,12 +523,11 @@ extension SQLRelation { /// let request4 = Book /// .joining(required: Book.author.filter(condition1)) /// .including(optional: Book.author.filter(condition2)) -struct SQLAssociationCondition: Equatable { - /// Definition of a foreign key - var foreignKeyRequest: SQLForeignKeyRequest - - /// True if the table at the origin of the foreign key is on the left of - /// the sql JOIN operator. +enum SQLAssociationCondition: Equatable { + /// Condition based on a foreign key + /// + /// originIsLeft is true if the table at the origin of the foreign key is on + /// the left of the sql JOIN operator. /// /// Let's consider the `book.authorId -> author.id` foreign key. /// Its origin table is `book`. @@ -544,60 +543,33 @@ struct SQLAssociationCondition: Equatable { /// /// -- Author.including(required: Author.books) /// SELECT ... FROM author JOIN book ON author.id = book.authorId - var originIsLeft: Bool + case foreignKey(request: SQLForeignKeyRequest, originIsLeft: Bool) var reversed: SQLAssociationCondition { - SQLAssociationCondition( - foreignKeyRequest: foreignKeyRequest, - originIsLeft: !originIsLeft) - } - - /// Orient foreignKey according to the originIsLeft flag - func columnMappings(_ db: Database) throws -> [(left: String, right: String)] { - let foreignKeyMapping = try foreignKeyRequest.fetchMapping(db) - if originIsLeft { - return foreignKeyMapping.map { (left: $0.origin, right: $0.destination) } - } else { - return foreignKeyMapping.map { (left: $0.destination, right: $0.origin) } + switch self { + case let .foreignKey(request: request, originIsLeft: originIsLeft): + return .foreignKey(request: request, originIsLeft: !originIsLeft) } } - - /// Resolves the condition into SQL expressions which involve both left - /// and right tables. - /// - /// SELECT * FROM left JOIN right ON (right.a = left.b) - /// <----------------> - /// - /// - parameter db: A database connection. - /// - parameter leftAlias: A TableAlias for the table on the left of the - /// JOIN operator. - /// - Returns: An array of SQL expression that should be joined with - /// the AND operator and qualified with the right table. - func expressions(_ db: Database, leftAlias: TableAlias) throws -> [SQLExpression] { - try columnMappings(db).map { - Column($0.right) == QualifiedColumn($0.left, alias: leftAlias) - } - } - +} + +extension JoinMapping { /// Resolves the condition into an SQL expression which involves only the - /// right table. + /// right table, and feeds left columns from `leftRows`. /// - /// Given `right.a = left.b`, returns `right.a = 1` or + /// For example, given `[(left: "a", right: "b")]`, returns `right.a = 1` or /// `right.a IN (1, 2, 3)`. - func filteringExpression(_ db: Database, leftRows: [Row]) throws -> SQLExpression { + func joinExpression(leftRows: [Row]) -> SQLExpression { guard let firstLeftRow = leftRows.first else { // Degenerate case: there is no row to attach return false.sqlExpression } - // The (left, right) column mapping pairs - let columnMappings = try self.columnMappings(db) - // We assume that all rows have the same layout, and that addressing // rows by index is faster than addressing them by column name. // So we use the first left row in order to convert left column names // into row indexes. - let mappings: [(leftIndex: Row.ColumnIndex, rightColumn: Column)] = columnMappings.map { mapping in + let mappings: [(leftIndex: Row.ColumnIndex, rightColumn: Column)] = map { mapping in guard let leftIndex = firstLeftRow.index(forColumn: mapping.left) else { fatalError("Missing column: \(mapping.left)") } @@ -639,6 +611,22 @@ struct SQLAssociationCondition: Equatable { .joined(operator: .or) } } + + /// Resolves the condition into SQL expressions which involve both left + /// and right tables. + /// + /// SELECT * FROM left JOIN right ON (right.a = left.b) + /// <----------------> + /// + /// - parameter leftAlias: A TableAlias for the table on the left of the + /// JOIN operator. + /// - Returns: An array of SQL expression that should be joined with + /// the AND operator and qualified with the right table. + func joinExpressions(leftAlias: TableAlias) -> [SQLExpression] { + map { + Column($0.right) == QualifiedColumn($0.left, alias: leftAlias) + } + } } /// A protocol for row-like containers diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 296124551..f9d899ba1 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -865,14 +865,21 @@ private struct SQLQualifiedJoin: Refinable { } // ... ON AND - var filters = try condition.expressions(context.db, leftAlias: leftAlias) - filters += try relation.filtersPromise.resolve(context.db) - if filters.isEmpty == false { - let filterSQL = try filters + var joinExpressions: [SQLExpression] + switch condition { + case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): + joinExpressions = try foreignKeyRequest + .fetchForeignKeyMapping(context.db) + .joinMapping(originIsLeft: originIsLeft) + .joinExpressions(leftAlias: leftAlias) + } + joinExpressions += try relation.filtersPromise.resolve(context.db) + if joinExpressions.isEmpty == false { + let joiningSQL = try joinExpressions .joined(operator: .and) .qualifiedExpression(with: rightAlias) .expressionSQL(context, wrappedInParenthesis: false) - sql += " ON \(filterSQL)" + sql += " ON \(joiningSQL)" } for (_, join) in relation.joins { diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 515548e70..a9713e549 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -1,6 +1,6 @@ extension TableRecord { - /// Creates a "Belongs To" association between Self and the - /// destination type. + /// Creates a "Belongs To" association between Self and the destination + /// type, based on a database foreign key. /// /// struct Author: TableRecord { ... } /// struct Book: TableRecord { @@ -64,8 +64,8 @@ extension TableRecord { BelongsToAssociation(key: key, using: foreignKey) } - /// Creates a "Has many" association between Self and the - /// destination type. + /// Creates a "Has many" association between Self and the destination type, + /// based on a database foreign key. /// /// struct Book: TableRecord { ... } /// struct Author: TableRecord { @@ -211,8 +211,8 @@ extension TableRecord { } } - /// Creates a "Has one" association between Self and the - /// destination type. + /// Creates a "Has one" association between Self and the destination type, + /// based on a database foreign key. /// /// struct Demographics: TableRecord { ... } /// struct Country: TableRecord { @@ -486,10 +486,22 @@ extension TableRecord where Self: EncodableRecord { -> QueryInterfaceRequest where A.OriginRowDecoder == Self { - let destinationRelation = association.sqlAssociation.destinationRelation(fromOriginRows: { db in - try [PersistenceContainer(db, self)] - }) - return QueryInterfaceRequest(relation: destinationRelation) + switch association.sqlAssociation.pivot.condition { + case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): + let destinationRelation = association + .sqlAssociation + .map(\.pivot.relation, { pivotRelation in + pivotRelation.filter { db in + // Filter the pivot on self + try foreignKeyRequest + .fetchForeignKeyMapping(db) + .joinMapping(originIsLeft: originIsLeft) + .joinExpression(leftRows: [PersistenceContainer(db, self)]) + } + }) + .destinationRelation() + return QueryInterfaceRequest(relation: destinationRelation) + } } }