Merge SQLQuery into SQLRelation

This commit is contained in:
Gwendal Roué committed 2021-03-07 14:37:53 +01:00
1 parent 37faf0a1fd
commit f49fab0cff
8 files changed
+247 -361

No files matched your search

@@ -444,7 +444,7 @@ extension QueryInterfaceRequest {
/// - parameter cte: A common table expression.
/// - returns: A request.
public func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self {
with(\.query.ctes[cte.tableName], cte.cte)
with(\.relation.ctes[cte.tableName], cte.cte)
}
}
@@ -29,24 +29,18 @@
///
/// See https://github.com/groue/GRDB.swift#the-query-interface
public struct QueryInterfaceRequest<RowDecoder> {
var query: SQLQuery
}
extension QueryInterfaceRequest {
init(relation: SQLRelation) {
self.init(query: SQLQuery(relation: relation))
}
var relation: SQLRelation
}
extension QueryInterfaceRequest: Refinable { }
extension QueryInterfaceRequest: FetchRequest {
public var sqlSubquery: SQLSubquery {
.query(query)
.relation(relation)
}
public func fetchCount(_ db: Database) throws -> Int {
try query.fetchCount(db)
try relation.fetchCount(db)
}
public func makePreparedRequest(
@@ -54,13 +48,13 @@ extension QueryInterfaceRequest: FetchRequest {
forSingleResult singleResult: Bool = false)
throws -> PreparedRequest
{
let generator = SQLQueryGenerator(query: query, forSingleResult: singleResult)
let generator = SQLQueryGenerator(relation: relation, forSingleResult: singleResult)
var preparedRequest = try generator.makePreparedRequest(db)
let associations = query.relation.prefetchedAssociations
let associations = relation.prefetchedAssociations
if associations.isEmpty == false {
// Eager loading of prefetched associations
preparedRequest = preparedRequest.with(\.supplementaryFetch) { [query] db, rows in
try prefetch(db, associations: associations, from: query, into: rows)
preparedRequest = preparedRequest.with(\.supplementaryFetch) { [relation] db, rows in
try prefetch(db, associations: associations, from: relation, into: rows)
}
}
return preparedRequest
@@ -83,7 +77,7 @@ extension QueryInterfaceRequest: SelectionRequest {
/// .select { db in [Column("id")] }
/// .select { db in [Column("email")] }
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
map(\.query) { $0.select { try selection($0).map(\.sqlSelection) } }
map(\.relation) { $0.select { try selection($0).map(\.sqlSelection) } }
}
/// Creates a request which selects *selection*, and fetches values of
@@ -174,7 +168,7 @@ extension QueryInterfaceRequest: SelectionRequest {
/// .select([Column("id"), Column("email")])
/// .annotated(with: { db in [Column("name")] })
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
map(\.query) { $0.annotated { try selection($0).map(\.sqlSelection) } }
map(\.relation) { $0.annotated { try selection($0).map(\.sqlSelection) } }
}
}
@@ -186,7 +180,7 @@ extension QueryInterfaceRequest: FilteredRequest {
/// var request = Player.all()
/// request = request.filter { db in true }
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
map(\.query) { $0.filter { try predicate($0).sqlExpression } }
map(\.relation) { $0.filter { try predicate($0).sqlExpression } }
}
}
@@ -205,7 +199,7 @@ extension QueryInterfaceRequest: OrderedRequest {
/// .reversed()
/// .order{ _ in [Column("name")] }
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest {
map(\.query) { $0.order { try orderings($0).map(\.sqlOrdering) } }
map(\.relation) { $0.order { try orderings($0).map(\.sqlOrdering) } }
}
/// Creates a request that reverses applied orderings.
@@ -220,7 +214,7 @@ extension QueryInterfaceRequest: OrderedRequest {
/// var request = Player.all()
/// request = request.reversed()
public func reversed() -> QueryInterfaceRequest {
map(\.query) { $0.reversed() }
map(\.relation) { $0.reversed() }
}
/// Creates a request without any ordering.
@@ -229,20 +223,20 @@ extension QueryInterfaceRequest: OrderedRequest {
/// var request = Player.all().order(Column("name"))
/// request = request.unordered()
public func unordered() -> QueryInterfaceRequest {
map(\.query) { $0.unordered() }
map(\.relation) { $0.unordered() }
}
}
extension QueryInterfaceRequest: AggregatingRequest {
/// Creates a request grouped according to *expressions promise*.
public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest {
map(\.query) { $0.group { try expressions($0).map(\.sqlExpression) } }
map(\.relation) { $0.group { try expressions($0).map(\.sqlExpression) } }
}
/// Creates a request with the provided *predicate promise* added to the
/// eventual set of already applied predicates.
public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
map(\.query) { $0.having { try predicate($0).sqlExpression } }
map(\.relation) { $0.having { try predicate($0).sqlExpression } }
}
}
@@ -250,27 +244,27 @@ extension QueryInterfaceRequest: AggregatingRequest {
extension QueryInterfaceRequest: _JoinableRequest {
/// :nodoc:
public func _including(all association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._including(all: association) }
map(\.relation) { $0._including(all: association) }
}
/// :nodoc:
public func _including(optional association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._including(optional: association) }
map(\.relation) { $0._including(optional: association) }
}
/// :nodoc:
public func _including(required association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._including(required: association) }
map(\.relation) { $0._including(required: association) }
}
/// :nodoc:
public func _joining(optional association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._joining(optional: association) }
map(\.relation) { $0._joining(optional: association) }
}
/// :nodoc:
public func _joining(required association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._joining(required: association) }
map(\.relation) { $0._joining(required: association) }
}
}
@@ -279,7 +273,7 @@ extension QueryInterfaceRequest: JoinableRequest { }
extension QueryInterfaceRequest: TableRequest {
/// :nodoc:
public var databaseTableName: String {
query.relation.source.tableName
relation.source.tableName
}
/// Creates a request that allows you to define expressions that target
@@ -300,7 +294,7 @@ extension QueryInterfaceRequest: TableRequest {
/// .aliased(playerAlias)
/// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")])
public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest {
map(\.query) { $0.aliased(alias) }
map(\.relation) { $0.aliased(alias) }
}
}
@@ -317,7 +311,7 @@ extension QueryInterfaceRequest {
/// var request = Player.select(Column("name"))
/// request = request.distinct()
public func distinct() -> QueryInterfaceRequest {
map(\.query) { $0.distinct() }
with(\.relation.isDistinct, true)
}
/// Creates a request which fetches *limit* rows, starting at *offset*.
@@ -328,7 +322,7 @@ extension QueryInterfaceRequest {
///
/// Any previous limit is replaced.
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest {
map(\.query) { $0.limit(limit, offset: offset) }
with(\.relation.limit, SQLLimit(limit: limit, offset: offset))
}
/// Creates a request bound to type RowDecoder.
@@ -345,7 +339,7 @@ extension QueryInterfaceRequest {
/// - parameter type: The fetched type RowDecoder
/// - returns: A request bound to type RowDecoder.
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
QueryInterfaceRequest<RowDecoder>(query: query)
QueryInterfaceRequest<RowDecoder>(relation: relation)
}
}
@@ -410,7 +404,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
public func deleteAll(_ db: Database) throws -> Int {
try SQLQueryGenerator(query: query).makeDeleteStatement(db).execute()
try SQLQueryGenerator(relation: relation).makeDeleteStatement(db).execute()
return db.changesCount
}
}
@@ -440,7 +434,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
_ assignments: [ColumnAssignment]) throws -> Int
{
let conflictResolution = conflictResolution ?? RowDecoder.persistenceConflictPolicy.conflictResolutionForUpdate
guard let updateStatement = try SQLQueryGenerator(query: query).makeUpdateStatement(
guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement(
db,
conflictResolution: conflictResolution,
assignments: assignments) else
@@ -582,7 +576,7 @@ public func /= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign
private func prefetch(
_ db: Database,
associations: [_SQLAssociation],
from originQuery: SQLQuery,
from originRelation: SQLRelation,
into originRows: [Row]) throws
{
guard let firstOriginRow = originRows.first else {
@@ -598,7 +592,7 @@ private func prefetch(
fatalError("Not implemented: prefetch association without any foreign key")
case let .foreignKey(pivotForeignKey):
let originTable = originQuery.relation.source.tableName
let originTable = originRelation.source.tableName
let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable)
let pivotColumns = pivotMapping.map(\.right)
let leftColumns = pivotMapping.map(\.left)
@@ -647,17 +641,16 @@ private func prefetch(
// FROM country
// JOIN passport ON passport.countryCode = country.code
// AND (passport.a, passport.b) IN grdb_base
let originQuery = originQuery.map(\.relation) { baseRelation in
// Ordering and including(all:) children are
// useless, and we only need pivoting columns:
baseRelation
.unordered()
.removingChildrenForPrefetchedAssociations()
.selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection })
}
//
// In the CTE, ordering and including(all:) children are
// useless, and we only need to select pivot columns:
let originRelation = originRelation
.unordered()
.removingChildrenForPrefetchedAssociations()
.selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection })
let originCTE = CommonTableExpression(
named: "grdb_base",
request: SQLSubquery.query(originQuery))
request: SQLSubquery.relation(originRelation))
let pivotRowValue = SQLExpression.rowValue(pivotColumns.map(SQLExpression.column))!
let pivotFilter = originCTE.contains(pivotRowValue)
@@ -785,9 +778,7 @@ throws -> DatabaseRegion
.map(\.pivot.relation) { $0.filter(pivotFilter) }
.destinationRelation()
let prefetchQuery = SQLQuery(relation: prefetchRelation)
return try SQLQueryGenerator(query: prefetchQuery)
return try SQLQueryGenerator(relation: prefetchRelation)
.makeSelectStatement(db)
.databaseRegion // contains region of nested associations
}
-164
View File
@@ -1,164 +0,0 @@
/// SQLQuery is a representation of an SQL query.
///
/// See SQLQueryGenerator for actual SQL generation.
struct SQLQuery {
var relation: SQLRelation
var isDistinct: Bool = false
var groupPromise: DatabasePromise<[SQLExpression]>?
var havingExpressionPromise: DatabasePromise<SQLExpression?> = DatabasePromise(value: nil)
var limit: SQLLimit?
var ctes: OrderedDictionary<String, SQLCTE> = [:]
}
extension SQLQuery: Refinable {
func distinct() -> Self {
with(\.isDistinct, true)
}
func limit(_ limit: Int, offset: Int? = nil) -> Self {
with(\.limit, SQLLimit(limit: limit, offset: offset))
}
func aliased(_ alias: TableAlias) -> Self {
map(\.relation) { $0.aliased(alias) }
}
}
extension SQLQuery {
func select(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
map(\.relation) { $0.select(selection) }
}
// Convenience
func select(_ expressions: SQLExpression...) -> Self {
select { _ in expressions.map { .expression($0) } }
}
func annotated(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
map(\.relation) { $0.annotated(with: selection) }
}
}
extension SQLQuery {
func filter(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
map(\.relation) { $0.filter(predicate) }
}
}
extension SQLQuery {
func order(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self {
map(\.relation) { $0.order(orderings) }
}
func reversed() -> Self {
map(\.relation) { $0.reversed() }
}
func unordered() -> Self {
map(\.relation) { $0.unordered() }
}
}
extension SQLQuery {
func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
with(\.groupPromise, DatabasePromise(expressions))
}
func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
map(\.havingExpressionPromise) { promise in
DatabasePromise { db in
if let filter = try promise.resolve(db) {
return try filter && predicate(db)
} else {
return try predicate(db)
}
}
}
}
}
extension SQLQuery{
func _including(all association: _SQLAssociation) -> Self {
map(\.relation) { $0._including(all: association) }
}
func _including(optional association: _SQLAssociation) -> Self {
map(\.relation) { $0._including(optional: association) }
}
func _including(required association: _SQLAssociation) -> Self {
map(\.relation) { $0._including(required: association) }
}
func _joining(optional association: _SQLAssociation) -> Self {
map(\.relation) { $0._joining(optional: association) }
}
func _joining(required association: _SQLAssociation) -> Self {
map(\.relation) { $0._joining(required: association) }
}
}
extension SQLQuery {
func fetchCount(_ db: Database) throws -> Int {
guard groupPromise == nil && limit == nil && ctes.isEmpty else {
// SELECT ... GROUP BY ...
// SELECT ... LIMIT ...
// WITH ... SELECT ...
return try fetchTrivialCount(db)
}
if relation.children.contains(where: { $0.value.impactsParentCount }) { // TODO: not tested
// SELECT ... FROM ... JOIN ...
return try fetchTrivialCount(db)
}
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 try fetchTrivialCount(db)
}
var countQuery = self.unordered()
countQuery.isDistinct = false
switch count {
case .all:
countQuery = countQuery.select(.countAll)
case .distinct(let expression):
countQuery = countQuery.select(.countDistinct(expression))
}
return try QueryInterfaceRequest(query: countQuery).fetchOne(db)!
} else {
// SELECT [DISTINCT] expr1, expr2, ... FROM tableName ...
guard !isDistinct else {
return try fetchTrivialCount(db)
}
// SELECT expr1, expr2, ... FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
let countQuery = unordered().select(.countAll)
return try QueryInterfaceRequest(query: countQuery).fetchOne(db)!
}
}
// SELECT COUNT(*) FROM (self)
func fetchTrivialCount(_ db: Database) throws -> Int {
let countRequest: SQLRequest<Int> = "SELECT COUNT(*) FROM (\(SQLSubquery.query(unordered())))"
return try countRequest.fetchOne(db)!
}
}
struct SQLLimit {
let limit: Int
let offset: Int?
var sql: String {
if let offset = offset {
return "\(limit) OFFSET \(offset)"
} else {
return "\(limit)"
}
}
}
+128 -35
View File
@@ -2,23 +2,20 @@
/// terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology),
/// is "a set of tuples sharing the same attributes; a set of columns and rows."
///
/// SQLRelation is defined with a selection, a source table of query, and an
/// eventual filter and ordering.
///
/// SELECT ... FROM ... WHERE ... ORDER BY ...
/// | | | |
/// | | | • ordering
/// | | • filter
/// | • source
/// • selection
///
/// Other SQL clauses such as GROUP BY, LIMIT are defined one level up, in the
/// `SQLQuery` type.
/// WITH ... -- ctes
/// SELECT ... -- selectionPromise
/// FROM ... -- source
/// JOIN ... -- children
/// WHERE ... -- filterPromise
/// GROUP BY ... -- groupPromise
/// HAVING ... -- havingExpressionPromise
/// ORDER BY ... -- ordering
/// LIMIT ... -- limit
///
/// ## Promises
///
/// Selection, filter, and ordering are "promises" which are resolved when a
/// database connection is available. This is how we can implement requests such
/// Most relation elements are "promises" which are resolved when a database
/// connection is available. This is how we can implement requests such
/// as `Record.filter(key: 1)` or `Record.orderByPrimaryKey()`: both need a
/// database connection in order to introspect the primary key. For example:
///
@@ -29,7 +26,7 @@
///
/// ## Children
///
/// Relations may also have children. A child is a link to another relation, and
/// Relations have children. A child is a link to another relation, and
/// provide support for joins and prefetched relations.
///
/// Relations and their children constitute a tree of relations, which the user
@@ -143,30 +140,19 @@ struct SQLRelation {
}
var source: SQLSource
var selectionPromise: DatabasePromise<[SQLSelection]> = DatabasePromise(value: [])
var selectionPromise: DatabasePromise<[SQLSelection]>
var filterPromise: DatabasePromise<SQLExpression?> = DatabasePromise(value: nil)
var ordering: SQLRelation.Ordering = SQLRelation.Ordering()
var children: OrderedDictionary<String, Child> = [:]
/// All prefetched associations (`including(all:)`), recursively
var prefetchedAssociations: [_SQLAssociation] {
children.flatMap { key, child -> [_SQLAssociation] in
switch child.kind {
case .all:
return [child.makeAssociationForKey(key)]
case .oneOptional, .oneRequired, .bridge:
return child.relation.prefetchedAssociations.map { association in
// Remove redundant pivot child
let pivotKey = association.pivot.keyName
let child = child.map(\.relation) { relation in
assert(relation.children[pivotKey] != nil)
return relation.removingChild(forKey: pivotKey)
}
return association.through(child.makeAssociationForKey(key))
}
}
}
}
// Properties below MUST NOT be used when joining to-one associations
#warning("TODO: make sure a precondition failure prevents those to be defined on to-one associations")
#warning("TODO: merge")
var isDistinct: Bool = false
var groupPromise: DatabasePromise<[SQLExpression]>?
var havingExpressionPromise: DatabasePromise<SQLExpression>?
var limit: SQLLimit?
var ctes: OrderedDictionary<String, SQLCTE> = [:]
}
extension SQLRelation {
@@ -192,6 +178,11 @@ extension SQLRelation: Refinable {
select { _ in selection }
}
// Convenience
func select(_ expressions: SQLExpression...) -> Self {
select { _ in expressions.map { .expression($0) } }
}
/// Removes all selections from chidren
func selectOnly(_ selection: [SQLSelection]) -> Self {
self
@@ -251,12 +242,48 @@ extension SQLRelation: Refinable {
}
}
func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
with(\.groupPromise, DatabasePromise(expressions))
}
func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
map(\.havingExpressionPromise) { promise in
DatabasePromise { db in
if let filter = try promise?.resolve(db) {
return try filter && predicate(db)
} else {
return try predicate(db)
}
}
}
}
func aliased(_ alias: TableAlias) -> Self {
map(\.source) { $0.aliased(alias) }
}
}
extension SQLRelation {
/// All prefetched associations (`including(all:)`), recursively
var prefetchedAssociations: [_SQLAssociation] {
children.flatMap { key, child -> [_SQLAssociation] in
switch child.kind {
case .all:
return [child.makeAssociationForKey(key)]
case .oneOptional, .oneRequired, .bridge:
return child.relation.prefetchedAssociations.map { association in
// Remove redundant pivot child
let pivotKey = association.pivot.keyName
let child = child.map(\.relation) { relation in
assert(relation.children[pivotKey] != nil)
return relation.removingChild(forKey: pivotKey)
}
return association.through(child.makeAssociationForKey(key))
}
}
}
}
/// Returns a relation extended with an association.
///
/// This method provides support for public joining methods such
@@ -466,6 +493,72 @@ extension SQLRelation {
}
}
extension SQLRelation {
func fetchCount(_ db: Database) throws -> Int {
guard groupPromise == nil && limit == nil && ctes.isEmpty else {
// SELECT ... GROUP BY ...
// SELECT ... LIMIT ...
// WITH ... SELECT ...
return try fetchTrivialCount(db)
}
if children.contains(where: { $0.value.impactsParentCount }) { // TODO: not tested
// SELECT ... FROM ... JOIN ...
return try fetchTrivialCount(db)
}
let selection = try 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 try fetchTrivialCount(db)
}
var countRelation = self.unordered()
countRelation.isDistinct = false
switch count {
case .all:
countRelation = countRelation.select(.countAll)
case .distinct(let expression):
countRelation = countRelation.select(.countDistinct(expression))
}
return try QueryInterfaceRequest(relation: countRelation).fetchOne(db)!
} else {
// SELECT [DISTINCT] expr1, expr2, ... FROM tableName ...
guard !isDistinct else {
return try fetchTrivialCount(db)
}
// SELECT expr1, expr2, ... FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
let countRelation = unordered().select(.countAll)
return try QueryInterfaceRequest(relation: countRelation).fetchOne(db)!
}
}
// SELECT COUNT(*) FROM (self)
private func fetchTrivialCount(_ db: Database) throws -> Int {
let countRequest: SQLRequest<Int> = "SELECT COUNT(*) FROM (\(SQLSubquery.relation(unordered())))"
return try countRequest.fetchOne(db)!
}
}
// MARK: - SQLLimit
struct SQLLimit {
let limit: Int
let offset: Int?
var sql: String {
if let offset = offset {
return "\(limit) OFFSET \(offset)"
} else {
return "\(limit)"
}
}
}
// MARK: - SQLSource
struct SQLSource {
+8 -8
View File
@@ -6,16 +6,16 @@ public struct SQLSubquery {
/// A literal SQL query
case literal(SQLLiteral)
/// A query interface query
case query(SQLQuery)
/// A query interface relation
case relation(SQLRelation)
}
static func literal(_ sqlLiteral: SQLLiteral) -> Self {
self.init(impl: .literal(sqlLiteral))
}
static func query(_ query: SQLQuery) -> Self {
self.init(impl: .query(query))
static func relation(_ relation: SQLRelation) -> Self {
self.init(impl: .relation(relation))
}
}
@@ -48,8 +48,8 @@ extension SQLSubquery {
let statement = try db.cachedSelectStatement(sql: sql)
return statement.columnCount
case let .query(query):
return try SQLQueryGenerator(query: query).columnsCount(db)
case let .relation(relation):
return try SQLQueryGenerator(relation: relation).columnsCount(db)
}
}
}
@@ -77,8 +77,8 @@ extension SQLSubquery {
case let .literal(sqlLiteral):
return try sqlLiteral.sql(context)
case let .query(query):
return try SQLQueryGenerator(query: query, forSingleResult: false).requestSQL(context)
case let .relation(relation):
return try SQLQueryGenerator(relation: relation).requestSQL(context)
}
}
}
@@ -1,12 +1,7 @@
/// SQLQueryGenerator is able to generate an SQL SELECT query.
struct SQLQueryGenerator: Refinable {
fileprivate private(set) var relation: SQLQualifiedRelation
private let isDistinct: Bool
private let groupPromise: DatabasePromise<[SQLExpression]>?
private let havingExpressionPromise: DatabasePromise<SQLExpression?>
private let limit: SQLLimit?
private let singleResult: Bool
private let ctes: OrderedDictionary<String, SQLCTE>
// For database region
private let prefetchedAssociations: [_SQLAssociation]
@@ -15,49 +10,12 @@ struct SQLQueryGenerator: Refinable {
/// - parameter singleResult: A hint as to whether the query should be
/// optimized for a single result.
init(
query: SQLQuery,
relation: SQLRelation,
forSingleResult singleResult: Bool = false)
{
// To generate SQL, we need a "qualified" relation, where all tables,
// expressions, etc, are identified with table aliases.
//
// All those aliases let us disambiguate tables at the SQL level, and
// prefix columns names. For example, the following request...
//
// Book.filter(Column("kind") == Book.Kind.novel)
// .including(optional: Book.author)
// .including(optional: Book.translator)
// .annotated(with: Book.awards.count)
//
// ... generates the following SQL, where all identifiers are correctly
// disambiguated and qualified:
//
// SELECT book.*, person1.*, person2.*, COUNT(DISTINCT award.id)
// FROM book
// LEFT JOIN person person1 ON person1.id = book.authorId
// LEFT JOIN person person2 ON person2.id = book.translatorId
// LEFT JOIN award ON award.bookId = book.id
// GROUP BY book.id
// WHERE book.kind = 'novel'
relation = SQLQualifiedRelation(query.relation)
// Qualify group expressions and having clause with the relation alias.
//
// This turns `GROUP BY id` INTO `GROUP BY book.id`, and
// `HAVING MAX(year) < 2000` INTO `HAVING MAX(book.year) < 2000`.
let sourceAlias = relation.source.alias
groupPromise = query.groupPromise?.map {
$0.map { $0.qualified(with: sourceAlias) }
}
havingExpressionPromise = query.havingExpressionPromise.map {
$0.map { $0.qualified(with: sourceAlias) }
}
limit = query.limit
isDistinct = query.isDistinct
self.relation = SQLQualifiedRelation(relation)
self.prefetchedAssociations = relation.prefetchedAssociations
self.singleResult = singleResult
prefetchedAssociations = query.relation.prefetchedAssociations
ctes = query.ctes
}
func requestSQL(_ context: SQLGenerationContext) throws -> String {
@@ -66,7 +24,7 @@ struct SQLQueryGenerator: Refinable {
var sql = try commonTableExpressionsPrefix(context)
sql += "SELECT"
if isDistinct {
if relation.isDistinct {
sql += " DISTINCT"
}
@@ -94,7 +52,7 @@ struct SQLQueryGenerator: Refinable {
sql += try filter.sql(context)
}
let groupExpressions = try groupPromise?.resolve(context.db) ?? []
let groupExpressions = try relation.groupPromise?.resolve(context.db) ?? []
if !groupExpressions.isEmpty {
sql += " GROUP BY "
sql += try groupExpressions
@@ -102,7 +60,7 @@ struct SQLQueryGenerator: Refinable {
.joined(separator: ", ")
}
if let havingExpression = try havingExpressionPromise.resolve(context.db) {
if let havingExpression = try relation.havingExpressionPromise?.resolve(context.db) {
sql += " HAVING "
sql += try havingExpression.sql(context)
}
@@ -115,8 +73,8 @@ struct SQLQueryGenerator: Refinable {
.joined(separator: ", ")
}
var limit = self.limit
if try singleResult && !expectsSingleResult(
var limit = relation.limit
if try limit == nil && singleResult && !expectsSingleResult(
context.db,
selection: selection,
filter: filter,
@@ -260,7 +218,7 @@ struct SQLQueryGenerator: Refinable {
sql += try filter.sql(context)
}
if let limit = limit {
if let limit = relation.limit {
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += " ORDER BY "
@@ -346,7 +304,7 @@ struct SQLQueryGenerator: Refinable {
sql += try filter.sql(context)
}
if let limit = limit {
if let limit = relation.limit {
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += " ORDER BY "
@@ -416,15 +374,15 @@ struct SQLQueryGenerator: Refinable {
}
private func commonTableExpressionsPrefix(_ context: SQLGenerationContext) throws -> String {
if ctes.isEmpty {
if relation.ctes.isEmpty {
return ""
}
var sql = "WITH "
if ctes.values.contains(where: \.isRecursive) {
if relation.ctes.values.contains(where: \.isRecursive) {
sql += "RECURSIVE "
}
sql += try ctes
sql += try relation.ctes
.map { tableName, cte in
var columnsSQL = ""
if let columns = cte.columns, !columns.isEmpty {
@@ -457,7 +415,7 @@ struct SQLQueryGenerator: Refinable {
private func grouping(_ db: Database) throws -> GroupingInfo {
// Empty group clause: no grouping
// SELECT * FROM player
guard let groupExpressions = try groupPromise?.resolve(db), groupExpressions.isEmpty == false else {
guard let groupExpressions = try relation.groupPromise?.resolve(db), groupExpressions.isEmpty == false else {
return .none
}
@@ -518,15 +476,40 @@ struct SQLQueryGenerator: Refinable {
}
}
/// A "qualified" relation, where all tables are identified with a table alias.
/// To generate SQL, we need a "qualified" relation, where all tables,
/// expressions, etc, are qualified with table aliases.
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// | | | | |
/// | | | | • ordering
/// | | | • filterPromise
/// | | • joins
/// | • source
/// • selectionPromise
/// All those aliases let us disambiguate tables at the SQL level, and
/// prefix columns names. For example, the following request...
///
/// Book.filter(Column("kind") == Book.Kind.novel)
/// .including(optional: Book.author)
/// .including(optional: Book.translator)
/// .annotated(with: Book.awards.count)
///
/// ... generates the following SQL, where all identifiers are correctly
/// disambiguated and qualified:
///
/// SELECT book.*, person1.*, person2.*, COUNT(DISTINCT award.id)
/// FROM book
/// LEFT JOIN person person1 ON person1.id = book.authorId
/// LEFT JOIN person person2 ON person2.id = book.translatorId
/// LEFT JOIN award ON award.bookId = book.id
/// GROUP BY book.id
/// WHERE book.kind = 'novel'
///
/// `SQLQualifiedRelation` contains the following information:
///
/// WITH ... -- ctes
/// SELECT ... -- selectionPromise
/// FROM ... -- source
/// JOIN ... -- joins
/// WHERE ... -- filterPromise
/// GROUP BY ... -- groupPromise
/// HAVING ... -- havingExpressionPromise
/// ORDER BY ... -- ordering
/// LIMIT ... -- limit
private struct SQLQualifiedRelation {
/// All aliases, including aliases of joined relations
var allAliases: [TableAlias] {
@@ -536,20 +519,15 @@ private struct SQLQualifiedRelation {
}
/// The source
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • source
let source: SQLQualifiedSource
/// The selection from source, not including selection of joined relations
private var sourceSelectionPromise: DatabasePromise<[SQLSelection]>
#warning("TODO: decide if selectOnly() should reset this flag")
let isDistinct: Bool
/// The full selection, including selection of joined relations
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • selectionPromise
var selectionPromise: DatabasePromise<[SQLSelection]> {
DatabasePromise { db in
let selection = try self.sourceSelectionPromise.resolve(db)
@@ -560,34 +538,24 @@ private struct SQLQualifiedRelation {
}
}
/// The filtering clause
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • filterPromise
let filterPromise: DatabasePromise<SQLExpression?>
/// The ordering of source, not including ordering of joined relations
private let sourceOrdering: SQLRelation.Ordering
/// The full ordering, including orderings of joined relations
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • ordering
var ordering: SQLRelation.Ordering {
joins.reduce(sourceOrdering) {
$0.appending($1.value.relation.ordering)
}
}
/// The joins
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • joins
private(set) var joins: OrderedDictionary<String, SQLQualifiedJoin>
let groupPromise: DatabasePromise<[SQLExpression]>?
let havingExpressionPromise: DatabasePromise<SQLExpression>?
let limit: SQLLimit?
let ctes: OrderedDictionary<String, SQLCTE>
init(_ relation: SQLRelation) {
// Qualify the source, so that it be disambiguated with an SQL alias
// if needed (when a select query uses the same table several times).
@@ -596,9 +564,8 @@ private struct SQLQualifiedRelation {
// this SQLQualifiedRelation generates SQL.
source = SQLQualifiedSource(relation.source)
// Qualify all joins, selection, filter, and ordering, so that all
// identifiers can be correctly disambiguated and qualified.
joins = relation.children.compactMapValues { SQLQualifiedJoin($0) }
// Qualify all selection, filter, etc, so that all identifiers
// can be correctly disambiguated and qualified.
let sourceAlias = source.alias
sourceSelectionPromise = relation.selectionPromise.map {
$0.map { $0.qualified(with: sourceAlias) }
@@ -607,6 +574,21 @@ private struct SQLQualifiedRelation {
$0.map { $0.qualified(with: sourceAlias) }
}
sourceOrdering = relation.ordering.qualified(with: sourceAlias)
groupPromise = relation.groupPromise?.map {
$0.map { $0.qualified(with: sourceAlias) }
}
havingExpressionPromise = relation.havingExpressionPromise.map {
$0.map { $0.qualified(with: sourceAlias) }
}
// Turns relation children into joins. `including(all:)` children are
// discarded on the way.
joins = relation.children.compactMapValues { SQLQualifiedJoin($0) }
// Copy other flags
limit = relation.limit
isDistinct = relation.isDistinct
ctes = relation.ctes
}
/// See SQLQueryGenerator.rowAdapter(_:)