From 33b40637a8fd265c37da21941b1899c05f9d1f67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Sep 2018 14:16:56 +0200 Subject: [PATCH] Merge associations --- .../Association/Association.swift | 48 +++++++++++---- .../Association/AssociationQuery.swift | 56 +++++++++++++++-- .../Association/AssociationRequest.swift | 6 +- .../Association/BelongsToAssociation.swift | 14 ++--- .../Association/ForeignKeyRequest.swift | 2 +- .../Association/HasManyAssociation.swift | 14 ++--- .../Association/HasOneAssociation.swift | 14 ++--- GRDB/QueryInterface/QueryInterfaceQuery.swift | 61 ++++++++++++++++--- .../QueryInterfaceRequest+Association.swift | 6 +- GRDB/Utils/OrderedDictionary.swift | 10 +++ .../AssociationParallelSQLTests.swift | 46 ++++++++++++++ 11 files changed, 219 insertions(+), 58 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 5d4e72dcf..2be63da26 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -52,7 +52,7 @@ public protocol Association: DerivableRequest { var request: AssociationRequest { get } /// :nodoc: - func joinCondition(_ db: Database) throws -> JoinCondition + var joinCondition: JoinCondition { get } /// :nodoc: func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> Self @@ -211,16 +211,39 @@ extension Association { } } -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// :nodoc: -public typealias JoinCondition = (_ leftAlias: TableAlias, _ rightAlias: TableAlias) -> SQLExpression? +///// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +///// :nodoc: +//public struct JoinCondition { +// var columnMapping: [(left: Column, right: Column)] +// +// func sqlExpression(leftAlias: TableAlias, rightAlias: TableAlias) -> SQLExpression? { +// return columnMapping +// .map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) } +// .joined(operator: .and) +// } +//} + +///// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +///// :nodoc: +//public typealias JoinCondition = (_ leftAlias: TableAlias, _ rightAlias: TableAlias) -> SQLExpression? /// Turns a ForeignKeyRequest into a JoinCondition -struct ForeignKeyJoinConditionRequest { +public struct JoinCondition: Equatable { var foreignKeyRequest: ForeignKeyRequest var originIsLeft: Bool - func fetch(_ db: Database) throws -> JoinCondition { +// func fetch(_ db: Database) throws -> JoinCondition { +// let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping +// let columnMapping: [(left: Column, right: Column)] +// if originIsLeft { +// columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) } +// } else { +// columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } +// } +// return JoinCondition(columnMapping: columnMapping) +// } + + func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression? { let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping let columnMapping: [(left: Column, right: Column)] if originIsLeft { @@ -228,11 +251,10 @@ struct ForeignKeyJoinConditionRequest { } else { columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } } - return { (leftAlias, rightAlias) in - return columnMapping - .map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) } - .joined(operator: .and) - } + + return columnMapping + .map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) } + .joined(operator: .and) } } @@ -296,7 +318,7 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { .filter { db in // Build a join condition: `association.recordId = record.id` // We still need to replace `record.id` with the actual record id. - guard let joinCondition = try self.joinCondition(db)(recordAlias, associationAlias) else { + guard let joinExpression = try self.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) else { fatalError("Can't request from record without join condition") } @@ -306,7 +328,7 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { let container = PersistenceContainer(record) // Replace `record.id` with 123 - return joinCondition.resolvedExpression(inContext: [recordAlias: container]) + return joinExpression.resolvedExpression(inContext: [recordAlias: container]) } // We just added a condition qualified with associationAlias. Don't diff --git a/GRDB/QueryInterface/Association/AssociationQuery.swift b/GRDB/QueryInterface/Association/AssociationQuery.swift index b42a0bd29..a7f882f95 100644 --- a/GRDB/QueryInterface/Association/AssociationQuery.swift +++ b/GRDB/QueryInterface/Association/AssociationQuery.swift @@ -59,12 +59,18 @@ extension AssociationQuery { return query } - func joining(_ join: AssociationJoin, forKey key: String) -> AssociationQuery { + func appendingJoin(_ join: AssociationJoin, forKey key: String) -> AssociationQuery { var query = self - guard query.joins[key] == nil else { - fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + if let existingJoin = query.joins[key] { + guard let mergedJoin = existingJoin.merged(with: join) else { + // can't merge + fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + } + query.joins.removeValue(forKey: key) + query.joins.append(value: mergedJoin, forKey: key) + } else { + query.joins.append(value: join, forKey: key) } - query.joins.append(value: join, forKey: key) return query } @@ -138,3 +144,45 @@ extension AssociationQuery { return (adapter: adapter.addingScopes(scopes), endIndex: endIndex) } } + +extension AssociationQuery { + /// Returns nil if queries can't be merged (conflict in source, joins...) + func merged(with other: AssociationQuery) -> AssociationQuery? { + guard let mergedSource = source.merged(with: other.source) else { + // can't merge + return nil + } + + let mergedFilterPromise = filterPromise.map { (db, expression) in + let otherExpression = try other.filterPromise.resolve(db) + let expressions = [expression, otherExpression].compactMap { $0 } + if expressions.isEmpty { + return nil + } + return expressions.joined(operator: .and) + } + + var mergedJoins: OrderedDictionary = [:] + for (key, join) in joins { + if let otherJoin = other.joins[key] { + guard let mergedJoin = join.merged(with: otherJoin) else { + // can't merge + return nil + } + mergedJoins.append(value: mergedJoin, forKey: key) + } else { + mergedJoins.append(value: join, forKey: key) + } + } + for (key, join) in other.joins where mergedJoins[key] == nil { + mergedJoins.append(value: join, forKey: key) + } + + return AssociationQuery( + source: mergedSource, + selection: other.selection, // possible conflict with self.selection here. + filterPromise: mergedFilterPromise, + ordering: other.ordering, // reorder + joins: mergedJoins) + } +} diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift index 6a5a80444..5eede5d33 100644 --- a/GRDB/QueryInterface/Association/AssociationRequest.swift +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -42,8 +42,8 @@ extension AssociationRequest { { let join = AssociationJoin( joinOperator: joinOperator, - query: association.request.query, - joinConditionPromise: DatabasePromise(association.joinCondition)) - return AssociationRequest(query: query.joining(join, forKey: association.key)) + joinCondition: association.joinCondition, + query: association.request.query) + return AssociationRequest(query: query.appendingJoin(join, forKey: association.key)) } } diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index 3b9fd882d..97b2bbaa8 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -59,8 +59,6 @@ /// /// See ForeignKey for more information. public struct BelongsToAssociation: Association { - fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest - /// :nodoc: public typealias OriginRowDecoder = Origin @@ -69,6 +67,9 @@ public struct BelongsToAssociation: Association { public var key: String + /// :nodoc: + public let joinCondition: JoinCondition + /// :nodoc: public var request: AssociationRequest @@ -78,11 +79,6 @@ public struct BelongsToAssociation: Association { return association } - /// :nodoc: - public func joinCondition(_ db: Database) throws -> JoinCondition { - return try joinConditionRequest.fetch(db) - } - /// :nodoc: public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> BelongsToAssociation { var association = self @@ -166,13 +162,13 @@ extension TableRecord { destinationTable: Destination.databaseTableName, foreignKey: foreignKey) - let joinConditionRequest = ForeignKeyJoinConditionRequest( + let joinCondition = JoinCondition( foreignKeyRequest: foreignKeyRequest, originIsLeft: true) return BelongsToAssociation( - joinConditionRequest: joinConditionRequest, key: key ?? Destination.databaseTableName, + joinCondition: joinCondition, request: AssociationRequest(Destination.all())) } } diff --git a/GRDB/QueryInterface/Association/ForeignKeyRequest.swift b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift index 077581950..268503c9d 100644 --- a/GRDB/QueryInterface/Association/ForeignKeyRequest.swift +++ b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift @@ -5,7 +5,7 @@ /// /// When the schema does not define any foreign key, we can still infer complete /// mappings from partial information and primary keys. -struct ForeignKeyRequest { +struct ForeignKeyRequest: Equatable { let originTable: String let destinationTable: String let originColumns: [String]? diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index 7e0fa6b72..e204058d6 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -59,8 +59,6 @@ /// /// See ForeignKey for more information. public struct HasManyAssociation: Association { - fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest - /// :nodoc: public typealias OriginRowDecoder = Origin @@ -69,6 +67,9 @@ public struct HasManyAssociation: Association { public var key: String + /// :nodoc: + public let joinCondition: JoinCondition + /// :nodoc: public var request: AssociationRequest @@ -78,11 +79,6 @@ public struct HasManyAssociation: Association { return association } - /// :nodoc: - public func joinCondition(_ db: Database) throws -> JoinCondition { - return try joinConditionRequest.fetch(db) - } - /// :nodoc: public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasManyAssociation { var association = self @@ -166,13 +162,13 @@ extension TableRecord { destinationTable: databaseTableName, foreignKey: foreignKey) - let joinConditionRequest = ForeignKeyJoinConditionRequest( + let joinCondition = JoinCondition( foreignKeyRequest: foreignKeyRequest, originIsLeft: false) return HasManyAssociation( - joinConditionRequest: joinConditionRequest, key: key ?? Destination.databaseTableName, + joinCondition: joinCondition, request: AssociationRequest(Destination.all())) } } diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index 58bb5eea6..e795ae494 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -61,8 +61,6 @@ /// /// See ForeignKey for more information. public struct HasOneAssociation : Association { - fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest - /// :nodoc: public typealias OriginRowDecoder = Origin @@ -71,6 +69,9 @@ public struct HasOneAssociation : Association { public var key: String + /// :nodoc: + public let joinCondition: JoinCondition + /// :nodoc: public var request: AssociationRequest @@ -80,11 +81,6 @@ public struct HasOneAssociation : Association { return association } - /// :nodoc: - public func joinCondition(_ db: Database) throws -> JoinCondition { - return try joinConditionRequest.fetch(db) - } - /// :nodoc: public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasOneAssociation { var association = self @@ -168,13 +164,13 @@ extension TableRecord { destinationTable: databaseTableName, foreignKey: foreignKey) - let joinConditionRequest = ForeignKeyJoinConditionRequest( + let joinCondition = JoinCondition( foreignKeyRequest: foreignKeyRequest, originIsLeft: false) return HasOneAssociation( - joinConditionRequest: joinConditionRequest, key: key ?? Destination.databaseTableName, + joinCondition: joinCondition, request: AssociationRequest(Destination.all())) } } diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 207e2282a..a6aa5e458 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -130,12 +130,18 @@ extension QueryInterfaceQuery { return query } - func joining(_ join: AssociationJoin, forKey key: String) -> QueryInterfaceQuery { + func appendingJoin(_ join: AssociationJoin, forKey key: String) -> QueryInterfaceQuery { var query = self - guard query.joins[key] == nil else { - fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + if let existingJoin = query.joins[key] { + guard let mergedJoin = existingJoin.merged(with: join) else { + // can't merge + fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + } + query.joins.removeValue(forKey: key) + query.joins.append(value: mergedJoin, forKey: key) + } else { + query.joins.append(value: join, forKey: key) } - query.joins.append(value: join, forKey: key) return query } @@ -460,9 +466,9 @@ enum AssociationJoinOperator { struct AssociationJoin { var joinOperator: AssociationJoinOperator + var joinCondition: JoinCondition var query: AssociationQuery - var joinConditionPromise: DatabasePromise - + var finalizedJoin: AssociationJoin { var join = self join.query = query.finalizedQuery @@ -505,7 +511,7 @@ struct AssociationJoin { let rightAlias = query.alias! let filters = try [ - joinConditionPromise.resolve(db)(leftAlias, rightAlias), + joinCondition.sqlExpression(db, leftAlias: leftAlias, rightAlias: rightAlias), query.filterPromise.resolve(db) ].compactMap { $0 } if !filters.isEmpty { @@ -518,6 +524,32 @@ struct AssociationJoin { return sql } + + /// Returns nil if joins can't be merged (conflict in condition, query...) + func merged(with other: AssociationJoin) -> AssociationJoin? { + guard joinCondition == other.joinCondition else { + // can't merge + return nil + } + + guard let mergedQuery = query.merged(with: other.query) else { + // can't merge + return nil + } + + let mergedJoinOperator: AssociationJoinOperator + switch (joinOperator, other.joinOperator) { + case (.required, _), (_, .required): + mergedJoinOperator = .required + default: + mergedJoinOperator = .optional + } + + return AssociationJoin( + joinOperator: mergedJoinOperator, + joinCondition: joinCondition, + query: mergedQuery) + } } // MARK: - SQLSource @@ -562,6 +594,21 @@ enum SQLSource { return .query(query.qualified(with: alias)) } } + + /// Returns nil if sources can't be merged (conflict in tables, aliases...) + func merged(with other: SQLSource) -> SQLSource? { + switch (self, other) { + case let (.table(tableName: tableName, alias: alias), .table(tableName: otherTableName, alias: otherAlias)): + guard tableName == otherTableName && alias == otherAlias else { + // can't merge + return nil + } + return .table(tableName: tableName, alias: alias) + default: + // can't merge + return nil + } + } } struct SQLLimit { diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift index aa7b688ed..e2ad7e0c0 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -5,9 +5,9 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { { let join = AssociationJoin( joinOperator: joinOperator, - query: association.request.query, - joinConditionPromise: DatabasePromise(association.joinCondition)) - return QueryInterfaceRequest(query: query.joining(join, forKey: association.key)) + joinCondition: association.joinCondition, + query: association.request.query) + return QueryInterfaceRequest(query: query.appendingJoin(join, forKey: association.key)) } // MARK: - Associations diff --git a/GRDB/Utils/OrderedDictionary.swift b/GRDB/Utils/OrderedDictionary.swift index ee8705c12..249a50034 100644 --- a/GRDB/Utils/OrderedDictionary.swift +++ b/GRDB/Utils/OrderedDictionary.swift @@ -26,6 +26,16 @@ struct OrderedDictionary { keys.append(key) } + @discardableResult + mutating func removeValue(forKey key: Key) -> Value? { + guard let value = values.removeValue(forKey: key) else { + return nil + } + let index = keys.index { $0 == key }! + keys.remove(at: index) + return value + } + func mapValues(_ transform: (Value) throws -> T) rethrows -> OrderedDictionary { var result = OrderedDictionary() for key in keys { diff --git a/Tests/GRDBTests/AssociationParallelSQLTests.swift b/Tests/GRDBTests/AssociationParallelSQLTests.swift index db57c3f06..5fb5d2c9f 100644 --- a/Tests/GRDBTests/AssociationParallelSQLTests.swift +++ b/Tests/GRDBTests/AssociationParallelSQLTests.swift @@ -108,6 +108,52 @@ class AssociationParallelSQLTests: GRDBTestCase { } } + func testParallelTwoIncludingIncludingSameAssociation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b).including(required: A.b), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + try assertEqualSQL(db, A.including(required: A.b).including(optional: A.b), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + try assertEqualSQL(db, A.including(optional: A.b).including(required: A.b), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + try assertEqualSQL(db, A.including(optional: A.b).including(optional: A.b), """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") + """) + try assertEqualSQL(db, B.including(required: B.a).including(required: B.a), """ + SELECT "b".*, "a".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(required: B.a).including(optional: B.a), """ + SELECT "b".*, "a".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(optional: B.a).including(required: B.a), """ + SELECT "b".*, "a".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(optional: B.a).including(optional: B.a), """ + SELECT "b".*, "a".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") + """) + } + } + func testParallelTwoIncludingJoining() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in