AggregateJoinableRequest is the new protocol that supports aggregate annotations

AssociationToMany is a subprotocol of AggregateJoinableRequest :-)
This commit is contained in:
Gwendal Roué committed 2021-03-07 19:15:09 +01:00
1 parent ea6a052b73
commit a4dca3390a
4 files changed
+244 -146

No files matched your search

@@ -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<PlayerInfo> {
/// 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<PlayerInfo> {
/// 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 {
@@ -1,20 +1,10 @@
import Foundation
typealias AssociationAggregatePreparation<RowDecoder> =
(inout QueryInterfaceRequest<RowDecoder>)
-> DatabasePromise<SQLExpression>
extension AssociationToMany {
private func makeAggregate(_ expressionPromise: DatabasePromise<SQLExpression>)
-> AssociationAggregate<OriginRowDecoder>
{
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<RowDecoder> {
/// 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<RowDecoder>
/// 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<RowDecoder> {
/// - 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<RowDecoder>
func prepare<Request>(_ request: inout Request) -> DatabasePromise<SQLExpression>
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<RowDecoder> {
func prepare<Request>(_ request: inout Request)
-> DatabasePromise<SQLExpression>
where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder
{
fatalError("subclass must override")
}
}
// swiftlint:disable:next colon
private class BasePreparation<Association: AssociationToMany>:
AssociationAggregatePreparation<Association.OriginRowDecoder>
{
private let association: Association
private let expressionPromise: DatabasePromise<SQLExpression>
init(association: Association, expressionPromise: DatabasePromise<SQLExpression>) {
self.association = association
self.expressionPromise = expressionPromise
}
override func prepare<Request>(_ request: inout Request)
-> DatabasePromise<SQLExpression>
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<RowDecoder>: AssociationAggregatePreparation<RowDecoder> {
private let base: AssociationAggregatePreparation<RowDecoder>
private let transform: (SQLExpression) throws -> SQLExpression
init(
base: AssociationAggregatePreparation<RowDecoder>,
transform: @escaping (SQLExpression) throws -> SQLExpression)
{
self.base = base
self.transform = transform
}
override func prepare<Request>(_ request: inout Request)
-> DatabasePromise<SQLExpression>
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<RowDecoder>: AssociationAggregatePreparation<RowDecoder> {
private let lhs: AssociationAggregatePreparation<RowDecoder>
private let rhs: AssociationAggregatePreparation<RowDecoder>
private let combine: (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression
init(
_ lhs: AssociationAggregatePreparation<RowDecoder>,
_ rhs: AssociationAggregatePreparation<RowDecoder>,
combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression)
{
self.lhs = lhs
self.rhs = rhs
self.combine = combine
}
override func prepare<Request>(_ request: inout Request)
-> DatabasePromise<SQLExpression>
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<RowDecoder>(
_ lhs: AssociationAggregate<RowDecoder>,
_ rhs: AssociationAggregate<RowDecoder>,
with combineExpressions : @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression)
with combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression)
-> AssociationAggregate<RowDecoder>
{
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)
@@ -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<RowDecoder>) -> 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<RowDecoder>...) -> 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<RowDecoder>]) -> 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<RowDecoder>) -> QueryInterfaceRequest {
var request = self
let expressionPromise = predicate.prepare(&request)
return request.having(expressionPromise.resolve)
}
}
// MARK: - Batch Delete
extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
@@ -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<RowDecoder>) -> 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<RowDecoder>...) -> 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<RowDecoder>]) -> 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<RowDecoder>) -> Self {
var request = self
let expressionPromise = predicate.prepare(&request)
return request.having(expressionPromise.resolve)
}
}