diff --git a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift index a5833c7c0..435d76725 100644 --- a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift @@ -74,20 +74,15 @@ public struct BelongsToAssociation: AssociationToOne { } init( - from originTable: String, to destinationRelation: SQLRelation, key: String?, using foreignKey: ForeignKey?) { let destinationTable = destinationRelation.source.tableName - let foreignKeyRequest = SQLForeignKeyRequest( - originTable: originTable, + let foreignKeyCondition = SQLForeignKeyCondition( destinationTable: destinationTable, - foreignKey: foreignKey) - - let condition = SQLAssociationCondition.foreignKey( - request: foreignKeyRequest, + foreignKey: foreignKey, originIsLeft: true) let associationKey: SQLAssociationKey @@ -99,7 +94,7 @@ public struct BelongsToAssociation: AssociationToOne { _sqlAssociation = _SQLAssociation( key: associationKey, - condition: condition, + condition: .foreignKey(foreignKeyCondition), relation: destinationRelation, cardinality: .toOne) } diff --git a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift index 8f21a823b..ad74dfbda 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift @@ -74,20 +74,15 @@ public struct HasManyAssociation: AssociationToMany { } init( - from originTable: String, to destinationRelation: SQLRelation, key: String?, using foreignKey: ForeignKey?) { let destinationTable = destinationRelation.source.tableName - let foreignKeyRequest = SQLForeignKeyRequest( - originTable: destinationTable, - destinationTable: originTable, - foreignKey: foreignKey) - - let condition = SQLAssociationCondition.foreignKey( - request: foreignKeyRequest, + let foreignKeyCondition = SQLForeignKeyCondition( + destinationTable: destinationTable, + foreignKey: foreignKey, originIsLeft: false) let associationKey: SQLAssociationKey @@ -99,7 +94,7 @@ public struct HasManyAssociation: AssociationToMany { _sqlAssociation = _SQLAssociation( key: associationKey, - condition: condition, + condition: .foreignKey(foreignKeyCondition), relation: destinationRelation, cardinality: .toMany) } diff --git a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift index 94f827e05..020b34b9f 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift @@ -76,20 +76,15 @@ public struct HasOneAssociation: AssociationToOne { } init( - from originTable: String, to destinationRelation: SQLRelation, key: String?, using foreignKey: ForeignKey?) { let destinationTable = destinationRelation.source.tableName - let foreignKeyRequest = SQLForeignKeyRequest( - originTable: destinationTable, - destinationTable: originTable, - foreignKey: foreignKey) - - let condition = SQLAssociationCondition.foreignKey( - request: foreignKeyRequest, + let foreignKeyCondition = SQLForeignKeyCondition( + destinationTable: destinationTable, + foreignKey: foreignKey, originIsLeft: false) let associationKey: SQLAssociationKey @@ -101,7 +96,7 @@ public struct HasOneAssociation: AssociationToOne { _sqlAssociation = _SQLAssociation( key: associationKey, - condition: condition, + condition: .foreignKey(foreignKeyCondition), relation: destinationRelation, cardinality: .toOne) } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 2c8fc9387..18c0d9132 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -56,7 +56,7 @@ extension QueryInterfaceRequest: FetchRequest { if associations.isEmpty == false { // Eager loading of prefetched associations preparedRequest = preparedRequest.with(\.supplementaryFetch) { db, rows in - try prefetch(db, associations: associations, into: rows, from: self) + try prefetch(db, associations: associations, from: self, into: rows) } } return preparedRequest @@ -539,8 +539,8 @@ public func /= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign private func prefetch( _ db: Database, associations: [_SQLAssociation], - into baseRows: [Row], - from baseRequest: QueryInterfaceRequest) throws + from baseRequest: QueryInterfaceRequest, + into baseRows: [Row]) throws { guard let firstBaseRow = baseRows.first else { // No rows -> no prefetch @@ -554,10 +554,9 @@ private func prefetch( // are not prefetched with including(all:) fatalError("Not implemented: prefetch association without any foreign key") - case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): - let pivotMapping = try foreignKeyRequest - .fetchForeignKeyMapping(db) - .joinMapping(originIsLeft: originIsLeft) + case let .foreignKey(pivotForeignKey): + let originTable = baseRequest.query.relation.source.tableName + let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable) let pivotColumns = pivotMapping.map(\.right) let leftColumns = pivotMapping.map(\.left) @@ -703,7 +702,12 @@ func makePrefetchRequest( // CAUTION: Keep this code in sync with prefetch(_:associations:in:) /// Returns the region of prefetched associations -func prefetchedRegion(_ db: Database, associations: [_SQLAssociation]) throws -> DatabaseRegion { +func prefetchedRegion( + _ db: Database, + associations: [_SQLAssociation], + from originTable: String) +throws -> DatabaseRegion +{ try associations.reduce(into: DatabaseRegion()) { (region, association) in switch association.pivot.condition { case .expression: @@ -711,10 +715,8 @@ func prefetchedRegion(_ db: Database, associations: [_SQLAssociation]) throws -> // are not prefetched with including(all:) fatalError("Not implemented: prefetch association without any foreign key") - case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): - let pivotMapping = try foreignKeyRequest - .fetchForeignKeyMapping(db) - .joinMapping(originIsLeft: originIsLeft) + case let .foreignKey(pivotForeignKey): + let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable) let prefetchRegion = try prefetchedRegion(db, association: association, pivotMapping: pivotMapping) region.formUnion(prefetchRegion) } diff --git a/GRDB/QueryInterface/SQL/SQLAssociation.swift b/GRDB/QueryInterface/SQL/SQLAssociation.swift index 75c065f85..3e6585cf1 100644 --- a/GRDB/QueryInterface/SQL/SQLAssociation.swift +++ b/GRDB/QueryInterface/SQL/SQLAssociation.swift @@ -130,7 +130,7 @@ public struct _SQLAssociation { return SQLAssociationStep( key: key, - condition: nextStep.condition.reversed, + condition: nextStep.condition.reversed(to: step.relation.source.tableName), relation: relation, cardinality: .toOne) }) diff --git a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift index 46725c635..7940b0484 100644 --- a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift +++ b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift @@ -88,6 +88,29 @@ typealias JoinMapping = [(left: String, right: String)] extension ForeignKeyMapping { /// Orient the foreign key mapping for a SQL join. + /// + /// - parameter originIsLeft: Whether the table at the origin of a + /// foreign key is on the left of a JOIN clause. + /// + /// For example, the two requests below use the same + /// `ForeignKeyMapping` from `book.authorID` (origin of the foreign key) + /// to `author.id` (destination). + /// + /// In the first request, the book origin is on the left of the + /// join clause: + /// + /// // SELECT book.*, author.* + /// // FROM book + /// // JOIN author ON author.id = book.authorID + /// Book.including(required: Book.author) + /// + /// In the second request, the book origin is on the right of the + /// join clause: + /// + /// // SELECT author.*, book.* + /// // FROM author + /// // JOIN book ON book.authorID = author.id + /// Author.including(required: Author.books) func joinMapping(originIsLeft: Bool) -> JoinMapping { if originIsLeft { return map { (left: $0.origin, right: $0.destination) } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 2dd137df2..fb0578d1e 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -539,27 +539,7 @@ extension SQLRelation { /// author.request(for: Author.books) enum SQLAssociationCondition { /// A 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`. - /// - /// The origin table `book` is on the left of the JOIN operator for - /// the BelongsTo association: - /// - /// -- Book.including(required: Book.author) - /// SELECT ... FROM book JOIN author ON author.id = book.authorId - /// ~~~~~~~~~~~~~~~~~~~~~~~~~ - /// - /// The origin table `book`is on the right of the JOIN operator for - /// the HasMany and HasOne associations: - /// - /// -- Author.including(required: Author.books) - /// SELECT ... FROM author JOIN book ON author.id = book.authorId - /// ~~~~~~~~~~~~~~~~~~~~~~~~~ - case foreignKey(request: SQLForeignKeyRequest, originIsLeft: Bool) + case foreignKey(SQLForeignKeyCondition) /// A condition based on a function that returns an expression. /// @@ -581,14 +561,96 @@ enum SQLAssociationCondition { /// in any way. static let none = expression({ _, _ in true }) - var reversed: SQLAssociationCondition { + func reversed(to destinationTable: String) -> SQLAssociationCondition { switch self { - case let .foreignKey(request: request, originIsLeft: originIsLeft): - return .foreignKey(request: request, originIsLeft: !originIsLeft) + case let .foreignKey(foreignKey): + return .foreignKey(foreignKey.reversed(to: destinationTable)) case let .expression(condition): return .expression { condition($1, $0) } } } + + func joinExpressions( + _ db: Database, + leftAlias: TableAlias, + rightAlias: TableAlias) + throws -> [SQLExpression] + { + switch self { + case let .expression(condition): + return [condition(leftAlias, rightAlias).sqlExpression] + case let .foreignKey(foreignKey): + return try foreignKey + .joinMapping(db, from: leftAlias.tableName) + .joinExpressions(leftAlias: leftAlias, rightAlias: rightAlias) + } + } +} + +/// An association condition based on a foreign key. +struct SQLForeignKeyCondition: Equatable { + /// The destination table of an association. + /// + /// In `Author.hasMany(Book.self)`, the destination is `book`. + var destinationTable: String + + /// A user-provided foreign key. When nil, we introspect the database in + /// order to look for a foreign key in the schema. + var foreignKey: ForeignKey? + + /// `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`. + /// + /// The origin table `book` is on the left of the JOIN operator for + /// the `BelongsTo` association: + /// + /// -- Book.including(required: Book.author) + /// SELECT ... FROM book JOIN author ON author.id = book.authorId + /// ~~~~ ~~~~ + /// + /// The origin table `book`is on the right of the JOIN operator for + /// the `HasMany` and `HasOne` associations: + /// + /// -- Author.including(required: Author.books) + /// SELECT ... FROM author JOIN book ON author.id = book.authorId + /// ~~~~ ~~~~ + /// + /// See also `ForeignKeyMapping.joinMapping(originIsLeft:)` + var originIsLeft: Bool + + func reversed(to destinationTable: String) -> SQLForeignKeyCondition { + SQLForeignKeyCondition( + destinationTable: destinationTable, + foreignKey: foreignKey, + originIsLeft: !originIsLeft) + } + + /// Turns the foreign key condition into a `JoinMapping` that can feed an + /// SQL JOIN clause. + func joinMapping(_ db: Database, from originTable: String) throws -> JoinMapping { + try foreignKeyRequest(from: originTable) + .fetchForeignKeyMapping(db) + .joinMapping(originIsLeft: originIsLeft) + } + + private func foreignKeyRequest(from originTable: String) -> SQLForeignKeyRequest { + // Convert association destination/origin to + // foreign key destination/origin. + if originIsLeft { + return SQLForeignKeyRequest( + originTable: originTable, + destinationTable: destinationTable, + foreignKey: foreignKey) + } else { + return SQLForeignKeyRequest( + originTable: destinationTable, + destinationTable: originTable, + foreignKey: foreignKey) + } + } } extension JoinMapping { @@ -661,11 +723,15 @@ extension JoinMapping { /// /// - parameter leftAlias: A TableAlias for the table on the left of the /// JOIN operator. + /// - parameter rightAlias: A TableAlias for the table on the right 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] { + func joinExpressions(leftAlias: TableAlias, rightAlias: TableAlias) -> [SQLExpression] { map { - Column($0.right) == SQLQualifiedColumn($0.left, alias: leftAlias) + let right = SQLQualifiedColumn($0.right, alias: rightAlias) + let left = SQLQualifiedColumn($0.left, alias: leftAlias) + return right == left } } } @@ -793,8 +859,8 @@ extension SQLSource { extension SQLAssociationCondition { func merged(with other: SQLAssociationCondition) -> Self? { switch (self, other) { - case let (.foreignKey(lr, lo), .foreignKey(rr, ro)): - if lr == rr && lo == ro { + case let (.foreignKey(lhs), .foreignKey(rhs)): + if lhs == rhs { return self } else { // can't merge diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 27867bbbc..18c6a2767 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -180,7 +180,11 @@ struct SQLQueryGenerator: Refinable { // Note that the request `parent.none().including(all: children)` is // different. Since `parent.none()` is provably empty, its region // is empty, and we thus avoid this code branch. - try statement.databaseRegion.formUnion(prefetchedRegion(db, associations: prefetchedAssociations)) + let region = try prefetchedRegion( + db, + associations: prefetchedAssociations, + from: relation.source.tableName) + statement.databaseRegion.formUnion(region) } return statement @@ -765,31 +769,24 @@ private struct SQLQualifiedJoin: Refinable { // JOIN table... var sql = try "\(kind.rawValue) \(relation.source.sql(context))" - let rightAlias = relation.source.alias // ... ON - var joinExpressions: [SQLExpression] - switch condition { - case let .expression(condition): - joinExpressions = [condition(leftAlias, rightAlias).sqlExpression] - - case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): - joinExpressions = try foreignKeyRequest - .fetchForeignKeyMapping(context.db) - .joinMapping(originIsLeft: originIsLeft) - .joinExpressions(leftAlias: leftAlias) - } + let rightAlias = relation.source.alias + var conditions = try condition.joinExpressions(context.db, + leftAlias: leftAlias, + rightAlias: rightAlias) - // ... ON ... AND - joinExpressions += try relation.filtersPromise.resolve(context.db) + // ... AND + conditions += try relation.filtersPromise + .resolve(context.db) + .map { $0._qualifiedExpression(with: rightAlias) } // Avoid generating on ON clause for trivially true conditions - joinExpressions = joinExpressions.filter { !$0._isTrue } + conditions = conditions.filter { !$0._isTrue } - if joinExpressions.isEmpty == false { - let joiningSQL = try joinExpressions + if conditions.isEmpty == false { + let joiningSQL = try conditions .joined(operator: .and) - ._qualifiedExpression(with: rightAlias) ._expressionSQL(context, wrappedInParenthesis: false) sql += " ON \(joiningSQL)" } diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index a4df01e9f..897c27bee 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -63,7 +63,6 @@ extension TableRecord { where Destination: TableRecord { BelongsToAssociation( - from: databaseTableName, to: Destination.relationForAll, key: key, using: foreignKey) @@ -133,7 +132,6 @@ extension TableRecord { where Destination: TableRecord { HasManyAssociation( - from: databaseTableName, to: Destination.relationForAll, key: key, using: foreignKey) @@ -285,7 +283,6 @@ extension TableRecord { where Destination: TableRecord { HasOneAssociation( - from: databaseTableName, to: Destination.relationForAll, key: key, using: foreignKey) @@ -432,7 +429,7 @@ extension TableRecord { /// static let authorForeignKey = ForeignKey(["authorId"], to: ["id"])) /// static let author = belongsTo(Person.self, using: authorForeignKey) /// } -public struct ForeignKey { +public struct ForeignKey: Equatable { var originColumns: [String] var destinationColumns: [String]? @@ -506,15 +503,14 @@ extension TableRecord where Self: EncodableRecord { // TODO: find a use case? fatalError("Not implemented: request association without any foreign key") - case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): + case let .foreignKey(foreignKey): 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) + try foreignKey + .joinMapping(db, from: Self.databaseTableName) .joinExpression(leftRows: [PersistenceContainer(db, self)]) } })