From d0ba9e342cba5c62874c37e4e11bd288bd92ebed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 25 Apr 2020 19:51:03 +0200 Subject: [PATCH] Turn selection and having clauses into promises. Give association aggregates access to the actual primary key, for better support for WITHOUT ROW ID tables. --- .../Request/Association/Association.swift | 12 +- .../Association/AssociationAggregate.swift | 317 +++++------------- .../Association/BelongsToAssociation.swift | 2 +- .../Association/HasManyAssociation.swift | 2 +- .../Association/HasOneAssociation.swift | 2 +- .../QueryInterfaceRequest+Association.swift | 15 +- .../Request/QueryInterfaceRequest.swift | 42 +-- .../Request/RequestProtocols.swift | 73 ++-- GRDB/QueryInterface/SQL/DatabasePromise.swift | 6 - GRDB/QueryInterface/SQL/SQLQuery.swift | 27 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 42 ++- .../SQLGeneration/SQLQueryGenerator.swift | 31 +- .../TableRecord+Association.swift | 9 +- .../TableRecord+QueryInterfaceRequest.swift | 11 +- .../GRDBTests/AssociationAggregateTests.swift | 124 +++---- .../MutablePersistableRecordDeleteTests.swift | 2 +- .../MutablePersistableRecordUpdateTests.swift | 2 +- 17 files changed, 310 insertions(+), 409 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 22abce855..68cc56433 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -113,7 +113,7 @@ extension Association { /// // SELECT player.*, team.color /// // FROM player /// // JOIN team ON team.id = player.teamId - /// let association = Player.team.select([Column("color")]) + /// let association = Player.team.select { db in [Column("color")] /// var request = Player.including(required: association) /// /// Any previous selection is replaced: @@ -122,10 +122,10 @@ extension Association { /// // FROM player /// // JOIN team ON team.id = player.teamId /// let association = Player.team - /// .select([Column("id")]) - /// .select([Column("color")]) + /// .select { db in [Column("id")] } + /// .select { db in [Column("color") } /// var request = Player.including(required: association) - public func select(_ selection: [SQLSelectable]) -> Self { + public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { mapDestinationRelation { $0.select(selection) } } @@ -140,9 +140,9 @@ extension Association { /// // JOIN team ON team.id = player.teamId /// let association = Player.team /// .select([Column("color")]) - /// .annotated(with: [Column("name")]) + /// .annotated(with: { db in [Column("name")] }) /// var request = Player.including(required: association) - public func annotated(with selection: [SQLSelectable]) -> Self { + public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { mapDestinationRelation { $0.annotated(with: selection) } } diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index a2e7cbe26..6b7da4c80 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -2,20 +2,25 @@ import Foundation typealias AssociationAggregatePreparation = (QueryInterfaceRequest) - -> (request: QueryInterfaceRequest, expression: SQLExpression) + -> (request: QueryInterfaceRequest, expressionPromise: DatabasePromise) extension AssociationToMany { - private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate { + private func makeAggregate(_ expressionPromise: DatabasePromise) -> AssociationAggregate { AssociationAggregate { request in let tableAlias = TableAlias() let request = request .joining(optional: self.aliased(tableAlias)) .groupByPrimaryKey() - let expression = tableAlias[expression] - return (request: request, expression: expression) + let expressionPromise = expressionPromise.map { tableAlias[$0] } + return (request: request, expressionPromise: expressionPromise) } } + // Convenience + private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate { + makeAggregate(DatabasePromise(value: expression)) + } + /// The number of associated records. /// /// It has a default name, which is "[key]Count", where key is the key of @@ -32,9 +37,11 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db) public var count: AssociationAggregate { - // TODO: try to replace rowid with actual primary key - makeAggregate(SQLExpressionCountDistinct(Column.rowID)) - .forKey("\(key.singularizedName)Count") + let expression = DatabasePromise { db in + let primaryKey = try db.primaryKeyExpression(self.databaseTableName) + return SQLExpressionCountDistinct(primaryKey) + } + return makeAggregate(expression).forKey("\(key.singularizedName)Count") } /// Creates an aggregate that is true if there exists no associated records. @@ -53,9 +60,11 @@ extension AssociationToMany { /// let teams: [Team] = try Team.having(!Team.players.isEmpty()) /// let teams: [Team] = try Team.having(Team.players.isEmpty() == false) public var isEmpty: AssociationAggregate { - // TODO: try to replace rowid with actual primary key - makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID))) - .forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") + let expression = DatabasePromise { db in + let primaryKey = try db.primaryKeyExpression(self.databaseTableName) + return SQLExpressionIsEmpty(SQLExpressionCountDistinct(primaryKey)) + } + return makeAggregate(expression).forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") } /// Creates an aggregate which evaluate to the average value of the given @@ -190,7 +199,6 @@ extension AssociationToMany { /// // Won't compile because Fruit is not Author. /// let request = Fruit.annotated(with: bookCount) public struct AssociationAggregate { - // TODO: replace rowid with actual primary key in the doc when implemented /// Given a request, returns a tuple made of a request extended with the /// associated records used to compute the aggregate, and an expression /// whose value is the aggregated value. @@ -216,7 +224,7 @@ public struct AssociationAggregate { /// /// // The aggregated value: /// // - /// // COUNT(DISTINCT book.rowid) + /// // COUNT(DISTINCT book.id) /// tuple.expression /// /// The aggregated value is not right away embedded in the extended request: @@ -262,6 +270,29 @@ extension AssociationAggregate: Refinable { public func forKey(_ key: CodingKey) -> Self { forKey(key.stringValue) } + + /// Transforms the expression, and does not preserve key. + func mapExpression(_ transform: @escaping (SQLExpression) throws -> SQLExpression) -> Self { + AssociationAggregate { request in + let (request, expressionPromise) = self.prepare(request) + return (request: request, expressionPromise: expressionPromise.map(transform)) + } + } + + func combined( + with other: Self, + _ combineExpressions : @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression) + -> Self + { + AssociationAggregate { request in + let (lRequest, lExpression) = self.prepare(request) + let (request, rExpression) = other.prepare(lRequest) + let expressionPromise = DatabasePromise { db in + try combineExpressions(lExpression.resolve(db), rExpression.resolve(db)) + } + return (request: request, expressionPromise: expressionPromise) + } + } } // MARK: - Logical Operators (AND, OR, NOT) @@ -272,10 +303,7 @@ extension AssociationAggregate: Refinable { /// /// Author.having(!Author.books.isEmpty) public prefix func ! (aggregate: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = aggregate.prepare(request) - return (request: request, expression: !expression) - } + aggregate.mapExpression { !$0 } } /// Groups two aggregates with the `AND` SQL operator. @@ -288,11 +316,7 @@ public func && ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (lRequest, lExpression) = lhs.prepare(request) - let (request, rExpression) = rhs.prepare(lRequest) - return (request: request, expression: lExpression && rExpression) - } + lhs.combined(with: rhs, &&) } // TODO: test @@ -302,10 +326,7 @@ public func && ( rhs: SQLExpressible) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression && rhs) - } + lhs.mapExpression { $0 && rhs } } // TODO: test @@ -315,10 +336,7 @@ public func && ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs && expression) - } + rhs.mapExpression { lhs && $0 } } @@ -332,11 +350,7 @@ public func || ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (lRequest, lExpression) = lhs.prepare(request) - let (request, rExpression) = rhs.prepare(lRequest) - return (request: request, expression: lExpression || rExpression) - } + lhs.combined(with: rhs, ||) } // TODO: test @@ -346,10 +360,7 @@ public func || ( rhs: SQLExpressible) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression || rhs) - } + lhs.mapExpression { $0 || rhs } } // TODO: test @@ -359,10 +370,7 @@ public func || ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs || expression) - } + rhs.mapExpression { lhs || $0 } } // MARK: - Egality and Identity Operators (=, <>, IS, IS NOT) @@ -377,11 +385,7 @@ public func == ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (lRequest, lExpression) = lhs.prepare(request) - let (request, rExpression) = rhs.prepare(lRequest) - return (request: request, expression: lExpression == rExpression) - } + lhs.combined(with: rhs, ==) } /// Returns an aggregate that compares an aggregate with the `=` SQL operator. @@ -394,10 +398,7 @@ public func == ( rhs: SQLExpressible) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression == rhs) - } + lhs.mapExpression { $0 == rhs } } /// Returns an aggregate that compares an aggregate with the `=` SQL operator. @@ -410,10 +411,7 @@ public func == ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs == expression) - } + rhs.mapExpression { lhs == $0 } } /// Returns an aggregate that checks the boolean value of an aggregate. @@ -422,10 +420,7 @@ public func == ( /// /// Author.having(Author.books.isEmpty == false) public func == (lhs: AssociationAggregate, rhs: Bool) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression == rhs) - } + lhs.mapExpression { $0 == rhs } } /// Returns an aggregate that checks the boolean value of an aggregate. @@ -434,10 +429,7 @@ public func == (lhs: AssociationAggregate, rhs: Bool) -> /// /// Author.having(false == Author.books.isEmpty) public func == (lhs: Bool, rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs == expression) - } + rhs.mapExpression { lhs == $0 } } /// Returns an aggregate that compares two aggregates with the `<>` SQL operator. @@ -450,11 +442,7 @@ public func != ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (lRequest, lExpression) = lhs.prepare(request) - let (request, rExpression) = rhs.prepare(lRequest) - return (request: request, expression: lExpression != rExpression) - } + lhs.combined(with: rhs, !=) } /// Returns an aggregate that compares an aggregate with the `<>` SQL operator. @@ -467,10 +455,7 @@ public func != ( rhs: SQLExpressible) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression != rhs) - } + lhs.mapExpression { $0 != rhs } } /// Returns an aggregate that compares an aggregate with the `<>` SQL operator. @@ -483,10 +468,7 @@ public func != ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs != expression) - } + rhs.mapExpression { lhs != $0 } } /// Returns an aggregate that checks the boolean value of an aggregate. @@ -495,10 +477,7 @@ public func != ( /// /// Author.having(Author.books.isEmpty != true) public func != (lhs: AssociationAggregate, rhs: Bool) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression != rhs) - } + lhs.mapExpression { $0 != rhs } } /// Returns an aggregate that checks the boolean value of an aggregate. @@ -507,10 +486,7 @@ public func != (lhs: AssociationAggregate, rhs: Bool) -> /// /// Author.having(true != Author.books.isEmpty) public func != (lhs: Bool, rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs != expression) - } + rhs.mapExpression { lhs != $0 } } /// Returns an aggregate that compares two aggregates with the `IS` SQL operator. @@ -523,11 +499,7 @@ public func === ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (lRequest, lExpression) = lhs.prepare(request) - let (request, rExpression) = rhs.prepare(lRequest) - return (request: request, expression: lExpression === rExpression) - } + lhs.combined(with: rhs, ===) } /// Returns an aggregate that compares an aggregate with the `IS` SQL operator. @@ -540,10 +512,7 @@ public func === ( rhs: SQLExpressible) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression === rhs) - } + lhs.mapExpression { $0 === rhs } } /// Returns an aggregate that compares an aggregate with the `IS` SQL operator. @@ -556,10 +525,7 @@ public func === ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs === expression) - } + rhs.mapExpression { lhs === $0 } } /// Returns an aggregate that compares two aggregates with the `IS NOT` SQL operator. @@ -572,11 +538,7 @@ public func !== ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (lRequest, lExpression) = lhs.prepare(request) - let (request, rExpression) = rhs.prepare(lRequest) - return (request: request, expression: lExpression !== rExpression) - } + lhs.combined(with: rhs, !==) } /// Returns an aggregate that compares an aggregate with the `IS NOT` SQL operator. @@ -589,10 +551,7 @@ public func !== ( rhs: SQLExpressible) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression !== rhs) - } + lhs.mapExpression { $0 !== rhs } } /// Returns an aggregate that compares an aggregate with the `IS NOT` SQL operator. @@ -605,10 +564,7 @@ public func !== ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs !== expression) - } + rhs.mapExpression { lhs !== $0 } } // MARK: - Comparison Operators (<, >, <=, >=) @@ -623,11 +579,7 @@ public func <= ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (lRequest, lExpression) = lhs.prepare(request) - let (request, rExpression) = rhs.prepare(lRequest) - return (request: request, expression: lExpression <= rExpression) - } + lhs.combined(with: rhs, <=) } /// Returns an aggregate that compares an aggregate with the `<=` SQL operator. @@ -640,10 +592,7 @@ public func <= ( rhs: SQLExpressible) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression <= rhs) - } + lhs.mapExpression { $0 <= rhs } } /// Returns an aggregate that compares an aggregate with the `<=` SQL operator. @@ -656,10 +605,7 @@ public func <= ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs <= expression) - } + rhs.mapExpression { lhs <= $0 } } /// Returns an aggregate that compares two aggregates with the `<` SQL operator. @@ -672,11 +618,7 @@ public func < ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (lRequest, lExpression) = lhs.prepare(request) - let (request, rExpression) = rhs.prepare(lRequest) - return (request: request, expression: lExpression < rExpression) - } + lhs.combined(with: rhs, <) } /// Returns an aggregate that compares an aggregate with the `<` SQL operator. @@ -689,10 +631,7 @@ public func < ( rhs: SQLExpressible) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression < rhs) - } + lhs.mapExpression { $0 < rhs } } /// Returns an aggregate that compares an aggregate with the `<` SQL operator. @@ -705,10 +644,7 @@ public func < ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs < expression) - } + rhs.mapExpression { lhs < $0 } } /// Returns an aggregate that compares two aggregates with the `>` SQL operator. @@ -721,11 +657,7 @@ public func > ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (lRequest, lExpression) = lhs.prepare(request) - let (request, rExpression) = rhs.prepare(lRequest) - return (request: request, expression: lExpression > rExpression) - } + lhs.combined(with: rhs, >) } /// Returns an aggregate that compares an aggregate with the `>` SQL operator. @@ -738,10 +670,7 @@ public func > ( rhs: SQLExpressible) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression > rhs) - } + lhs.mapExpression { $0 > rhs } } /// Returns an aggregate that compares an aggregate with the `>` SQL operator. @@ -754,10 +683,7 @@ public func > ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs > expression) - } + rhs.mapExpression { lhs > $0 } } /// Returns an aggregate that compares two aggregates with the `>=` SQL operator. @@ -770,11 +696,7 @@ public func >= ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (lRequest, lExpression) = lhs.prepare(request) - let (request, rExpression) = rhs.prepare(lRequest) - return (request: request, expression: lExpression >= rExpression) - } + lhs.combined(with: rhs, >=) } /// Returns an aggregate that compares an aggregate with the `>=` SQL operator. @@ -787,10 +709,7 @@ public func >= ( rhs: SQLExpressible) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression >= rhs) - } + lhs.mapExpression { $0 >= rhs } } /// Returns an aggregate that compares an aggregate with the `>=` SQL operator. @@ -803,10 +722,7 @@ public func >= ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs >= expression) - } + rhs.mapExpression { lhs >= $0 } } // MARK: - Arithmetic Operators (+, -, *, /) @@ -817,10 +733,7 @@ public func >= ( /// /// Author.annotated(with: -Author.books.count) public prefix func - (aggregate: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = aggregate.prepare(request) - return (request: request, expression:-expression) - } + aggregate.mapExpression { -$0 } } /// Returns an aggregate that sums two aggregates with the `+` SQL operator. @@ -833,11 +746,7 @@ public func + ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (lRequest, lExpression) = lhs.prepare(request) - let (request, rExpression) = rhs.prepare(lRequest) - return (request: request, expression: lExpression + rExpression) - } + lhs.combined(with: rhs, +) } /// Returns an aggregate that sums an aggregate with the `+` SQL operator. @@ -850,10 +759,7 @@ public func + ( rhs: SQLExpressible) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression + rhs) - } + lhs.mapExpression { $0 + rhs } } /// Returns an aggregate that sums an aggregate with the `+` SQL operator. @@ -866,10 +772,7 @@ public func + ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs + expression) - } + rhs.mapExpression { lhs + $0 } } /// Returns an aggregate that substracts two aggregates with the `-` SQL operator. @@ -882,11 +785,7 @@ public func - ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (lRequest, lExpression) = lhs.prepare(request) - let (request, rExpression) = rhs.prepare(lRequest) - return (request: request, expression: lExpression - rExpression) - } + lhs.combined(with: rhs, -) } /// Returns an aggregate that substracts an aggregate with the `-` SQL operator. @@ -899,10 +798,7 @@ public func - ( rhs: SQLExpressible) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression - rhs) - } + lhs.mapExpression { $0 - rhs } } /// Returns an aggregate that substracts an aggregate with the `-` SQL operator. @@ -915,10 +811,7 @@ public func - ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs - expression) - } + rhs.mapExpression { lhs - $0 } } /// Returns an aggregate that multiplies two aggregates with the `*` SQL operator. @@ -931,11 +824,7 @@ public func * ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (lRequest, lExpression) = lhs.prepare(request) - let (request, rExpression) = rhs.prepare(lRequest) - return (request: request, expression: lExpression * rExpression) - } + lhs.combined(with: rhs, *) } /// Returns an aggregate that substracts an aggregate with the `*` SQL operator. @@ -948,10 +837,7 @@ public func * ( rhs: SQLExpressible) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression * rhs) - } + lhs.mapExpression { $0 * rhs } } /// Returns an aggregate that substracts an aggregate with the `*` SQL operator. @@ -964,10 +850,7 @@ public func * ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs * expression) - } + rhs.mapExpression { lhs * $0 } } /// Returns an aggregate that multiplies two aggregates with the `/` SQL operator. @@ -980,11 +863,7 @@ public func / ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (lRequest, lExpression) = lhs.prepare(request) - let (request, rExpression) = rhs.prepare(lRequest) - return (request: request, expression: lExpression / rExpression) - } + lhs.combined(with: rhs, /) } /// Returns an aggregate that substracts an aggregate with the `/` SQL operator. @@ -997,10 +876,7 @@ public func / ( rhs: SQLExpressible) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression / rhs) - } + lhs.mapExpression { $0 / rhs } } /// Returns an aggregate that substracts an aggregate with the `/` SQL operator. @@ -1013,10 +889,7 @@ public func / ( rhs: AssociationAggregate) -> AssociationAggregate { - AssociationAggregate { request in - let (request, expression) = rhs.prepare(request) - return (request: request, expression: lhs / expression) - } + rhs.mapExpression { lhs / $0 } } // MARK: - IFNULL(...) @@ -1029,14 +902,8 @@ public func ?? ( rhs: SQLExpressible) -> AssociationAggregate { - var aggregate = AssociationAggregate { request in - let (request, expression) = lhs.prepare(request) - return (request: request, expression: expression ?? rhs) - } - // Preserve key - aggregate.key = lhs.key - return aggregate + lhs.mapExpression { $0 ?? rhs }.with(\.key, lhs.key) } // TODO: add support for ABS(aggregate) diff --git a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift index 9d5eef9f1..c46840432 100644 --- a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift @@ -96,7 +96,7 @@ public struct BelongsToAssociation: sqlAssociation = SQLAssociation( key: associationKey, condition: condition, - relation: Destination.all().relation, + relation: Destination.relationForAll, cardinality: .toMany) } } diff --git a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift index f909ba766..5b94c4f51 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift @@ -98,7 +98,7 @@ public struct HasOneAssociation: sqlAssociation = SQLAssociation( key: associationKey, condition: condition, - relation: Destination.all().relation, + relation: Destination.relationForAll, cardinality: .toOne) } } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift index 4c7743a40..3604279b8 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift @@ -5,16 +5,15 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { private func annotated(with aggregate: AssociationAggregate) -> QueryInterfaceRequest { let (request, expression) = aggregate.prepare(self) if let key = aggregate.key { - return request.annotated(with: [expression.forKey(key)]) + return request.annotated(with: { db in try [expression.resolve(db).forKey(key)] }) } else { - return request.annotated(with: [expression]) + return request.annotated(with: { db in try [expression.resolve(db)] }) } } - // TODO: replace rowid with actual primary key in the doc when implemented /// Creates a request which appends *aggregates* to the current selection. /// - /// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount + /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount /// // FROM player LEFT JOIN book ... /// var request = Player.all() /// request = request.annotated(with: Player.books.count) @@ -22,10 +21,9 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { annotated(with: aggregates) } - // TODO: replace rowid with actual primary key in the doc when implemented /// Creates a request which appends *aggregates* to the current selection. /// - /// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount + /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount /// // FROM player LEFT JOIN book ... /// var request = Player.all() /// request = request.annotated(with: [Player.books.count]) @@ -35,17 +33,16 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { } } - // TODO: replace rowid with actual primary key in the doc when implemented /// Creates a request which appends the provided aggregate *predicate* to /// the eventual set of already applied predicates. /// /// // SELECT player.* /// // FROM player LEFT JOIN book ... - /// // HAVING COUNT(DISTINCT book.rowid) = 0 + /// // HAVING COUNT(DISTINCT book.id) = 0 /// var request = Player.all() /// request = request.having(Player.books.isEmpty) public func having(_ predicate: AssociationAggregate) -> QueryInterfaceRequest { let (request, expression) = predicate.prepare(self) - return request.having(expression) + return request.having(expression.resolve) } } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index d4854e97c..4a82f9b6e 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -117,19 +117,19 @@ extension QueryInterfaceRequest: FetchRequest { extension QueryInterfaceRequest: SelectionRequest { // MARK: Request Derivation - /// Creates a request which selects *selection*. + /// Creates a request which selects *selection promise*. /// /// // SELECT id, email FROM player /// var request = Player.all() - /// request = request.select([Column("id"), Column("email")]) + /// request = request.select { db in [Column("id"), Column("email")] } /// /// Any previous selection is replaced: /// /// // SELECT email FROM player /// request - /// .select([Column("id")]) - /// .select([Column("email")]) - public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { + /// .select { db in [Column("id")] } + /// .select { db in [Column("email")] } + public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { map(\.query) { $0.select(selection) } } @@ -213,14 +213,14 @@ extension QueryInterfaceRequest: SelectionRequest { select(sqlLiteral.sqlSelectable, as: type) } - /// Creates a request which appends *selection*. + /// Creates a request which appends *selection promise*. /// /// // SELECT id, email, name FROM player /// var request = Player.all() /// request = request /// .select([Column("id"), Column("email")]) - /// .annotated(with: [Column("name")]) - public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { + /// .annotated(with: { db in [Column("name")] }) + public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { map(\.query) { $0.annotated(with: selection) } } } @@ -292,9 +292,9 @@ extension QueryInterfaceRequest: AggregatingRequest { map(\.query) { $0.group(expressions) } } - /// Creates a request with the provided *predicate* added to the + /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. - public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest { + public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { map(\.query) { $0.having(predicate) } } } @@ -407,28 +407,6 @@ extension QueryInterfaceRequest: Refinable { } } -extension QueryInterfaceRequest { - /// Turns a request into a SQLRelation. - /// - /// This method helps initializing associations: - /// - /// struct Book: TableRecord { - /// // invokes Author.all().relation - /// static let author = belongsTo(Author.self) - /// } - var relation: SQLRelation { - let query = self.query - - // Prevent information loss - GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries") - GRDBPrecondition(query.groupPromise == nil, "Can't join aggregated queries") - GRDBPrecondition(query.havingExpressions.isEmpty, "Can't join aggregated queries") - GRDBPrecondition(query.limit == nil, "Can't join limited queries") - - return query.relation - } -} - extension QueryInterfaceRequest: TableRequest { /// :nodoc: public var databaseTableName: String { diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index ae0dc95ea..9dba53911 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -6,6 +6,32 @@ /// /// :nodoc: public protocol SelectionRequest { + /// Creates a request which selects *selection promise*. + /// + /// // SELECT id, email FROM player + /// var request = Player.all() + /// request = request.select { db in [Column("id"), Column("email") }) + /// + /// Any previous selection is replaced: + /// + /// // SELECT email FROM player + /// request + /// .select { db in [Column("id")] } + /// .select { db in [Column("email")] } + func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self + + /// Creates a request which appends *selection promise*. + /// + /// // SELECT id, email, name FROM player + /// var request = Player.all() + /// request = request + /// .select([Column("id"), Column("email")]) + /// .annotated(with: { db in [Column("name")] }) + func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self +} + +/// :nodoc: +extension SelectionRequest { /// Creates a request which selects *selection*. /// /// // SELECT id, email FROM player @@ -18,20 +44,10 @@ public protocol SelectionRequest { /// request /// .select([Column("id")]) /// .select([Column("email")]) - func select(_ selection: [SQLSelectable]) -> Self + public func select(_ selection: [SQLSelectable]) -> Self { + select { _ in selection } + } - /// Creates a request which appends *selection*. - /// - /// // SELECT id, email, name FROM player - /// var request = Player.all() - /// request = request - /// .select([Column("id"), Column("email")]) - /// .annotated(with: [Column("name")]) - func annotated(with selection: [SQLSelectable]) -> Self -} - -/// :nodoc: -extension SelectionRequest { /// Creates a request which selects *selection*. /// /// // SELECT id, email FROM player @@ -91,7 +107,18 @@ extension SelectionRequest { /// .select(literal: SQLLiteral(sql: "email")) public func select(literal sqlLiteral: SQLLiteral) -> Self { // NOT TESTED - return select(sqlLiteral.sqlSelectable) + select(sqlLiteral.sqlSelectable) + } + + /// Creates a request which appends *selection*. + /// + /// // SELECT id, email, name FROM player + /// var request = Player.all() + /// request = request + /// .select([Column("id"), Column("email")]) + /// .annotated(with: [Column("name")]) + public func annotated(with selection: [SQLSelectable]) -> Self { + annotated(with: { _ in selection }) } /// Creates a request which appends *selection*. @@ -174,7 +201,7 @@ extension FilteredRequest { /// request = request.filter(literal: "name = \("O'Brien")") public func filter(literal sqlLiteral: SQLLiteral) -> Self { // NOT TESTED - return filter(sqlLiteral.sqlExpression) + filter(sqlLiteral.sqlExpression) } /// Creates a request that matches nothing. @@ -344,9 +371,9 @@ public protocol AggregatingRequest { /// Creates a request grouped according to *expressions promise*. func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self - /// Creates a request with the provided *predicate* added to the + /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. - func having(_ predicate: SQLExpressible) -> Self + func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self } /// :nodoc: @@ -369,7 +396,13 @@ extension AggregatingRequest { /// Creates a request with a new grouping. public func group(literal sqlLiteral: SQLLiteral) -> Self { // NOT TESTED - return group(sqlLiteral.sqlExpression) + group(sqlLiteral.sqlExpression) + } + + /// Creates a request with the provided *predicate* added to the + /// eventual set of already applied predicates. + public func having(_ predicate: SQLExpressible) -> Self { + having { _ in predicate } } /// Creates a request with the provided *sql* added to the @@ -382,7 +415,7 @@ extension AggregatingRequest { /// eventual set of already applied predicates. public func having(literal sqlLiteral: SQLLiteral) -> Self { // NOT TESTED - return having(sqlLiteral.sqlExpression) + having(sqlLiteral.sqlExpression) } } @@ -496,7 +529,7 @@ extension OrderedRequest { /// .order(sql: "name") public func order(literal sqlLiteral: SQLLiteral) -> Self { // NOT TESTED - return order(sqlLiteral.sqlOrderingTerm) + order(sqlLiteral.sqlOrderingTerm) } } diff --git a/GRDB/QueryInterface/SQL/DatabasePromise.swift b/GRDB/QueryInterface/SQL/DatabasePromise.swift index f5f1ca31c..815e15f77 100644 --- a/GRDB/QueryInterface/SQL/DatabasePromise.swift +++ b/GRDB/QueryInterface/SQL/DatabasePromise.swift @@ -41,10 +41,4 @@ struct DatabasePromise { try transform(self.resolve(db)) } } - - func flatMap(_ transform: @escaping (T) -> DatabasePromise) -> DatabasePromise { - DatabasePromise { db in - try transform(self.resolve(db)).resolve(db) - } - } } diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index e507a6957..6fc070aa3 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -9,7 +9,7 @@ struct SQLQuery { // Having clause is an array of expressions that we'll join with // the AND operator. This gives nicer output in generated SQL: // `(a AND b AND c)` instead of `((a AND b) AND c)`. - var havingExpressions: [SQLExpression] = [] + var havingExpressionsPromise: DatabasePromise<[SQLExpression]> = DatabasePromise(value: []) var limit: SQLLimit? } @@ -34,11 +34,11 @@ extension SQLQuery: Refinable { } extension SQLQuery: SelectionRequest { - func select(_ selection: [SQLSelectable]) -> Self { + func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { map(\.relation) { $0.select(selection) } } - func annotated(with selection: [SQLSelectable]) -> Self { + func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { map(\.relation) { $0.annotated(with: selection) } } } @@ -68,8 +68,12 @@ extension SQLQuery: AggregatingRequest { with(\.groupPromise, DatabasePromise { db in try expressions(db).map(\.sqlExpression) }) } - func having(_ predicate: SQLExpressible) -> Self { - mapInto(\.havingExpressions) { $0.append(predicate.sqlExpression) } + func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { + map(\.havingExpressionsPromise) { havingExpressionsPromise in + DatabasePromise { db in + try havingExpressionsPromise.resolve(db) + [predicate(db).sqlExpression] + } + } } } @@ -97,11 +101,11 @@ extension SQLQuery: _JoinableRequest { extension SQLQuery { func fetchCount(_ db: Database) throws -> Int { - let (statement, adapter) = try SQLQueryGenerator(countQuery).prepare(db) + let (statement, adapter) = try SQLQueryGenerator(countQuery(db)).prepare(db) return try Int.fetchOne(statement, adapter: adapter)! } - private var countQuery: SQLQuery { + private func countQuery(_ db: Database) throws -> SQLQuery { guard groupPromise == nil && limit == nil else { // SELECT ... GROUP BY ... // SELECT ... LIMIT ... @@ -118,9 +122,10 @@ extension SQLQuery { return trivialCountQuery } - GRDBPrecondition(!relation.selection.isEmpty, "Can't generate SQL with empty selection") - if relation.selection.count == 1 { - guard let count = relation.selection[0].count(distinct: isDistinct) else { + let selection = try relation.selectionPromise.resolve(db) + GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") + if selection.count == 1 { + guard let count = selection[0].count(distinct: isDistinct) else { return trivialCountQuery } var countQuery = self.unordered() @@ -150,7 +155,7 @@ extension SQLQuery { private var trivialCountQuery: SQLQuery { let relation = SQLRelation( source: .query(unordered()), - selection: [SQLExpressionCount(AllColumns())]) + selectionPromise: DatabasePromise(value: [SQLExpressionCount(AllColumns())])) return SQLQuery(relation: relation) } } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 3d0d154f1..90626bb7d 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -158,7 +158,7 @@ struct SQLRelation { } var source: SQLSource - var selection: [SQLSelectable] = [] + var selectionPromise: DatabasePromise<[SQLSelectable]> = DatabasePromise(value: []) // Filter is an array of expressions that we'll join with the AND operator. // This gives nicer output in generated SQL: `(a AND b AND c)` instead of // `((a AND b) AND c)`. @@ -199,24 +199,37 @@ struct SQLRelation { } extension SQLRelation: Refinable { + func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { + with(\.selectionPromise, DatabasePromise(selection)) + } + + // Convenience func select(_ selection: [SQLSelectable]) -> Self { - with(\.selection, selection) + select { _ in selection } } /// Removes all selections from chidren func selectOnly(_ selection: [SQLSelectable]) -> Self { - self.with(\.selection, selection) - .map(\.children, { $0.mapValues { $0.map(\.relation, { $0.selectOnly([]) }) } }) + select(selection).map(\.children, { $0.mapValues { $0.map(\.relation, { $0.selectOnly([]) }) } }) } + func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { + map(\.selectionPromise) { selectionPromise in + DatabasePromise { db in + try selectionPromise.resolve(db) + selection(db) + } + } + } + + // Convenience func annotated(with selection: [SQLSelectable]) -> Self { - mapInto(\.selection) { $0.append(contentsOf: selection) } + annotated(with: { _ in selection }) } func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { map(\.filtersPromise) { filtersPromise in - filtersPromise.flatMap { filters in - DatabasePromise { try filters + [predicate($0).sqlExpression] } + DatabasePromise { db in + try filtersPromise.resolve(db) + [predicate(db).sqlExpression] } } } @@ -653,8 +666,8 @@ extension SQLRelation { return nil } - let mergedFiltersPromise: DatabasePromise<[SQLExpression]> = filtersPromise.flatMap { filters in - DatabasePromise { try filters + other.filtersPromise.resolve($0) } + let mergedFiltersPromise = DatabasePromise<[SQLExpression]> { db in + try self.filtersPromise.resolve(db) + other.filtersPromise.resolve(db) } var mergedChildren: OrderedDictionary = [:] @@ -674,14 +687,21 @@ extension SQLRelation { } // replace selection unless empty - let mergedSelection = other.selection.isEmpty ? selection : other.selection + let mergedSelectionPromise = DatabasePromise { db -> [SQLSelectable] in + let otherSelection = try other.selectionPromise.resolve(db) + if otherSelection.isEmpty { + return try self.selectionPromise.resolve(db) + } else { + return otherSelection + } + } // replace ordering unless empty let mergedOrdering = other.ordering.isEmpty ? ordering : other.ordering return SQLRelation( source: mergedSource, - selection: mergedSelection, + selectionPromise: mergedSelectionPromise, filtersPromise: mergedFiltersPromise, ordering: mergedOrdering, children: mergedChildren) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index c6a34bbd2..a54738d5b 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -3,7 +3,7 @@ struct SQLQueryGenerator: Refinable { fileprivate private(set) var relation: SQLQualifiedRelation private let isDistinct: Bool private let groupPromise: DatabasePromise<[SQLExpression]>? - private let havingExpressions: [SQLExpression] + private let havingExpressionsPromise: DatabasePromise<[SQLExpression]> private let limit: SQLLimit? init(_ query: SQLQuery) { @@ -36,7 +36,7 @@ struct SQLQueryGenerator: Refinable { // `HAVING MAX(year) < 2000` INTO `HAVING MAX(book.year) < 2000`. let alias = relation.sourceAlias groupPromise = query.groupPromise?.map { $0.map { $0.qualifiedExpression(with: alias) } } - havingExpressions = query.havingExpressions.map { $0.qualifiedExpression(with: alias) } + havingExpressionsPromise = query.havingExpressionsPromise.map { $0.map { $0.qualifiedExpression(with: alias) } } // Preserve other flags isDistinct = query.isDistinct @@ -50,7 +50,7 @@ struct SQLQueryGenerator: Refinable { sql += " DISTINCT" } - let selection = relation.selection + let selection = try relation.selectionPromise.resolve(db) GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") @@ -75,6 +75,7 @@ struct SQLQueryGenerator: Refinable { .joined(separator: ", ") } + let havingExpressions = try havingExpressionsPromise.resolve(db) if havingExpressions.isEmpty == false { sql += " HAVING " sql += havingExpressions.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false) @@ -411,7 +412,7 @@ struct SQLQueryGenerator: Refinable { /// | | | • filterPromise /// | | • joins /// | • source -/// • selection +/// • selectionPromise private struct SQLQualifiedRelation { /// The source alias var sourceAlias: TableAlias { source.alias } @@ -431,16 +432,20 @@ private struct SQLQualifiedRelation { let source: SQLQualifiedSource /// The selection from source, not including selection of joined relations - private var sourceSelection: [SQLSelectable] + private var sourceSelectionPromise: DatabasePromise<[SQLSelectable]> /// The full selection, including selection of joined relations /// /// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ... /// | - /// • selection - var selection: [SQLSelectable] { - joins.reduce(into: sourceSelection) { - $0.append(contentsOf: $1.value.relation.selection) + /// • selectionPromise + var selectionPromise: DatabasePromise<[SQLSelectable]> { + DatabasePromise { db in + let selection = try self.sourceSelectionPromise.resolve(db) + return try self.joins.values.reduce(into: selection) { selection, join in + let joinedSelection = try join.relation.selectionPromise.resolve(db) + selection.append(contentsOf: joinedSelection) + } } } @@ -484,7 +489,7 @@ private struct SQLQualifiedRelation { // Qualify all joins, selection, filter, and ordering, so that all // identifiers can be correctly disambiguated and qualified. joins = relation.children.compactMapValues { SQLQualifiedJoin($0) } - sourceSelection = relation.selection.map { $0.qualifiedSelectable(with: sourceAlias) } + sourceSelectionPromise = relation.selectionPromise.map { $0.map { $0.qualifiedSelectable(with: sourceAlias) } } filtersPromise = relation.filtersPromise.map { $0.map { $0.qualifiedExpression(with: sourceAlias) } } sourceOrdering = relation.ordering.qualified(with: sourceAlias) } @@ -507,7 +512,7 @@ private struct SQLQualifiedRelation { // The number of columns in source selection. Columns selected by joined // relations are appended after. - let sourceSelectionWidth = try sourceSelection.reduce(0) { + let sourceSelectionWidth = try sourceSelectionPromise.resolve(db).reduce(0) { try $0 + $1.columnCount(db) } @@ -551,7 +556,9 @@ private struct SQLQualifiedRelation { /// Removes all selections from joins func selectOnly(_ selection: [SQLSelectable]) -> Self { - self.with(\.sourceSelection, selection.map { $0.qualifiedSelectable(with: sourceAlias) }) + let selectionPromise = DatabasePromise(value: selection.map { $0.qualifiedSelectable(with: sourceAlias) }) + return self + .with(\.sourceSelectionPromise, selectionPromise) .map(\.joins, { $0.mapValues { $0.selectOnly([]) } }) } } diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 7afa6e10c..ef9323dd2 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -547,32 +547,29 @@ extension TableRecord { // MARK: - Association Aggregates - // TODO: replace rowid with actual primary key in the doc when implemented /// Creates a request with *aggregates* appended to the selection. /// - /// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount + /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount /// // FROM player LEFT JOIN book ... /// var request = Player.annotated(with: Player.books.count) public static func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { all().annotated(with: aggregates) } - // TODO: replace rowid with actual primary key in the doc when implemented /// Creates a request with *aggregates* appended to the selection. /// - /// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount + /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount /// // FROM player LEFT JOIN book ... /// var request = Player.annotated(with: [Player.books.count]) public static func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { all().annotated(with: aggregates) } - // TODO: replace rowid with actual primary key in the doc when implemented /// Creates a request with the provided aggregate *predicate*. /// /// // SELECT player.* /// // FROM player LEFT JOIN book ... - /// // HAVING COUNT(DISTINCT book.rowid) = 0 + /// // HAVING COUNT(DISTINCT book.id) = 0 /// var request = Player.all() /// request = request.having(Player.books.isEmpty) /// diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 73aff4827..3c074e33a 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -2,6 +2,12 @@ extension TableRecord { // MARK: Request Derivation + static var relationForAll: SQLRelation { + SQLRelation( + source: .table(tableName: databaseTableName, alias: nil), + selectionPromise: DatabasePromise(value: databaseSelection)) + } + /// Creates a request which fetches all records. /// /// // SELECT * FROM player @@ -11,10 +17,7 @@ extension TableRecord { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public static func all() -> QueryInterfaceRequest { - let relation = SQLRelation( - source: .table(tableName: databaseTableName, alias: nil), - selection: databaseSelection) - return QueryInterfaceRequest(relation: relation) + QueryInterfaceRequest(relation: relationForAll) } /// Creates a request which fetches no record. diff --git a/Tests/GRDBTests/AssociationAggregateTests.swift b/Tests/GRDBTests/AssociationAggregateTests.swift index 62d2d07ba..982dd828b 100644 --- a/Tests/GRDBTests/AssociationAggregateTests.swift +++ b/Tests/GRDBTests/AssociationAggregateTests.swift @@ -18,7 +18,7 @@ private struct Player: Codable, FetchableRecord, PersistableRecord { } private struct Award: Codable, FetchableRecord, PersistableRecord { - var id: Int64 + var customPrimaryKey: Int64 var teamId: Int64? var name: String } @@ -56,7 +56,7 @@ class AssociationAggregateTests: GRDBTestCase { t.column("score", .integer) } try db.create(table: "award") { t in - t.column("id", .integer).primaryKey() + t.column("customPrimaryKey", .integer).primaryKey() t.column("teamId", .integer).references("team") t.column("name", .text) } @@ -64,16 +64,16 @@ class AssociationAggregateTests: GRDBTestCase { try Team(id: 1, name: "Reds").insert(db) try Player(id: 1, teamId: 1, name: "Arthur", score: 100).insert(db) try Player(id: 2, teamId: 1, name: "Barbara", score: 1000).insert(db) - try Award(id: 1, teamId: 1, name: "World cup 2035").insert(db) - try Award(id: 2, teamId: 1, name: "World cup 2038").insert(db) - try Award(id: 3, teamId: 1, name: "European cup 2038").insert(db) + try Award(customPrimaryKey: 1, teamId: 1, name: "World cup 2035").insert(db) + try Award(customPrimaryKey: 2, teamId: 1, name: "World cup 2038").insert(db) + try Award(customPrimaryKey: 3, teamId: 1, name: "European cup 2038").insert(db) try Team(id: 2, name: "Blues").insert(db) try Player(id: 3, teamId: 2, name: "Craig", score: 200).insert(db) try Player(id: 4, teamId: 2, name: "David", score: 500).insert(db) try Player(id: 5, teamId: 2, name: "Elise", score: 800).insert(db) - try Award(id: 4, teamId: 2, name: "European cup 2036").insert(db) + try Award(customPrimaryKey: 4, teamId: 2, name: "European cup 2036").insert(db) try Team(id: 3, name: "Greens").insert(db) - try Award(id: 5, teamId: 3, name: "World cup 2037").insert(db) + try Award(customPrimaryKey: 5, teamId: 3, name: "World cup 2037").insert(db) try Team(id: 4, name: "Oranges").insert(db) try Player(id: 6, teamId: 4, name: "Fiona", score: 0).insert(db) } @@ -88,7 +88,7 @@ class AssociationAggregateTests: GRDBTestCase { .joining(required: Team.players.aliased(tableAlias).filter(sql: "custom.score < ?", arguments: [500])) try assertEqualSQL(db, request, """ - SELECT "team".*, COUNT(DISTINCT "custom"."rowid") AS "playerCount" \ + SELECT "team".*, COUNT(DISTINCT "custom"."id") AS "playerCount" \ FROM "team" \ JOIN "player" "custom" ON ("custom"."teamId" = "team"."id") AND (custom.score < 500) \ GROUP BY "team"."id" @@ -105,7 +105,7 @@ class AssociationAggregateTests: GRDBTestCase { .group(Column("name")) try assertEqualSQL(db, request, """ - SELECT "team"."name", COUNT(DISTINCT "player"."rowid") AS "playerCount" \ + SELECT "team"."name", COUNT(DISTINCT "player"."id") AS "playerCount" \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."name" @@ -159,7 +159,7 @@ class AssociationAggregateTests: GRDBTestCase { .asRequest(of: TeamInfo.self) try assertEqualSQL(db, request, """ - SELECT "team".*, COUNT(DISTINCT "player"."rowid") AS "playerCount" \ + SELECT "team".*, COUNT(DISTINCT "player"."id") AS "playerCount" \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ @@ -200,7 +200,7 @@ class AssociationAggregateTests: GRDBTestCase { .asRequest(of: PlayerInfo.self) try assertEqualSQL(db, request, """ - SELECT "player".*, COUNT(DISTINCT "award"."rowid") AS "awardCount" \ + SELECT "player".*, COUNT(DISTINCT "award"."customPrimaryKey") AS "awardCount" \ FROM "player" \ LEFT JOIN "team" ON "team"."id" = "player"."teamId" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ @@ -396,7 +396,7 @@ class AssociationAggregateTests: GRDBTestCase { try assertEqualSQL(db, request, """ SELECT "team".*, \ AVG("player"."score") AS "averagePlayerScore", \ - COUNT(DISTINCT "player"."rowid") AS "playerCount", \ + COUNT(DISTINCT "player"."id") AS "playerCount", \ MIN("player"."score") AS "minPlayerScore", \ MAX("player"."score") AS "maxPlayerScore", \ SUM("player"."score") AS "playerScoreSum" \ @@ -489,7 +489,7 @@ class AssociationAggregateTests: GRDBTestCase { .asRequest(of: CustomTeamInfo.self) try assertEqualSQL(db, request, """ - SELECT "team".*, COUNT(DISTINCT "player"."rowid") AS "customPlayerCount" \ + SELECT "team".*, COUNT(DISTINCT "player"."id") AS "customPlayerCount" \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ @@ -642,7 +642,7 @@ class AssociationAggregateTests: GRDBTestCase { try assertEqualSQL(db, request, """ SELECT "team".*, \ AVG("player"."score") AS "averageCustomPlayerScore", \ - COUNT(DISTINCT "player"."rowid") AS "customPlayerCount", \ + COUNT(DISTINCT "player"."id") AS "customPlayerCount", \ MIN("player"."score") AS "minCustomPlayerScore", \ MAX("player"."score") AS "maxCustomPlayerScore", \ SUM("player"."score") AS "customPlayerScoreSum" \ @@ -702,7 +702,7 @@ class AssociationAggregateTests: GRDBTestCase { try assertEqualSQL(db, request, """ SELECT "team".*, \ AVG("player"."score") AS "a1", \ - COUNT(DISTINCT "player"."rowid") AS "a2", \ + COUNT(DISTINCT "player"."id") AS "a2", \ MAX("player"."score") AS "a3", \ MIN("player"."score") AS "a4", \ SUM("player"."score") AS "a5" \ @@ -750,8 +750,8 @@ class AssociationAggregateTests: GRDBTestCase { try assertEqualSQL(db, request, """ SELECT "team".*, \ - COUNT(DISTINCT "player1"."rowid") AS "lowPlayerCount", \ - COUNT(DISTINCT "player2"."rowid") AS "highPlayerCount" \ + COUNT(DISTINCT "player1"."id") AS "lowPlayerCount", \ + COUNT(DISTINCT "player2"."id") AS "highPlayerCount" \ FROM "team" \ LEFT JOIN "player" "player1" ON ("player1"."teamId" = "team"."id") AND ("player1"."score" < 500) \ LEFT JOIN "player" "player2" ON ("player2"."teamId" = "team"."id") AND ("player2"."score" >= 500) \ @@ -790,7 +790,7 @@ class AssociationAggregateTests: GRDBTestCase { do { let request = Team.annotated(with: Team.players.isEmpty) try assertEqualSQL(db, request, """ - SELECT "team".*, COUNT(DISTINCT "player"."rowid") = 0 AS "hasNoPlayer" \ + SELECT "team".*, COUNT(DISTINCT "player"."id") = 0 AS "hasNoPlayer" \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" @@ -801,7 +801,7 @@ class AssociationAggregateTests: GRDBTestCase { do { let request = Team.annotated(with: !Team.players.isEmpty) try assertEqualSQL(db, request, """ - SELECT "team".*, COUNT(DISTINCT "player"."rowid") > 0 \ + SELECT "team".*, COUNT(DISTINCT "player"."id") > 0 \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" @@ -816,7 +816,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") = 0 + HAVING COUNT(DISTINCT "player"."id") = 0 """) try XCTAssertEqual(request.fetchAll(db).count, 1) try XCTAssertEqual(request.fetchCount(db), 1) @@ -828,7 +828,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") > 0 + HAVING COUNT(DISTINCT "player"."id") > 0 """) try XCTAssertEqual(request.fetchAll(db).count, 3) try XCTAssertEqual(request.fetchCount(db), 3) @@ -840,7 +840,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") > 0 + HAVING COUNT(DISTINCT "player"."id") > 0 """) try XCTAssertEqual(request.fetchAll(db).count, 3) try XCTAssertEqual(request.fetchCount(db), 3) @@ -852,7 +852,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") = 0 + HAVING COUNT(DISTINCT "player"."id") = 0 """) try XCTAssertEqual(request.fetchAll(db).count, 1) try XCTAssertEqual(request.fetchCount(db), 1) @@ -871,7 +871,7 @@ class AssociationAggregateTests: GRDBTestCase { LEFT JOIN "team" ON "team"."id" = "player"."teamId" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ GROUP BY "player"."id" \ - HAVING COUNT(DISTINCT "award"."rowid") = 0 + HAVING COUNT(DISTINCT "award"."customPrimaryKey") = 0 """) try XCTAssertEqual(request.fetchAll(db).count, 1) try XCTAssertEqual(request.fetchCount(db), 1) @@ -884,7 +884,7 @@ class AssociationAggregateTests: GRDBTestCase { LEFT JOIN "team" ON "team"."id" = "player"."teamId" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ GROUP BY "player"."id" \ - HAVING COUNT(DISTINCT "award"."rowid") > 0 + HAVING COUNT(DISTINCT "award"."customPrimaryKey") > 0 """) try XCTAssertEqual(request.fetchAll(db).count, 5) try XCTAssertEqual(request.fetchCount(db), 5) @@ -897,7 +897,7 @@ class AssociationAggregateTests: GRDBTestCase { LEFT JOIN "team" ON "team"."id" = "player"."teamId" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ GROUP BY "player"."id" \ - HAVING COUNT(DISTINCT "award"."rowid") > 0 + HAVING COUNT(DISTINCT "award"."customPrimaryKey") > 0 """) try XCTAssertEqual(request.fetchAll(db).count, 5) try XCTAssertEqual(request.fetchCount(db), 5) @@ -910,7 +910,7 @@ class AssociationAggregateTests: GRDBTestCase { LEFT JOIN "team" ON "team"."id" = "player"."teamId" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ GROUP BY "player"."id" \ - HAVING COUNT(DISTINCT "award"."rowid") = 0 + HAVING COUNT(DISTINCT "award"."customPrimaryKey") = 0 """) try XCTAssertEqual(request.fetchAll(db).count, 1) try XCTAssertEqual(request.fetchCount(db), 1) @@ -929,7 +929,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") = 2 + HAVING COUNT(DISTINCT "player"."id") = 2 """) } do { @@ -940,7 +940,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING 2 = COUNT(DISTINCT "player"."rowid") + HAVING 2 = COUNT(DISTINCT "player"."id") """) } do { @@ -952,7 +952,7 @@ class AssociationAggregateTests: GRDBTestCase { LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") = COUNT(DISTINCT "award"."rowid") + HAVING COUNT(DISTINCT "player"."id") = COUNT(DISTINCT "award"."customPrimaryKey") """) } } @@ -969,7 +969,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") <> 2 + HAVING COUNT(DISTINCT "player"."id") <> 2 """) } do { @@ -980,7 +980,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING 2 <> COUNT(DISTINCT "player"."rowid") + HAVING 2 <> COUNT(DISTINCT "player"."id") """) } do { @@ -992,7 +992,7 @@ class AssociationAggregateTests: GRDBTestCase { LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") <> COUNT(DISTINCT "award"."rowid") + HAVING COUNT(DISTINCT "player"."id") <> COUNT(DISTINCT "award"."customPrimaryKey") """) } } @@ -1009,7 +1009,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") >= 2 + HAVING COUNT(DISTINCT "player"."id") >= 2 """) } do { @@ -1020,7 +1020,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING 2 >= COUNT(DISTINCT "player"."rowid") + HAVING 2 >= COUNT(DISTINCT "player"."id") """) } do { @@ -1032,7 +1032,7 @@ class AssociationAggregateTests: GRDBTestCase { LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") >= COUNT(DISTINCT "award"."rowid") + HAVING COUNT(DISTINCT "player"."id") >= COUNT(DISTINCT "award"."customPrimaryKey") """) } } @@ -1049,7 +1049,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") > 2 + HAVING COUNT(DISTINCT "player"."id") > 2 """) } do { @@ -1060,7 +1060,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING 2 > COUNT(DISTINCT "player"."rowid") + HAVING 2 > COUNT(DISTINCT "player"."id") """) } do { @@ -1072,7 +1072,7 @@ class AssociationAggregateTests: GRDBTestCase { LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") > COUNT(DISTINCT "award"."rowid") + HAVING COUNT(DISTINCT "player"."id") > COUNT(DISTINCT "award"."customPrimaryKey") """) } } @@ -1089,7 +1089,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") <= 2 + HAVING COUNT(DISTINCT "player"."id") <= 2 """) } do { @@ -1100,7 +1100,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING 2 <= COUNT(DISTINCT "player"."rowid") + HAVING 2 <= COUNT(DISTINCT "player"."id") """) } do { @@ -1112,7 +1112,7 @@ class AssociationAggregateTests: GRDBTestCase { LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") <= COUNT(DISTINCT "award"."rowid") + HAVING COUNT(DISTINCT "player"."id") <= COUNT(DISTINCT "award"."customPrimaryKey") """) } } @@ -1129,7 +1129,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") < 2 + HAVING COUNT(DISTINCT "player"."id") < 2 """) } do { @@ -1140,7 +1140,7 @@ class AssociationAggregateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING 2 < COUNT(DISTINCT "player"."rowid") + HAVING 2 < COUNT(DISTINCT "player"."id") """) } do { @@ -1152,7 +1152,7 @@ class AssociationAggregateTests: GRDBTestCase { LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") < COUNT(DISTINCT "award"."rowid") + HAVING COUNT(DISTINCT "player"."id") < COUNT(DISTINCT "award"."customPrimaryKey") """) } } @@ -1170,7 +1170,7 @@ class AssociationAggregateTests: GRDBTestCase { LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING (COUNT(DISTINCT "player"."rowid") = 0) AND (COUNT(DISTINCT "award"."rowid") = 0) + HAVING (COUNT(DISTINCT "player"."id") = 0) AND (COUNT(DISTINCT "award"."customPrimaryKey") = 0) """) } do { @@ -1182,7 +1182,7 @@ class AssociationAggregateTests: GRDBTestCase { LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING (COUNT(DISTINCT "player"."rowid") = 0) OR (COUNT(DISTINCT "award"."rowid") = 0) + HAVING (COUNT(DISTINCT "player"."id") = 0) OR (COUNT(DISTINCT "award"."customPrimaryKey") = 0) """) } do { @@ -1194,7 +1194,7 @@ class AssociationAggregateTests: GRDBTestCase { LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING NOT ((COUNT(DISTINCT "player"."rowid") = 0) OR (COUNT(DISTINCT "award"."rowid") = 0)) + HAVING NOT ((COUNT(DISTINCT "player"."id") = 0) OR (COUNT(DISTINCT "award"."customPrimaryKey") = 0)) """) } do { @@ -1206,7 +1206,7 @@ class AssociationAggregateTests: GRDBTestCase { LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING (NOT (COUNT(DISTINCT "player"."rowid") > 3)) OR (COUNT(DISTINCT "award"."rowid") = 0) + HAVING (NOT (COUNT(DISTINCT "player"."id") > 3)) OR (COUNT(DISTINCT "award"."customPrimaryKey") = 0) """) } } @@ -1219,7 +1219,7 @@ class AssociationAggregateTests: GRDBTestCase { let request = Team.annotated(with: -Team.players.count) try assertEqualSQL(db, request, """ - SELECT "team".*, -COUNT(DISTINCT "player"."rowid") \ + SELECT "team".*, -COUNT(DISTINCT "player"."id") \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" @@ -1235,7 +1235,7 @@ class AssociationAggregateTests: GRDBTestCase { let request = Team.annotated(with: Team.players.count + 2) try assertEqualSQL(db, request, """ - SELECT "team".*, COUNT(DISTINCT "player"."rowid") + 2 \ + SELECT "team".*, COUNT(DISTINCT "player"."id") + 2 \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" @@ -1245,7 +1245,7 @@ class AssociationAggregateTests: GRDBTestCase { let request = Team.annotated(with: 2 + Team.players.count) try assertEqualSQL(db, request, """ - SELECT "team".*, 2 + COUNT(DISTINCT "player"."rowid") \ + SELECT "team".*, 2 + COUNT(DISTINCT "player"."id") \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" @@ -1255,7 +1255,7 @@ class AssociationAggregateTests: GRDBTestCase { let request = Team.annotated(with: Team.players.count + Team.awards.count) try assertEqualSQL(db, request, """ - SELECT "team".*, COUNT(DISTINCT "player"."rowid") + COUNT(DISTINCT "award"."rowid") \ + SELECT "team".*, COUNT(DISTINCT "player"."id") + COUNT(DISTINCT "award"."customPrimaryKey") \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ @@ -1272,7 +1272,7 @@ class AssociationAggregateTests: GRDBTestCase { let request = Team.annotated(with: Team.players.count - 2) try assertEqualSQL(db, request, """ - SELECT "team".*, COUNT(DISTINCT "player"."rowid") - 2 \ + SELECT "team".*, COUNT(DISTINCT "player"."id") - 2 \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" @@ -1282,7 +1282,7 @@ class AssociationAggregateTests: GRDBTestCase { let request = Team.annotated(with: 2 - Team.players.count) try assertEqualSQL(db, request, """ - SELECT "team".*, 2 - COUNT(DISTINCT "player"."rowid") \ + SELECT "team".*, 2 - COUNT(DISTINCT "player"."id") \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" @@ -1292,7 +1292,7 @@ class AssociationAggregateTests: GRDBTestCase { let request = Team.annotated(with: Team.players.count - Team.awards.count) try assertEqualSQL(db, request, """ - SELECT "team".*, COUNT(DISTINCT "player"."rowid") - COUNT(DISTINCT "award"."rowid") \ + SELECT "team".*, COUNT(DISTINCT "player"."id") - COUNT(DISTINCT "award"."customPrimaryKey") \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ @@ -1309,7 +1309,7 @@ class AssociationAggregateTests: GRDBTestCase { let request = Team.annotated(with: Team.players.count * 2) try assertEqualSQL(db, request, """ - SELECT "team".*, COUNT(DISTINCT "player"."rowid") * 2 \ + SELECT "team".*, COUNT(DISTINCT "player"."id") * 2 \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" @@ -1319,7 +1319,7 @@ class AssociationAggregateTests: GRDBTestCase { let request = Team.annotated(with: 2 * Team.players.count) try assertEqualSQL(db, request, """ - SELECT "team".*, 2 * COUNT(DISTINCT "player"."rowid") \ + SELECT "team".*, 2 * COUNT(DISTINCT "player"."id") \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" @@ -1329,7 +1329,7 @@ class AssociationAggregateTests: GRDBTestCase { let request = Team.annotated(with: Team.players.count * Team.awards.count) try assertEqualSQL(db, request, """ - SELECT "team".*, COUNT(DISTINCT "player"."rowid") * COUNT(DISTINCT "award"."rowid") \ + SELECT "team".*, COUNT(DISTINCT "player"."id") * COUNT(DISTINCT "award"."customPrimaryKey") \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ @@ -1346,7 +1346,7 @@ class AssociationAggregateTests: GRDBTestCase { let request = Team.annotated(with: Team.players.count / 2) try assertEqualSQL(db, request, """ - SELECT "team".*, COUNT(DISTINCT "player"."rowid") / 2 \ + SELECT "team".*, COUNT(DISTINCT "player"."id") / 2 \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" @@ -1356,7 +1356,7 @@ class AssociationAggregateTests: GRDBTestCase { let request = Team.annotated(with: 2 / Team.players.count) try assertEqualSQL(db, request, """ - SELECT "team".*, 2 / COUNT(DISTINCT "player"."rowid") \ + SELECT "team".*, 2 / COUNT(DISTINCT "player"."id") \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" @@ -1366,7 +1366,7 @@ class AssociationAggregateTests: GRDBTestCase { let request = Team.annotated(with: Team.players.count / Team.awards.count) try assertEqualSQL(db, request, """ - SELECT "team".*, COUNT(DISTINCT "player"."rowid") / COUNT(DISTINCT "award"."rowid") \ + SELECT "team".*, COUNT(DISTINCT "player"."id") / COUNT(DISTINCT "award"."customPrimaryKey") \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ LEFT JOIN "award" ON "award"."teamId" = "team"."id" \ diff --git a/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift b/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift index a22d34815..009cccf3a 100644 --- a/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift @@ -229,7 +229,7 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") = 0) + HAVING COUNT(DISTINCT "player"."id") = 0) """) } do { diff --git a/Tests/GRDBTests/MutablePersistableRecordUpdateTests.swift b/Tests/GRDBTests/MutablePersistableRecordUpdateTests.swift index dc22d59d0..46724f55a 100644 --- a/Tests/GRDBTests/MutablePersistableRecordUpdateTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordUpdateTests.swift @@ -456,7 +456,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ - HAVING COUNT(DISTINCT "player"."rowid") = 0) + HAVING COUNT(DISTINCT "player"."id") = 0) """) } do {