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

-10
View File
@@ -829,9 +829,6 @@
56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; };
56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; };
56D91AAB2205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; };
56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
56D91AB12205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
56D91AB22205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; };
@@ -953,7 +950,6 @@
AAA4DCB4230F1E0600C74B15 /* HasOneThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */; };
AAA4DCB5230F1E0600C74B15 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; };
AAA4DCB6230F1E0600C74B15 /* ReadWriteBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */; };
AAA4DCB7230F1E0600C74B15 /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
AAA4DCB8230F1E0600C74B15 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
AAA4DCB9230F1E0600C74B15 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; };
@@ -1565,7 +1561,6 @@
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
56D91AA82205F2F000770D8D /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = "<group>"; };
56D91AAF2205F8AC00770D8D /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = "<group>"; };
56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = "<group>"; };
56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = "<group>"; };
56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = "<group>"; };
@@ -2042,7 +2037,6 @@
566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */,
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */,
568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */,
56D91AAF2205F8AC00770D8D /* SQLQuery.swift */,
56D91AA12205E03700770D8D /* SQLRelation.swift */,
568ECA8925D7013000B71526 /* SQLSelection.swift */,
568ECB1725D9161500B71526 /* SQLSubquery.swift */,
@@ -2866,7 +2860,6 @@
5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */,
56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
5656A8B22295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
56D91AB22205F8AC00770D8D /* SQLQuery.swift in Sources */,
56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
5653EB0B20944C7C00F46237 /* Association.swift in Sources */,
564CE59F21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
@@ -3070,7 +3063,6 @@
56AE64132229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
56A2388C1B9C75030082EB20 /* Statement.swift in Sources */,
5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
56D91AB12205F8AC00770D8D /* SQLQuery.swift in Sources */,
56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */,
5690C3431D23E82A00E59934 /* Data.swift in Sources */,
5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
@@ -3655,7 +3647,6 @@
AAA4DCB4230F1E0600C74B15 /* HasOneThroughAssociation.swift in Sources */,
AAA4DCB5230F1E0600C74B15 /* Statement.swift in Sources */,
AAA4DCB6230F1E0600C74B15 /* ReadWriteBox.swift in Sources */,
AAA4DCB7230F1E0600C74B15 /* SQLQuery.swift in Sources */,
AAA4DCB8230F1E0600C74B15 /* Migration.swift in Sources */,
AAA4DCB9230F1E0600C74B15 /* Data.swift in Sources */,
AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */,
@@ -3946,7 +3937,6 @@
files = (
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */,
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
@@ -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(_:)
-6
View File
@@ -256,8 +256,6 @@
5656A8942295BD56001FF3FF /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84C2295BD56001FF3FF /* SQLFunctions.swift */; };
5656A8972295BD56001FF3FF /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84E2295BD56001FF3FF /* SQLRelation.swift */; };
5656A8982295BD56001FF3FF /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84E2295BD56001FF3FF /* SQLRelation.swift */; };
5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8502295BD56001FF3FF /* SQLQuery.swift */; };
5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8502295BD56001FF3FF /* SQLQuery.swift */; };
5656A8A72295BF44001FF3FF /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A52295BF44001FF3FF /* DatabasePromise.swift */; };
5656A8A82295BF44001FF3FF /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A52295BF44001FF3FF /* DatabasePromise.swift */; };
5657AABB1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; };
@@ -907,7 +905,6 @@
5656A84A2295BD56001FF3FF /* Column.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Column.swift; sourceTree = "<group>"; };
5656A84C2295BD56001FF3FF /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = "<group>"; };
5656A84E2295BD56001FF3FF /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
5656A8502295BD56001FF3FF /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = "<group>"; };
5656A8A52295BF44001FF3FF /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = "<group>"; };
5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = "<group>"; };
5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = "<group>"; };
@@ -1549,7 +1546,6 @@
5656A84C2295BD56001FF3FF /* SQLFunctions.swift */,
5656A8462295BD56001FF3FF /* SQLOperators.swift */,
5656A8452295BD56001FF3FF /* SQLOrdering.swift */,
5656A8502295BD56001FF3FF /* SQLQuery.swift */,
5656A84E2295BD56001FF3FF /* SQLRelation.swift */,
568ECB0C25D904CA00B71526 /* SQLSelection.swift */,
568ECB3425D91CEE00B71526 /* SQLSubquery.swift */,
@@ -2355,7 +2351,6 @@
F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */,
5656A8702295BD56001FF3FF /* Association.swift in Sources */,
563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */,
5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */,
5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
5656A85C2295BD56001FF3FF /* TableDefinition.swift in Sources */,
5656A8562295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */,
@@ -2713,7 +2708,6 @@
F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */,
5656A86F2295BD56001FF3FF /* Association.swift in Sources */,
563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */,
5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */,
5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
5656A85B2295BD56001FF3FF /* TableDefinition.swift in Sources */,
5656A8552295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */,