diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index cf5e404a6..c4a337b7d 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -381,40 +381,113 @@ public /* TODO: internal */ struct SQLAssociation { -> QueryInterfaceRequest where OriginRowDecoder: MutablePersistableRecord { - guard tail.isEmpty else { - fatalError("Not implemented") +// guard let next = tail.first else { +// // Goal: turn `JOIN association ON association.recordId = record.id` +// // into a regular request `SELECT * FROM association WHERE association.recordId = 123` +// +// // We need table aliases to build the joining condition +// let associationAlias = TableAlias() +// let recordAlias = TableAlias() +// +// // Turn the association query into a query interface request: +// // JOIN association -> SELECT FROM association +// return QueryInterfaceRequest(query: SQLSelectQuery(relation: head.relation)) +// +// // Turn the JOIN condition into a regular WHERE condition +// .filter { db in +// // Build a join condition: `association.recordId = record.id` +// // We still need to replace `record.id` with the actual record id. +// let joinExpression = try self.head.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) +// +// // Serialize record: ["id": 123, ...] +// // We do it as late as possible, when request is about to be +// // executed, in order to support long-lived reference types. +// let container = try PersistenceContainer(db, record) +// +// // Replace `record.id` with 123 +// return joinExpression.resolvedExpression(inContext: [recordAlias: container]) +// } +// +// // We just added a condition qualified with associationAlias. Don't +// // risk introducing conflicting aliases that would prevent the user +// // from setting a custom alias name: force the same alias for the +// // whole request. +// .aliased(associationAlias) +// } +// +// let headJoin = SQLJoin( +// joinOperator: .required, +// joinCondition: head.joinCondition, +// relation: head.relation) +// let nextRelation = next.relation.select([]).appendingJoin(headJoin, forKey: head.key) +// let nextHead = Item(key: next.key, joinCondition: next.joinCondition, relation: nextRelation) +// let nextTail = Array(tail.dropFirst()) +// let nextImpl = SQLAssociation(head: nextHead, tail: nextTail) +// return nextImpl.request(of: RowDecoder.self, from: record) + + + // SELECT head < (JOIN next < ...) + // SELECT head WHERE record_condition + // SELECT head JOIN next ON record_condition + // SELECT head JOIN next JOIN next2 ON record_condition + // SELECT head JOIN next JOIN next2 JOIN next3 ON record_condition + +// let items = ([head] + tail).reversed() +// let relation = items[items.startIndex].relation +// relation.filter { db in +// +// } +// items[items.startIndex].relation + + + // [(khead, condhead, relhead), (k2, cond2, r2), (k3, cond3, r3)] + // normal: (SELECT * FROM record) (JOIN r3 ON cond3) (JOIN r2 ON cond2) (JOIN relhead ON condhead) + // reversed: (SELECT * FROM relhead) (JOIN r2 ON condhead') (JOIN r3 ON cond2') (JOIN record ON cond3' && recordCond) + + func filter(relation: SQLRelation, condition: JoinCondition, associationAlias: TableAlias) -> SQLRelation { + return relation + .qualified(with: associationAlias) + .filter { db in + let recordAlias = TableAlias(tableName: type(of: record).databaseTableName) + + // Build a join condition: `association.recordId = record.id` + // We still need to replace `record.id` with the actual record id. + let joinExpression = try condition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) + + // Serialize record: ["id": 123, ...] + // We do it as late as possible, when request is about to be + // executed, in order to support long-lived reference types. + let container = try PersistenceContainer(db, record) + + // Replace `record.id` with 123 + return joinExpression.resolvedExpression(inContext: [recordAlias: container]) + } } - // Goal: turn `JOIN association ON association.recordId = record.id` - // into a regular request `SELECT * FROM association WHERE association.recordId = 123` - - // We need table aliases to build the joining condition - let associationAlias = TableAlias() - let recordAlias = TableAlias() - - // Turn the association query into a query interface request: - // JOIN association -> SELECT FROM association - return QueryInterfaceRequest(query: SQLSelectQuery(relation: head.relation)) - - // Turn the JOIN condition into a regular WHERE condition - .filter { db in - // Build a join condition: `association.recordId = record.id` - // We still need to replace `record.id` with the actual record id. - let joinExpression = try self.head.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) - - // Serialize record: ["id": 123, ...] - // We do it as late as possible, when request is about to be - // executed, in order to support long-lived reference types. - let container = try PersistenceContainer(db, record) - - // Replace `record.id` with 123 - return joinExpression.resolvedExpression(inContext: [recordAlias: container]) - } - - // We just added a condition qualified with associationAlias. Don't - // risk introducing conflicting aliases that would prevent the user - // from setting a custom alias name: force the same alias for the - // whole request. - .aliased(associationAlias) + let items = [head] + tail + let reversedItems = zip(items, items.dropFirst()).map { + Item(key: "" /* ignored */, joinCondition: $0.joinCondition.reversed, relation: $1.relation.select([])) + }.reversed() + if let reversedHead = reversedItems.first { + let associationAlias = TableAlias() + let filteredRelation = filter( + relation: reversedHead.relation, + condition: tail.last!.joinCondition, + associationAlias: associationAlias) + let reversedHead = Item( + key: reversedHead.key, + joinCondition: reversedHead.joinCondition, + relation: filteredRelation) + let reversedSQLAssociation = SQLAssociation(head: reversedHead, tail: Array(reversedItems.dropFirst())) + let relation = reversedSQLAssociation.joinedRelation(head.relation, joinOperator: .required) + return QueryInterfaceRequest(query: SQLSelectQuery(relation: relation)) + } else { + let associationAlias = TableAlias() + let filteredRelation = filter( + relation: head.relation, + condition: head.joinCondition, + associationAlias: associationAlias) + return QueryInterfaceRequest(query: SQLSelectQuery(relation: filteredRelation)) + } } } diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index 144d91185..82ffa4f47 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -316,6 +316,10 @@ public /* TODO: internal */ struct JoinCondition: Equatable { /// SELECT ... FROM author JOIN book ON author.id = book.authorId var originIsLeft: Bool + var reversed: JoinCondition { + return JoinCondition(foreignKeyRequest: foreignKeyRequest, originIsLeft: !originIsLeft) + } + /// Returns an SQL expression for the join condition. /// /// SELECT ... FROM book JOIN author ON author.id = book.authorId diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift index 0e3940fb1..17e290bb8 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift @@ -12,9 +12,12 @@ import XCTest class AssociationHasOneThroughSQLTests: GRDBTestCase { func testBelongsToBelongsTo() throws { - struct A: TableRecord { + struct A: MutablePersistableRecord { static let b = belongsTo(B.self) static let c = hasOne(B.c, through: b) + func encode(to container: inout PersistenceContainer) { + container["bId"] = 1 + } } struct B: TableRecord { static let c = belongsTo(C.self) @@ -40,13 +43,21 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { db, ab: A.b, ac: A.c, bCondition: "(\"b\".\"id\" = \"a\".\"bId\")", cCondition: "(\"c\".\"id\" = \"b\".\"cId\")") + + try assertEqualSQL(db, A().request(for: A.c), """ + SELECT "c".* FROM "c" \ + JOIN "b" ON (("b"."cId" = "c"."id") AND ("b"."id" = 1)) + """) } } func testBelongsToHasOne() throws { - struct A: TableRecord { + struct A: MutablePersistableRecord { static let b = belongsTo(B.self) static let c = hasOne(B.c, through: b) + func encode(to container: inout PersistenceContainer) { + container["bId"] = 1 + } } struct B: TableRecord { static let c = hasOne(C.self) @@ -72,13 +83,21 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { db, ab: A.b, ac: A.c, bCondition: "(\"b\".\"id\" = \"a\".\"bId\")", cCondition: "(\"c\".\"bId\" = \"b\".\"id\")") + + try assertEqualSQL(db, A().request(for: A.c), """ + SELECT "c".* FROM "c" \ + JOIN "b" ON (("b"."id" = "c"."bId") AND ("b"."id" = 1)) + """) } } func testHasOneBelongsTo() throws { - struct A: TableRecord { + struct A: MutablePersistableRecord { static let b = hasOne(B.self) static let c = hasOne(B.c, through: b) + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } } struct B: TableRecord { static let c = belongsTo(C.self) @@ -104,13 +123,21 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { db, ab: A.b, ac: A.c, bCondition: "(\"b\".\"aId\" = \"a\".\"id\")", cCondition: "(\"c\".\"id\" = \"b\".\"cId\")") + + try assertEqualSQL(db, A().request(for: A.c), """ + SELECT "c".* FROM "c" \ + JOIN "b" ON (("b"."cId" = "c"."id") AND ("b"."aId" = 1)) + """) } } func testHasOneHasOne() throws { - struct A: TableRecord { + struct A: MutablePersistableRecord { static let b = hasOne(B.self) static let c = hasOne(B.c, through: b) + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } } struct B: TableRecord { static let c = hasOne(C.self) @@ -136,6 +163,11 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { db, ab: A.b, ac: A.c, bCondition: "(\"b\".\"aId\" = \"a\".\"id\")", cCondition: "(\"c\".\"bId\" = \"b\".\"id\")") + + try assertEqualSQL(db, A().request(for: A.c), """ + SELECT "c".* FROM "c" \ + JOIN "b" ON (("b"."id" = "c"."bId") AND ("b"."aId" = 1)) + """) } } @@ -285,11 +317,14 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } func testBelongsToBelongsToBelongsTo() throws { - struct A: TableRecord { + struct A: MutablePersistableRecord { static let b = belongsTo(B.self) static let c = hasOne(B.c, through: b) static let dThroughC = hasOne(C.d, through: c) static let dThroughB = hasOne(B.d, through: b) + func encode(to container: inout PersistenceContainer) { + container["bId"] = 1 + } } struct B: TableRecord { static let c = belongsTo(C.self) @@ -324,15 +359,29 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { bCondition: "(\"b\".\"id\" = \"a\".\"bId\")", cCondition: "(\"c\".\"id\" = \"b\".\"cId\")", dCondition: "(\"d\".\"id\" = \"c\".\"dId\")") + + try assertEqualSQL(db, A().request(for: A.dThroughC), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."dId" = "d"."id") \ + JOIN "b" ON (("b"."cId" = "c"."id") AND ("b"."id" = 1)) + """) + try assertEqualSQL(db, A().request(for: A.dThroughB), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."dId" = "d"."id") \ + JOIN "b" ON (("b"."cId" = "c"."id") AND ("b"."id" = 1)) + """) } } func testBelongsToBelongsToHasOne() throws { - struct A: TableRecord { + struct A: MutablePersistableRecord { static let b = belongsTo(B.self) static let c = hasOne(B.c, through: b) static let dThroughC = hasOne(C.d, through: c) static let dThroughB = hasOne(B.d, through: b) + func encode(to container: inout PersistenceContainer) { + container["bId"] = 1 + } } struct B: TableRecord { static let c = belongsTo(C.self) @@ -367,15 +416,29 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { bCondition: "(\"b\".\"id\" = \"a\".\"bId\")", cCondition: "(\"c\".\"id\" = \"b\".\"cId\")", dCondition: "(\"d\".\"cId\" = \"c\".\"id\")") + + try assertEqualSQL(db, A().request(for: A.dThroughC), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."id" = "d"."cId") \ + JOIN "b" ON (("b"."cId" = "c"."id") AND ("b"."id" = 1)) + """) + try assertEqualSQL(db, A().request(for: A.dThroughB), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."id" = "d"."cId") \ + JOIN "b" ON (("b"."cId" = "c"."id") AND ("b"."id" = 1)) + """) } } func testBelongsToHasOneBelongsTo() throws { - struct A: TableRecord { + struct A: MutablePersistableRecord { static let b = belongsTo(B.self) static let c = hasOne(B.c, through: b) static let dThroughC = hasOne(C.d, through: c) static let dThroughB = hasOne(B.d, through: b) + func encode(to container: inout PersistenceContainer) { + container["bId"] = 1 + } } struct B: TableRecord { static let c = hasOne(C.self) @@ -410,15 +473,29 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { bCondition: "(\"b\".\"id\" = \"a\".\"bId\")", cCondition: "(\"c\".\"bId\" = \"b\".\"id\")", dCondition: "(\"d\".\"id\" = \"c\".\"dId\")") + + try assertEqualSQL(db, A().request(for: A.dThroughC), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."dId" = "d"."id") \ + JOIN "b" ON (("b"."id" = "c"."bId") AND ("b"."id" = 1)) + """) + try assertEqualSQL(db, A().request(for: A.dThroughB), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."dId" = "d"."id") \ + JOIN "b" ON (("b"."id" = "c"."bId") AND ("b"."id" = 1)) + """) } } func testBelongsToHasOneHasOne() throws { - struct A: TableRecord { + struct A: MutablePersistableRecord { static let b = belongsTo(B.self) static let c = hasOne(B.c, through: b) static let dThroughC = hasOne(C.d, through: c) static let dThroughB = hasOne(B.d, through: b) + func encode(to container: inout PersistenceContainer) { + container["bId"] = 1 + } } struct B: TableRecord { static let c = hasOne(C.self) @@ -453,15 +530,29 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { bCondition: "(\"b\".\"id\" = \"a\".\"bId\")", cCondition: "(\"c\".\"bId\" = \"b\".\"id\")", dCondition: "(\"d\".\"cId\" = \"c\".\"id\")") + + try assertEqualSQL(db, A().request(for: A.dThroughC), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."id" = "d"."cId") \ + JOIN "b" ON (("b"."id" = "c"."bId") AND ("b"."id" = 1)) + """) + try assertEqualSQL(db, A().request(for: A.dThroughB), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."id" = "d"."cId") \ + JOIN "b" ON (("b"."id" = "c"."bId") AND ("b"."id" = 1)) + """) } } func testHasOneBelongsToBelongsTo() throws { - struct A: TableRecord { + struct A: MutablePersistableRecord { static let b = hasOne(B.self) static let c = hasOne(B.c, through: b) static let dThroughC = hasOne(C.d, through: c) static let dThroughB = hasOne(B.d, through: b) + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } } struct B: TableRecord { static let c = belongsTo(C.self) @@ -496,15 +587,29 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { bCondition: "(\"b\".\"aId\" = \"a\".\"id\")", cCondition: "(\"c\".\"id\" = \"b\".\"cId\")", dCondition: "(\"d\".\"id\" = \"c\".\"dId\")") + + try assertEqualSQL(db, A().request(for: A.dThroughC), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."dId" = "d"."id") \ + JOIN "b" ON (("b"."cId" = "c"."id") AND ("b"."aId" = 1)) + """) + try assertEqualSQL(db, A().request(for: A.dThroughB), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."dId" = "d"."id") \ + JOIN "b" ON (("b"."cId" = "c"."id") AND ("b"."aId" = 1)) + """) } } func testHasOneBelongsToHasOne() throws { - struct A: TableRecord { + struct A: MutablePersistableRecord { static let b = hasOne(B.self) static let c = hasOne(B.c, through: b) static let dThroughC = hasOne(C.d, through: c) static let dThroughB = hasOne(B.d, through: b) + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } } struct B: TableRecord { static let c = belongsTo(C.self) @@ -539,15 +644,29 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { bCondition: "(\"b\".\"aId\" = \"a\".\"id\")", cCondition: "(\"c\".\"id\" = \"b\".\"cId\")", dCondition: "(\"d\".\"cId\" = \"c\".\"id\")") + + try assertEqualSQL(db, A().request(for: A.dThroughC), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."id" = "d"."cId") \ + JOIN "b" ON (("b"."cId" = "c"."id") AND ("b"."aId" = 1)) + """) + try assertEqualSQL(db, A().request(for: A.dThroughB), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."id" = "d"."cId") \ + JOIN "b" ON (("b"."cId" = "c"."id") AND ("b"."aId" = 1)) + """) } } func testHasOneHasOneBelongsTo() throws { - struct A: TableRecord { + struct A: MutablePersistableRecord { static let b = hasOne(B.self) static let c = hasOne(B.c, through: b) static let dThroughC = hasOne(C.d, through: c) static let dThroughB = hasOne(B.d, through: b) + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } } struct B: TableRecord { static let c = hasOne(C.self) @@ -582,15 +701,29 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { bCondition: "(\"b\".\"aId\" = \"a\".\"id\")", cCondition: "(\"c\".\"bId\" = \"b\".\"id\")", dCondition: "(\"d\".\"id\" = \"c\".\"dId\")") + + try assertEqualSQL(db, A().request(for: A.dThroughC), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."dId" = "d"."id") \ + JOIN "b" ON (("b"."id" = "c"."bId") AND ("b"."aId" = 1)) + """) + try assertEqualSQL(db, A().request(for: A.dThroughB), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."dId" = "d"."id") \ + JOIN "b" ON (("b"."id" = "c"."bId") AND ("b"."aId" = 1)) + """) } } func testHasOneHasOneHasOne() throws { - struct A: TableRecord { + struct A: MutablePersistableRecord { static let b = hasOne(B.self) static let c = hasOne(B.c, through: b) static let dThroughC = hasOne(C.d, through: c) static let dThroughB = hasOne(B.d, through: b) + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } } struct B: TableRecord { static let c = hasOne(C.self) @@ -625,6 +758,17 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { bCondition: "(\"b\".\"aId\" = \"a\".\"id\")", cCondition: "(\"c\".\"bId\" = \"b\".\"id\")", dCondition: "(\"d\".\"cId\" = \"c\".\"id\")") + + try assertEqualSQL(db, A().request(for: A.dThroughC), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."id" = "d"."cId") \ + JOIN "b" ON (("b"."id" = "c"."bId") AND ("b"."aId" = 1)) + """) + try assertEqualSQL(db, A().request(for: A.dThroughB), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON ("c"."id" = "d"."cId") \ + JOIN "b" ON (("b"."id" = "c"."bId") AND ("b"."aId" = 1)) + """) } }