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

-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)
}
}
}