From a4dca3390a806a02254fc938fee744e9effbcd89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Mar 2021 19:15:09 +0100 Subject: [PATCH] AggregateJoinableRequest is the new protocol that supports aggregate annotations AssociationToMany is a subprotocol of AggregateJoinableRequest :-) --- .../Request/Association/Association.swift | 151 ++++++++++-------- .../Association/AssociationAggregate.swift | 134 ++++++++++++---- .../Request/QueryInterfaceRequest.swift | 52 +----- .../Request/RequestProtocols.swift | 53 ++++++ 4 files changed, 244 insertions(+), 146 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index d04576c0a..90a796792 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -72,13 +72,12 @@ extension Association { } extension Association { - private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self { + fileprivate func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self { .init(sqlAssociation: _sqlAssociation.map(\.destination.relation, transform)) } } extension Association { - /// The association key defines how rows fetched from this association /// should be consumed. /// @@ -105,6 +104,67 @@ extension Association { /// } var key: SQLAssociationKey { _sqlAssociation.destination.key } + /// Creates an association with the given key. + /// + /// This new key helps Decodable records decode rows fetched from the + /// resulting association: + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// struct PlayerInfo: FetchableRecord, Decodable { + /// let player: Player + /// let team: Team + /// + /// static func all() -> QueryInterfaceRequest { + /// return Player + /// .including(required: Player.team.forKey(CodingKeys.team)) + /// .asRequest(of: PlayerInfo.self) + /// } + /// } + /// + /// let playerInfos = PlayerInfo.all().fetchAll(db) + /// print(playerInfos.first?.team) + public func forKey(_ codingKey: CodingKey) -> Self { + forKey(codingKey.stringValue) + } + + /// Creates an association that allows you to define expressions that target + /// a specific database table. + /// + /// In the example below, the "team.color = 'red'" condition in the where + /// clause could be not achieved without table aliases. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // JOIN team ON ... + /// // WHERE team.color = 'red' + /// let teamAlias = TableAlias() + /// let request = Player + /// .including(required: Player.team.aliased(teamAlias)) + /// .filter(teamAlias[Column("color")] == "red") + /// + /// When you give a name to a table alias, you can reliably inject sql + /// snippets in your requests: + /// + /// // SELECT player.*, custom.* + /// // JOIN team custom ON ... + /// // WHERE custom.color = 'red' + /// let teamAlias = TableAlias(name: "custom") + /// let request = Player + /// .including(required: Player.team.aliased(teamAlias)) + /// .filter(sql: "custom.color = ?", arguments: ["red"]) + public func aliased(_ alias: TableAlias) -> Self { + mapDestinationRelation { $0.aliased(alias) } + } +} + +extension Association where Self: SelectionRequest { + /// Creates an association which selects *selection*. /// /// struct Player: TableRecord { @@ -146,7 +206,9 @@ extension Association { public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { mapDestinationRelation { $0.annotated { try selection($0).map(\.sqlSelection) } } } - +} + +extension Association where Self: FilteredRequest { /// Creates an association with the provided *predicate promise* added to /// the eventual set of already applied predicates. /// @@ -162,7 +224,9 @@ extension Association { public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { mapDestinationRelation { $0.filter { try predicate($0).sqlExpression } } } - +} + +extension Association where Self: OrderedRequest { /// Creates an association with the provided *orderings promise*. /// /// struct Player: TableRecord { @@ -229,71 +293,24 @@ extension Association { public func unordered() -> Self { mapDestinationRelation { $0.unordered() } } - - /// Creates an association with the given key. - /// - /// This new key helps Decodable records decode rows fetched from the - /// resulting association: - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// struct PlayerInfo: FetchableRecord, Decodable { - /// let player: Player - /// let team: Team - /// - /// static func all() -> QueryInterfaceRequest { - /// return Player - /// .including(required: Player.team.forKey(CodingKeys.team)) - /// .asRequest(of: PlayerInfo.self) - /// } - /// } - /// - /// let playerInfos = PlayerInfo.all().fetchAll(db) - /// print(playerInfos.first?.team) - public func forKey(_ codingKey: CodingKey) -> Self { - forKey(codingKey.stringValue) - } - - /// Creates an association that allows you to define expressions that target - /// a specific database table. - /// - /// In the example below, the "team.color = 'red'" condition in the where - /// clause could be not achieved without table aliases. - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// // SELECT player.*, team.* - /// // JOIN team ON ... - /// // WHERE team.color = 'red' - /// let teamAlias = TableAlias() - /// let request = Player - /// .including(required: Player.team.aliased(teamAlias)) - /// .filter(teamAlias[Column("color")] == "red") - /// - /// When you give a name to a table alias, you can reliably inject sql - /// snippets in your requests: - /// - /// // SELECT player.*, custom.* - /// // JOIN team custom ON ... - /// // WHERE custom.color = 'red' - /// let teamAlias = TableAlias(name: "custom") - /// let request = Player - /// .including(required: Player.team.aliased(teamAlias)) - /// .filter(sql: "custom.color = ?", arguments: ["red"]) - public func aliased(_ alias: TableAlias) -> Self { - mapDestinationRelation { $0.aliased(alias) } +} + +extension Association where Self: TableRequest { + public var databaseTableName: String { + _sqlAssociation.destination.relation.source.tableName } } -// TableRequest -extension Association { - /// :nodoc: - public var databaseTableName: String { - _sqlAssociation.destination.relation.source.tableName +extension Association where Self: AggregatingRequest { + /// Creates an association grouped according to *expressions promise*. + public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self { + mapDestinationRelation { $0.group { try expressions($0).map(\.sqlExpression) } } + } + + /// Creates an association with the provided *predicate promise* added to + /// the eventual set of already applied predicates. + public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { + mapDestinationRelation { $0.having { try predicate($0).sqlExpression } } } } @@ -312,7 +329,7 @@ extension AssociationToOne { // MARK: - AssociationToMany /// The base protocol for all associations that define a one-to-many connection. -public protocol AssociationToMany: Association { } +public protocol AssociationToMany: Association, AggregateJoinableRequest { } extension AssociationToMany { public func forKey(_ key: String) -> Self { diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 6163a2cf2..78aaf6b04 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -1,20 +1,10 @@ import Foundation -typealias AssociationAggregatePreparation = - (inout QueryInterfaceRequest) - -> DatabasePromise - extension AssociationToMany { private func makeAggregate(_ expressionPromise: DatabasePromise) -> AssociationAggregate { - AssociationAggregate { request in - let tableAlias = TableAlias() - request = request - .joining(optional: self.aliased(tableAlias)) - .groupByPrimaryKey() - return expressionPromise.map { tableAlias[$0] } - } + AssociationAggregate(preparation: BasePreparation(association: self, expressionPromise: expressionPromise)) } // Convenience @@ -194,8 +184,13 @@ extension AssociationToMany { /// // Won't compile because Fruit is not Author. /// let request = Fruit.annotated(with: bookCount) public struct AssociationAggregate { - /// Extend the request with the associated records used to compute the - /// aggregate, and return an expression promise which resolves to the + fileprivate let preparation: AssociationAggregatePreparation + + /// The SQL name for the value of this aggregate. See forKey(_:). + var key: String? = nil + + /// Extends the request with the associated records used to compute the + /// aggregate, and returns an expression promise which resolves to the /// aggregated value. /// /// For example: @@ -227,10 +222,12 @@ public struct AssociationAggregate { /// - We don't know yet if the aggregated value will be used in the /// SQL selection, or in the HAVING clause. /// - It helps implementing aggregate operators such as `&&`, `+`, etc. - let prepare: AssociationAggregatePreparation + func prepare(_ request: inout Request) -> DatabasePromise + where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder + { + preparation.prepare(&request) + } - /// The SQL name for the value of this aggregate. See forKey(_:). - var key: String? = nil } extension AssociationAggregate: Refinable { @@ -265,11 +262,100 @@ extension AssociationAggregate: Refinable { public func forKey(_ key: CodingKey) -> Self { forKey(key.stringValue) } +} + +// MARK: - AssociationAggregatePreparation + +/// An abstract class that workarounds the lack of generic closures in Swift. +/// +/// It only exists as support for `AssociationAggregate.prepare(_:)`. +private class AssociationAggregatePreparation { + func prepare(_ request: inout Request) + -> DatabasePromise + where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder + { + fatalError("subclass must override") + } +} + +// swiftlint:disable:next colon +private class BasePreparation: + AssociationAggregatePreparation +{ + private let association: Association + private let expressionPromise: DatabasePromise + init(association: Association, expressionPromise: DatabasePromise) { + self.association = association + self.expressionPromise = expressionPromise + } + + override func prepare(_ request: inout Request) + -> DatabasePromise + where Request: AggregateJoinableRequest, Request.RowDecoder == Association.OriginRowDecoder + { + let tableAlias = TableAlias() + request = request + .joining(optional: association.aliased(tableAlias)) + .groupByPrimaryKey() + return expressionPromise.map { tableAlias[$0] } + } +} + +/// Transforms the expression of an aggregate. +private class MapPreparation: AssociationAggregatePreparation { + private let base: AssociationAggregatePreparation + private let transform: (SQLExpression) throws -> SQLExpression + + init( + base: AssociationAggregatePreparation, + transform: @escaping (SQLExpression) throws -> SQLExpression) + { + self.base = base + self.transform = transform + } + + override func prepare(_ request: inout Request) + -> DatabasePromise + where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder + { + base.prepare(&request).map(transform) + } +} + +extension AssociationAggregate { /// Transforms the expression, and does not preserve key. fileprivate func map(_ transform: @escaping (SQLExpression) throws -> SQLExpression) -> Self { - AssociationAggregate { request in - self.prepare(&request).map(transform) + AssociationAggregate(preparation: MapPreparation(base: preparation, transform: transform)) + } +} + +/// Combines the expressions of two aggregates. +private class CombinePreparation: AssociationAggregatePreparation { + private let lhs: AssociationAggregatePreparation + private let rhs: AssociationAggregatePreparation + private let combine: (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression + + init( + _ lhs: AssociationAggregatePreparation, + _ rhs: AssociationAggregatePreparation, + combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression) + { + self.lhs = lhs + self.rhs = rhs + self.combine = combine + } + + override func prepare(_ request: inout Request) + -> DatabasePromise + where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder + { + let lhsPromise = lhs.prepare(&request) + let rhsPromise = rhs.prepare(&request) + return DatabasePromise { [combine] db in + try combine( + lhsPromise.resolve(db), + rhsPromise.resolve(db)) } } } @@ -278,18 +364,10 @@ extension AssociationAggregate: Refinable { private func combine( _ lhs: AssociationAggregate, _ rhs: AssociationAggregate, - with combineExpressions : @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression) + with combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression) -> AssociationAggregate { - AssociationAggregate { request in - let lhsPromise = lhs.prepare(&request) - let rhsPromise = rhs.prepare(&request) - return DatabasePromise { db in - try combineExpressions( - lhsPromise.resolve(db), - rhsPromise.resolve(db)) - } - } + AssociationAggregate(preparation: CombinePreparation(lhs.preparation, rhs.preparation, combine: combine)) } // MARK: - Logical Operators (AND, OR, NOT) diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 7aabf8770..1e91e60ec 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -299,6 +299,7 @@ extension QueryInterfaceRequest: TableRequest { } extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { } +extension QueryInterfaceRequest: AggregateJoinableRequest where RowDecoder: TableRecord { } extension QueryInterfaceRequest { /// Creates a request which returns distinct rows. @@ -343,57 +344,6 @@ extension QueryInterfaceRequest { } } -// MARK: - Aggregates - -extension QueryInterfaceRequest { - - private func annotated(with aggregate: AssociationAggregate) -> QueryInterfaceRequest { - var request = self - let expressionPromise = aggregate.prepare(&request) - if let key = aggregate.key { - return request.annotated(with: { db in try [expressionPromise.resolve(db).forKey(key)] }) - } else { - return request.annotated(with: { db in try [expressionPromise.resolve(db)] }) - } - } - - /// Creates a request which appends *aggregates* to the current selection. - /// - /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount - /// // FROM player LEFT JOIN book ... - /// var request = Player.all() - /// request = request.annotated(with: Player.books.count) - public func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { - annotated(with: aggregates) - } - - /// Creates a request which appends *aggregates* to the current selection. - /// - /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount - /// // FROM player LEFT JOIN book ... - /// var request = Player.all() - /// request = request.annotated(with: [Player.books.count]) - public func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { - aggregates.reduce(self) { request, aggregate in - request.annotated(with: aggregate) - } - } - - /// 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.id) = 0 - /// var request = Player.all() - /// request = request.having(Player.books.isEmpty) - public func having(_ predicate: AssociationAggregate) -> QueryInterfaceRequest { - var request = self - let expressionPromise = predicate.prepare(&request) - return request.having(expressionPromise.resolve) - } -} - // MARK: - Batch Delete extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 347206c29..4be01a31d 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -591,3 +591,56 @@ extension JoinableRequest { /// The base protocol for all requests that can be refined. public protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest { } + +// MARK: - AggregateJoinableRequest + +/// The base protocol for all requests that can use association aggregates. +public protocol AggregateJoinableRequest: AggregatingRequest & JoinableRequest & SelectionRequest & TableRequest { } + +extension AggregateJoinableRequest { + private func annotated(with aggregate: AssociationAggregate) -> Self { + var request = self + let expressionPromise = aggregate.prepare(&request) + if let key = aggregate.key { + return request.annotated(with: { db in try [expressionPromise.resolve(db).forKey(key)] }) + } else { + return request.annotated(with: { db in try [expressionPromise.resolve(db)] }) + } + } + + /// Creates a request which appends *aggregates* to the current selection. + /// + /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount + /// // FROM player LEFT JOIN book ... + /// var request = Player.all() + /// request = request.annotated(with: Player.books.count) + public func annotated(with aggregates: AssociationAggregate...) -> Self { + annotated(with: aggregates) + } + + /// Creates a request which appends *aggregates* to the current selection. + /// + /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount + /// // FROM player LEFT JOIN book ... + /// var request = Player.all() + /// request = request.annotated(with: [Player.books.count]) + public func annotated(with aggregates: [AssociationAggregate]) -> Self { + aggregates.reduce(self) { request, aggregate in + request.annotated(with: aggregate) + } + } + + /// 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.id) = 0 + /// var request = Player.all() + /// request = request.having(Player.books.isEmpty) + public func having(_ predicate: AssociationAggregate) -> Self { + var request = self + let expressionPromise = predicate.prepare(&request) + return request.having(expressionPromise.resolve) + } +}