From fb550d30a090f25c4cabe8a60c848b16317b0bb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 17 Apr 2020 18:52:27 +0200 Subject: [PATCH] HasManyAssociation.first and last --- .../Association/BelongsToAssociation.swift | 3 +- .../Association/HasManyAssociation.swift | 15 +- .../Association/HasOneAssociation.swift | 3 +- GRDB/QueryInterface/SQL/SQLAssociation.swift | 10 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 24 ++- .../SQLGeneration/SQLQueryGenerator.swift | 65 ++++++-- .../TableRecord+Association.swift | 7 +- .../GRDBTests/AssociationHasOneSQLTests.swift | 150 ++++++++++++++++++ 8 files changed, 250 insertions(+), 27 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift index 9d5eef9f1..99a03a3c4 100644 --- a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift @@ -97,6 +97,7 @@ public struct BelongsToAssociation: key: associationKey, condition: condition, relation: Destination.all().relation, - cardinality: .toMany) + cardinality: .toMany, + firstOnly: false) + } + + /// TODO + public var first: HasOneAssociation { + var step = sqlAssociation.steps[0] + step.firstOnly = true + return HasOneAssociation(sqlAssociation: SQLAssociation(steps: [step])) + } + + /// TODO + public var last: HasOneAssociation { + reversed().first } } diff --git a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift index f909ba766..916fc0317 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift @@ -99,6 +99,7 @@ public struct HasOneAssociation: key: associationKey, condition: condition, relation: Destination.all().relation, - cardinality: .toOne) + cardinality: .toOne, + firstOnly: false) } } diff --git a/GRDB/QueryInterface/SQL/SQLAssociation.swift b/GRDB/QueryInterface/SQL/SQLAssociation.swift index 8a84642db..416382314 100644 --- a/GRDB/QueryInterface/SQL/SQLAssociation.swift +++ b/GRDB/QueryInterface/SQL/SQLAssociation.swift @@ -75,13 +75,15 @@ public /* TODO: internal */ struct SQLAssociation { key: SQLAssociationKey, condition: SQLAssociationCondition, relation: SQLRelation, - cardinality: SQLAssociationCardinality) + cardinality: SQLAssociationCardinality, + firstOnly: Bool) { let step = SQLAssociationStep( key: key, condition: condition, relation: relation, - cardinality: cardinality) + cardinality: cardinality, + firstOnly: firstOnly) self.init(steps: [step]) } @@ -187,7 +189,8 @@ public /* TODO: internal */ struct SQLAssociation { key: key, condition: nextStep.condition.reversed, relation: relation, - cardinality: .toOne) + cardinality: .toOne, + firstOnly: false) }) .reversed() let reversedAssociation = SQLAssociation(steps: Array(reversedSteps)) @@ -202,6 +205,7 @@ struct SQLAssociationStep: Refinable { var condition: SQLAssociationCondition var relation: SQLRelation var cardinality: SQLAssociationCardinality + var firstOnly: Bool var keyName: String { key.name(for: cardinality) } } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 7a70bf8b6..a55dc9b27 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -124,6 +124,7 @@ struct SQLRelation { var kind: Kind var condition: SQLAssociationCondition var relation: SQLRelation + var firstOnly: Bool /// Returns true iff this child can change the parent count. /// @@ -144,7 +145,8 @@ struct SQLRelation { key: key, condition: condition, relation: relation, - cardinality: kind.cardinality) + cardinality: kind.cardinality, + firstOnly: firstOnly) } } @@ -216,6 +218,15 @@ extension SQLRelation: Refinable { func qualified(with alias: TableAlias) -> Self { map(\.source) { $0.qualified(with: alias) } } + + // Remove everything but selection + var witnessRelation: Self { + var result = self + result.filtersPromise = DatabasePromise(value: []) + result.ordering = SQLRelation.Ordering() + result.children = [:] + return result + } } extension SQLRelation { @@ -261,7 +272,8 @@ extension SQLRelation { let child = SQLRelation.Child( kind: kind, condition: association.destination.condition, - relation: association.destination.relation) + relation: association.destination.relation, + firstOnly: association.destination.firstOnly) let initialSteps = association.steps.dropLast() if initialSteps.isEmpty { @@ -705,6 +717,11 @@ extension SQLRelation.Child { return nil } + guard firstOnly == other.firstOnly else { + // can't merge + return nil + } + guard let mergedRelation = relation.merged(with: other.relation) else { // can't merge return nil @@ -718,7 +735,8 @@ extension SQLRelation.Child { return SQLRelation.Child( kind: mergedKind, condition: condition, - relation: mergedRelation) + relation: mergedRelation, + firstOnly: firstOnly) } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 06e6a09d4..4559678b0 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -493,10 +493,19 @@ private struct SQLQualifiedRelation { return nil } - return SQLQualifiedJoin( - kind: kind, - condition: child.condition, - relation: SQLQualifiedRelation(child.relation)) + if child.firstOnly { + return SQLQualifiedJoin( + kind: kind, + condition: child.condition, + relation: SQLQualifiedRelation(child.relation.witnessRelation), + target: .firstOnly(child.relation)) + } else { + return SQLQualifiedJoin( + kind: kind, + condition: child.condition, + relation: SQLQualifiedRelation(child.relation), + target: .all) + } } sourceSelection = relation.selection.map { $0.qualifiedSelectable(with: sourceAlias) } filtersPromise = relation.filtersPromise.map { $0.map { $0.qualifiedExpression(with: sourceAlias) } } @@ -620,26 +629,30 @@ private enum SQLQualifiedSource { } /// A "qualified" join, where all tables are identified with a table alias. -private struct SQLQualifiedJoin { +private struct SQLQualifiedJoin: Refinable { enum Kind: String { case leftJoin = "LEFT JOIN" case innerJoin = "JOIN" } - let kind: Kind - let condition: SQLAssociationCondition - let relation: SQLQualifiedRelation + enum Target { + case all + case firstOnly(SQLRelation) + } + + var kind: Kind + var condition: SQLAssociationCondition + var relation: SQLQualifiedRelation + var target: Target +// var firstOnly: Bool func sql(_ db: Database, _ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String { try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true) } /// Removes all selections from joins - func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedJoin { - SQLQualifiedJoin( - kind: kind, - condition: condition, - relation: relation.selectOnly(selection)) + func selectOnly(_ selection: [SQLSelectable]) -> Self { + map(\.relation) { $0.selectOnly(selection) } } private func sql( @@ -668,10 +681,28 @@ private struct SQLQualifiedJoin { sql += try "\(kind.rawValue) \(relation.source.sql(db, &context))" let rightAlias = relation.sourceAlias - let filters = try condition.expressions(db, leftAlias: leftAlias, rightAlias: rightAlias) - + relation.filtersPromise.resolve(db) - if filters.isEmpty == false { - sql += " ON \(filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false))" + switch target { + case let .all: + let filters = try condition.expressions(db, leftAlias: leftAlias, rightAlias: rightAlias) + + relation.filtersPromise.resolve(db) + if filters.isEmpty == false { + sql += " ON \(filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false))" + } + case let .firstOnly(subRelation): + #warning("TODO: use child.condition") + let subAlias = TableAlias() + let filters = try condition.expressions(db, leftAlias: leftAlias, rightAlias: subAlias) + let subRelation = subRelation + .qualified(with: subAlias) + .selectOnly([Column.rowID]) + .map(\.filtersPromise) { $0.flatMap { DatabasePromise(value: filters + $0) } } + let subQuery = SQLQuery(relation: subRelation, limit: SQLLimit(limit: 1, offset: nil)) + let subQueryGenerator = SQLQueryGenerator(subQuery) + + sql += " ON " + sql += rightAlias[Column.rowID].expressionSQL(&context, wrappedInParenthesis: false) + // SELECT rowid FROM child WHERE child.parentId = parent.id ORDER BY id DESC LIMIT 1 + sql += try " = (" + subQueryGenerator.sql(db, &context) + ")" } for (_, join) in relation.joins { diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 2b83533b5..4d49c3ba7 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -489,7 +489,12 @@ extension TableRecord where Self: EncodableRecord { let destinationRelation = association.sqlAssociation.destinationRelation(fromOriginRows: { db in try [Row(PersistenceContainer(db, self))] }) - return QueryInterfaceRequest(relation: destinationRelation) + let request = QueryInterfaceRequest(relation: destinationRelation) + if association.sqlAssociation.destination.firstOnly { + return request.limit(1) + } else { + return request + } } } diff --git a/Tests/GRDBTests/AssociationHasOneSQLTests.swift b/Tests/GRDBTests/AssociationHasOneSQLTests.swift index 629e2f957..064abc5a7 100644 --- a/Tests/GRDBTests/AssociationHasOneSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasOneSQLTests.swift @@ -760,4 +760,154 @@ class AssociationHasOneSQLTests: GRDBTestCase { } } } + + func testHasManyFirst() throws { + struct Child : TableRecord { } + struct Parent: TableRecord, EncodableRecord { + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + container["rowid"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "child") { t in + t.autoIncrementedPrimaryKey("id") + t.column("parentId", .integer).references("parent") + } + + do { + let association = Parent + .hasMany(Child.self) + .orderByPrimaryKey() + .first() + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parent".*, "child".* \ + FROM "parent" \ + JOIN "child" ON "child"."rowid" = (\ + SELECT "child"."rowid" \ + FROM "child" \ + WHERE "child"."parentId" = "parent"."id" \ + ORDER BY "child"."id" \ + LIMIT 1) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parent".*, "child".* \ + FROM "parent" \ + LEFT JOIN "child" ON "child"."rowid" = (\ + SELECT "child"."rowid" \ + FROM "child" \ + WHERE "child"."parentId" = "parent"."id" \ + ORDER BY "child"."id" \ + LIMIT 1) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parent".* \ + FROM "parent" \ + JOIN "child" ON "child"."rowid" = (\ + SELECT "child"."rowid" \ + FROM "child" \ + WHERE "child"."parentId" = "parent"."id" \ + ORDER BY "child"."id" \ + LIMIT 1) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parent".* \ + FROM "parent" \ + LEFT JOIN "child" ON "child"."rowid" = (\ + SELECT "child"."rowid" \ + FROM "child" \ + WHERE "child"."parentId" = "parent"."id" \ + ORDER BY "child"."id" \ + LIMIT 1) + """) + try assertEqualSQL(db, Parent().request(for: association), """ + SELECT * FROM "child" \ + WHERE "parentId" = 1 \ + ORDER BY "id" \ + LIMIT 1 + """) + } + // TODO: test that first/last can be used with filtering with further association + } + } + + func testHasManyLast() throws { + struct Child : TableRecord { } + struct Parent: TableRecord, EncodableRecord { + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + container["rowid"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "child") { t in + t.autoIncrementedPrimaryKey("id") + t.column("parentId", .integer).references("parent") + } + + do { + let association = Parent + .hasMany(Child.self) + .orderByPrimaryKey() + .last() + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parent".*, "child".* \ + FROM "parent" \ + JOIN "child" ON "child"."rowid" = (\ + SELECT "child"."rowid" \ + FROM "child" \ + WHERE "child"."parentId" = "parent"."id" \ + ORDER BY "child"."id" DESC \ + LIMIT 1) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parent".*, "child".* \ + FROM "parent" \ + LEFT JOIN "child" ON "child"."rowid" = (\ + SELECT "child"."rowid" \ + FROM "child" \ + WHERE "child"."parentId" = "parent"."id" \ + ORDER BY "child"."id" DESC \ + LIMIT 1) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parent".* \ + FROM "parent" \ + JOIN "child" ON "child"."rowid" = (\ + SELECT "child"."rowid" \ + FROM "child" \ + WHERE "child"."parentId" = "parent"."id" \ + ORDER BY "child"."id" DESC \ + LIMIT 1) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parent".* \ + FROM "parent" \ + LEFT JOIN "child" ON "child"."rowid" = (\ + SELECT "child"."rowid" \ + FROM "child" \ + WHERE "child"."parentId" = "parent"."id" \ + ORDER BY "child"."id" DESC \ + LIMIT 1) + """) + try assertEqualSQL(db, Parent().request(for: association), """ + SELECT * FROM "child" \ + WHERE "parentId" = 1 \ + ORDER BY "id" DESC \ + LIMIT 1 + """) + } + // TODO: test that first/last can be used with filtering with further association + } + } }