mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-30 04:28:44 +00:00
Turn selection and having clauses into promises. Give association aggregates access to the actual primary key, for better support for WITHOUT ROW ID tables.
This commit is contained in:
1 parent
b38ccb5f40
commit
d0ba9e342c
17 files changed
+310
-409
No files matched your search
@@ -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) }
|
||||
}
|
||||
|
||||
|
||||
@@ -2,20 +2,25 @@ import Foundation
|
||||
|
||||
typealias AssociationAggregatePreparation<RowDecoder> =
|
||||
(QueryInterfaceRequest<RowDecoder>)
|
||||
-> (request: QueryInterfaceRequest<RowDecoder>, expression: SQLExpression)
|
||||
-> (request: QueryInterfaceRequest<RowDecoder>, expressionPromise: DatabasePromise<SQLExpression>)
|
||||
|
||||
extension AssociationToMany {
|
||||
private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate<OriginRowDecoder> {
|
||||
private func makeAggregate(_ expressionPromise: DatabasePromise<SQLExpression>) -> AssociationAggregate<OriginRowDecoder> {
|
||||
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<OriginRowDecoder> {
|
||||
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<OriginRowDecoder> {
|
||||
// TODO: try to replace rowid with actual primary key
|
||||
makeAggregate(SQLExpressionCountDistinct(Column.rowID))
|
||||
.forKey("\(key.singularizedName)Count")
|
||||
let expression = DatabasePromise<SQLExpression> { 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<OriginRowDecoder> {
|
||||
// TODO: try to replace rowid with actual primary key
|
||||
makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID)))
|
||||
.forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
|
||||
let expression = DatabasePromise<SQLExpression> { 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<RowDecoder> {
|
||||
// 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<RowDecoder> {
|
||||
///
|
||||
/// // 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<SQLExpression> { 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 ! <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
|
||||
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 && <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 && <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 && <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 || <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 || <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 || <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 == <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 == <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 == <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 == <RowDecoder>(
|
||||
///
|
||||
/// Author.having(Author.books.isEmpty == false)
|
||||
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) -> AssociationAggregate<RowDecoder> {
|
||||
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 == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) ->
|
||||
///
|
||||
/// Author.having(false == Author.books.isEmpty)
|
||||
public func == <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
|
||||
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 != <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 != <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 != <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 != <RowDecoder>(
|
||||
///
|
||||
/// Author.having(Author.books.isEmpty != true)
|
||||
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) -> AssociationAggregate<RowDecoder> {
|
||||
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 != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) ->
|
||||
///
|
||||
/// Author.having(true != Author.books.isEmpty)
|
||||
public func != <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
|
||||
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 === <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 === <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 === <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 !== <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 !== <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 !== <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 <= <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 <= <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 <= <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 < <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 < <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 < <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 > <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 > <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 > <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 >= <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 >= <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 >= <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 >= <RowDecoder>(
|
||||
///
|
||||
/// Author.annotated(with: -Author.books.count)
|
||||
public prefix func - <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
|
||||
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 + <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 + <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 + <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 - <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 - <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 - <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 * <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 * <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 * <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 / <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 / <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 / <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
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 ?? <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
var aggregate = AssociationAggregate<RowDecoder> { 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)
|
||||
|
||||
@@ -96,7 +96,7 @@ public struct BelongsToAssociation<Origin: TableRecord, Destination: TableRecord
|
||||
sqlAssociation = SQLAssociation(
|
||||
key: associationKey,
|
||||
condition: condition,
|
||||
relation: Destination.all().relation,
|
||||
relation: Destination.relationForAll,
|
||||
cardinality: .toOne)
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,7 @@ public struct HasManyAssociation<Origin: TableRecord, Destination: TableRecord>:
|
||||
sqlAssociation = SQLAssociation(
|
||||
key: associationKey,
|
||||
condition: condition,
|
||||
relation: Destination.all().relation,
|
||||
relation: Destination.relationForAll,
|
||||
cardinality: .toMany)
|
||||
}
|
||||
}
|
||||
@@ -98,7 +98,7 @@ public struct HasOneAssociation<Origin: TableRecord, Destination: TableRecord>:
|
||||
sqlAssociation = SQLAssociation(
|
||||
key: associationKey,
|
||||
condition: condition,
|
||||
relation: Destination.all().relation,
|
||||
relation: Destination.relationForAll,
|
||||
cardinality: .toOne)
|
||||
}
|
||||
}
|
||||
@@ -5,16 +5,15 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
|
||||
private func annotated(with aggregate: AssociationAggregate<RowDecoder>) -> 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<RowDecoder>) -> QueryInterfaceRequest {
|
||||
let (request, expression) = predicate.prepare(self)
|
||||
return request.having(expression)
|
||||
return request.having(expression.resolve)
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -41,10 +41,4 @@ struct DatabasePromise<T> {
|
||||
try transform(self.resolve(db))
|
||||
}
|
||||
}
|
||||
|
||||
func flatMap<U>(_ transform: @escaping (T) -> DatabasePromise<U>) -> DatabasePromise<U> {
|
||||
DatabasePromise<U> { db in
|
||||
try transform(self.resolve(db)).resolve(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<String, SQLRelation.Child> = [:]
|
||||
@@ -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)
|
||||
|
||||
@@ -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([]) } })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Self>...) -> QueryInterfaceRequest<Self> {
|
||||
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<Self>]) -> QueryInterfaceRequest<Self> {
|
||||
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)
|
||||
///
|
||||
|
||||
@@ -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<Self> {
|
||||
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.
|
||||
|
||||
Reference in new issue
Block a user