Use "finalized" to describe queries that are ready for SQL generation

This commit is contained in:
Gwendal Roué committed 2018-05-01 17:42:39 +02:00
1 parent ffaabdfd62
commit ab36df6e0f
3 files changed
+347 -336

No files matched your search

+280 -276
View File
@@ -58,275 +58,9 @@ struct QueryInterfaceQuery {
joins: query.joins)
}
func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String {
var sql = "SELECT"
if isDistinct {
sql += " DISTINCT"
}
let selection = completeSelection
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ")
sql += try " FROM " + source.sourceSQL(db, &context)
for join in joins {
sql += try " " + join.joinSQL(db, &context, leftAlias: alias!, isRequiredAllowed: true)
}
if let filter = try filterPromise.resolve(db) {
sql += " WHERE " + filter.expressionSQL(&context)
}
if !groupByExpressions.isEmpty {
sql += " GROUP BY "
sql += groupByExpressions.map { $0.expressionSQL(&context) }
.joined(separator: ", ")
}
if let havingExpression = havingExpression {
sql += " HAVING " + havingExpression.expressionSQL(&context)
}
let orderings = completeOrdering.resolve()
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
}
if let limit = limit {
sql += " LIMIT " + limit.sql
}
return sql
}
/// precondition: self is the result of qualifiedQuery
func makeDeleteStatement(_ db: Database) throws -> UpdateStatement {
guard groupByExpressions.isEmpty else {
// Programmer error
fatalError("Can't delete query with GROUP BY clause")
}
guard havingExpression == nil else {
// Programmer error
fatalError("Can't delete query with HAVING clause")
}
guard joins.isEmpty else {
// Programmer error
fatalError("Can't delete query with JOIN clause")
}
guard case .table = source else {
// Programmer error
fatalError("Can't delete without any database table")
}
var context = SQLGenerationContext.queryGenerationContext(aliases: allAliases)
var sql = try "DELETE FROM " + source.sourceSQL(db, &context)
if let filter = try filterPromise.resolve(db) {
sql += " WHERE " + filter.expressionSQL(&context)
}
if let limit = limit {
let orderings = self.completeOrdering.resolve()
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
}
if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") {
sql += " LIMIT " + limit.sql
} else {
fatalError("Can't delete query with limit")
}
}
let statement = try db.makeUpdateStatement(sql)
statement.arguments = context.arguments!
return statement
}
/// Remove ordering
var unorderedQuery: QueryInterfaceQuery {
var query = self
query.ordering = QueryOrdering()
return query
}
// MARK: Join Support
var alias: TableAlias? {
return source.alias
}
var allAliases: [TableAlias] {
var aliases: [TableAlias] = []
if let alias = alias {
aliases.append(alias)
}
return joins.reduce(into: aliases) {
$0.append(contentsOf: $1.allAliases)
}
}
var completeSelection: [SQLSelectable] {
return joins.reduce(into: selection) {
$0.append(contentsOf: $1.completeSelection)
}
}
var completeOrdering: QueryOrdering {
return joins.reduce(ordering) {
$0.appending($1.completeOrdering)
}
}
}
extension QueryInterfaceQuery {
var qualifiedQuery: QueryInterfaceQuery {
var query = self
let alias = TableAlias()
query.source = source.qualified(with: alias)
query.selection = query.selection.map { $0.qualifiedSelectable(with: alias) }
query.filterPromise = query.filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) }
query.groupByExpressions = query.groupByExpressions.map { $0.qualifiedExpression(with: alias) }
query.ordering = query.ordering.qualified(with: alias)
query.havingExpression = query.havingExpression?.qualifiedExpression(with: alias)
query.joins = query.joins.map { $0.qualifiedJoin }
return query
}
/// precondition: self is the result of qualifiedQuery
private func makeSelectStatement(_ db: Database) throws -> SelectStatement {
var context = SQLGenerationContext.queryGenerationContext(aliases: allAliases)
let sql = try self.sql(db, &context)
let statement = try db.makeSelectStatement(sql)
statement.arguments = context.arguments!
return statement
}
/// precondition: self is the result of qualifiedQuery
private func rowAdapter(_ db: Database) throws -> RowAdapter? {
if joins.isEmpty {
return nil
}
let selectionWidth = try selection
.map { try $0.columnCount(db) }
.reduce(0, +)
var endIndex = selectionWidth
var scopes: [String: RowAdapter] = [:]
for join in joins {
if let (joinAdapter, joinEndIndex) = try join.rowAdapter(db, fromIndex: endIndex, forKeyPath: [join.key]) {
GRDBPrecondition(scopes[join.key] == nil, "The association key \"\(join.key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.")
scopes[join.key] = joinAdapter
endIndex = joinEndIndex
}
}
if selectionWidth == 0 && scopes.isEmpty {
return nil
}
let adapter = RangeRowAdapter(0 ..< (0 + selectionWidth))
return adapter.addingScopes(scopes)
}
/// precondition: self is the result of qualifiedQuery
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try (makeSelectStatement(db), rowAdapter(db))
}
func fetchCount(_ db: Database) throws -> Int {
let (statement, adapter) = try countQuery.prepare(db)
return try Int.fetchOne(statement, adapter: adapter)!
}
/// The database region that the request looks into.
/// precondition: self is the result of qualifiedQuery
func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
let statement = try qualifiedQuery.makeSelectStatement(db)
let region = statement.fetchedRegion
// Can we intersect the region with rowIds?
//
// Give up unless request feeds from a single database table
guard case .table(tableName: let tableName, alias: _) = source else {
// TODO: try harder
return region
}
// Give up unless primary key is rowId
let primaryKeyInfo = try db.primaryKey(tableName)
guard primaryKeyInfo.isRowID else {
return region
}
// Give up unless there is a where clause
guard let filter = try filterPromise.resolve(db) else {
return region
}
// The filter knows better
guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else {
return region
}
// Database regions are case-insensitive: use the canonical table name
let canonicalTableName = try db.canonicalTableName(tableName)
return region.tableIntersection(canonicalTableName, rowIds: rowIds)
}
private var countQuery: QueryInterfaceQuery {
guard groupByExpressions.isEmpty && limit == nil else {
// SELECT ... GROUP BY ...
// SELECT ... LIMIT ...
return trivialCountQuery
}
guard joins.isEmpty, case .table = source else {
// SELECT ... FROM (something which is not a plain table)
return trivialCountQuery
}
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
if selection.count == 1 {
guard let count = self.selection[0].count(distinct: isDistinct) else {
return trivialCountQuery
}
var countQuery = unorderedQuery
countQuery.isDistinct = false
countQuery.selection = [count.sqlSelectable]
return countQuery
} else {
// SELECT [DISTINCT] expr1, expr2, ... FROM tableName ...
guard !isDistinct else {
return trivialCountQuery
}
// SELECT expr1, expr2, ... FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
var countQuery = unorderedQuery
countQuery.selection = [SQLExpressionCount(AllColumns())]
return countQuery
}
}
// SELECT COUNT(*) FROM (self)
private var trivialCountQuery: QueryInterfaceQuery {
return QueryInterfaceQuery(
source: .query(unorderedQuery),
selection: [SQLExpressionCount(AllColumns())])
}
}
extension QueryInterfaceQuery {
@@ -384,6 +118,12 @@ extension QueryInterfaceQuery {
return query
}
func unordered() -> QueryInterfaceQuery {
var query = self
query.ordering = QueryOrdering()
return query
}
func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceQuery {
var query = self
query.limit = SQLLimit(limit: limit, offset: offset)
@@ -403,6 +143,269 @@ extension QueryInterfaceQuery {
}
}
extension QueryInterfaceQuery {
/// A finalized query is ready for SQL generation
var finalizedQuery: QueryInterfaceQuery {
var query = self
let alias = TableAlias()
query.source = source.qualified(with: alias)
query.selection = query.selection.map { $0.qualifiedSelectable(with: alias) }
query.filterPromise = query.filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) }
query.groupByExpressions = query.groupByExpressions.map { $0.qualifiedExpression(with: alias) }
query.ordering = query.ordering.qualified(with: alias)
query.havingExpression = query.havingExpression?.qualifiedExpression(with: alias)
query.joins = query.joins.map { $0.finalizedJoin }
return query
}
/// precondition: self is the result of finalizedQuery
var finalizedAliases: [TableAlias] {
var aliases: [TableAlias] = []
if let alias = alias {
aliases.append(alias)
}
return joins.reduce(into: aliases) {
$0.append(contentsOf: $1.finalizedAliases)
}
}
/// precondition: self is the result of finalizedQuery
var finalizedSelection: [SQLSelectable] {
return joins.reduce(into: selection) {
$0.append(contentsOf: $1.finalizedSelection)
}
}
/// precondition: self is the result of finalizedQuery
var finalizedOrdering: QueryOrdering {
return joins.reduce(ordering) {
$0.appending($1.finalizedOrdering)
}
}
/// precondition: self is the result of finalizedQuery
private func finalizedRowAdapter(_ db: Database) throws -> RowAdapter? {
if joins.isEmpty {
return nil
}
let selectionWidth = try selection
.map { try $0.columnCount(db) }
.reduce(0, +)
var endIndex = selectionWidth
var scopes: [String: RowAdapter] = [:]
for join in joins {
if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: [join.key]) {
GRDBPrecondition(scopes[join.key] == nil, "The association key \"\(join.key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.")
scopes[join.key] = joinAdapter
endIndex = joinEndIndex
}
}
if selectionWidth == 0 && scopes.isEmpty {
return nil
}
let adapter = RangeRowAdapter(0 ..< (0 + selectionWidth))
return adapter.addingScopes(scopes)
}
}
extension QueryInterfaceQuery {
func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String {
var sql = "SELECT"
if isDistinct {
sql += " DISTINCT"
}
let selection = finalizedSelection
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ")
sql += try " FROM " + source.sourceSQL(db, &context)
for join in joins {
sql += try " " + join.joinSQL(db, &context, leftAlias: alias!, isRequiredAllowed: true)
}
if let filter = try filterPromise.resolve(db) {
sql += " WHERE " + filter.expressionSQL(&context)
}
if !groupByExpressions.isEmpty {
sql += " GROUP BY "
sql += groupByExpressions.map { $0.expressionSQL(&context) }
.joined(separator: ", ")
}
if let havingExpression = havingExpression {
sql += " HAVING " + havingExpression.expressionSQL(&context)
}
let orderings = finalizedOrdering.resolve()
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
}
if let limit = limit {
sql += " LIMIT " + limit.sql
}
return sql
}
/// precondition: self is the result of finalizedQuery
private func makeSelectStatement(_ db: Database) throws -> SelectStatement {
var context = SQLGenerationContext.queryGenerationContext(aliases: finalizedAliases)
let sql = try self.sql(db, &context)
let statement = try db.makeSelectStatement(sql)
statement.arguments = context.arguments!
return statement
}
/// precondition: self is the result of finalizedQuery
func makeDeleteStatement(_ db: Database) throws -> UpdateStatement {
guard groupByExpressions.isEmpty else {
// Programmer error
fatalError("Can't delete query with GROUP BY clause")
}
guard havingExpression == nil else {
// Programmer error
fatalError("Can't delete query with HAVING clause")
}
guard joins.isEmpty else {
// Programmer error
fatalError("Can't delete query with JOIN clause")
}
guard case .table = source else {
// Programmer error
fatalError("Can't delete without any database table")
}
var context = SQLGenerationContext.queryGenerationContext(aliases: finalizedAliases)
var sql = try "DELETE FROM " + source.sourceSQL(db, &context)
if let filter = try filterPromise.resolve(db) {
sql += " WHERE " + filter.expressionSQL(&context)
}
if let limit = limit {
let orderings = finalizedOrdering.resolve()
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
}
if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") {
sql += " LIMIT " + limit.sql
} else {
fatalError("Can't delete query with limit")
}
}
let statement = try db.makeUpdateStatement(sql)
statement.arguments = context.arguments!
return statement
}
/// precondition: self is the result of finalizedQuery
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try (makeSelectStatement(db), finalizedRowAdapter(db))
}
func fetchCount(_ db: Database) throws -> Int {
let (statement, adapter) = try countQuery.prepare(db)
return try Int.fetchOne(statement, adapter: adapter)!
}
/// The database region that the request looks into.
/// precondition: self is the result of finalizedQuery
func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
let statement = try makeSelectStatement(db)
let region = statement.fetchedRegion
// Can we intersect the region with rowIds?
//
// Give up unless request feeds from a single database table
guard case .table(tableName: let tableName, alias: _) = source else {
// TODO: try harder
return region
}
// Give up unless primary key is rowId
let primaryKeyInfo = try db.primaryKey(tableName)
guard primaryKeyInfo.isRowID else {
return region
}
// Give up unless there is a where clause
guard let filter = try filterPromise.resolve(db) else {
return region
}
// The filter knows better
guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else {
return region
}
// Database regions are case-insensitive: use the canonical table name
let canonicalTableName = try db.canonicalTableName(tableName)
return region.tableIntersection(canonicalTableName, rowIds: rowIds)
}
private var countQuery: QueryInterfaceQuery {
guard groupByExpressions.isEmpty && limit == nil else {
// SELECT ... GROUP BY ...
// SELECT ... LIMIT ...
return trivialCountQuery
}
guard joins.isEmpty, case .table = source else {
// SELECT ... FROM (something which is not a plain table)
return trivialCountQuery
}
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
if selection.count == 1 {
guard let count = self.selection[0].count(distinct: isDistinct) else {
return trivialCountQuery
}
var countQuery = self.unordered()
countQuery.isDistinct = false
countQuery.selection = [count.sqlSelectable]
return countQuery
} else {
// SELECT [DISTINCT] expr1, expr2, ... FROM tableName ...
guard !isDistinct else {
return trivialCountQuery
}
// SELECT expr1, expr2, ... FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
var countQuery = self.unordered()
countQuery.selection = [SQLExpressionCount(AllColumns())]
return countQuery
}
}
// SELECT COUNT(*) FROM (self)
private var trivialCountQuery: QueryInterfaceQuery {
return QueryInterfaceQuery(
source: .query(unordered()),
selection: [SQLExpressionCount(AllColumns())])
}
}
// MARK: - AssociationJoin
/// Not to be mismatched with SQL join operators (inner join, left join).
@@ -458,28 +461,29 @@ struct AssociationJoin {
var key: String
var joinConditionPromise: DatabasePromise<JoinCondition>
var qualifiedJoin: AssociationJoin {
var finalizedJoin: AssociationJoin {
var join = self
join.query = query.qualifiedQuery
join.query = query.finalizedQuery
return join
}
var allAliases: [TableAlias] {
return query.allAliases
var finalizedAliases: [TableAlias] {
return query.finalizedAliases
}
var completeSelection: [SQLSelectable] {
return query.completeSelection
var finalizedSelection: [SQLSelectable] {
return query.finalizedSelection
}
var completeOrdering: QueryOrdering {
return query.completeOrdering
var finalizedOrdering: QueryOrdering {
return query.finalizedOrdering
}
func rowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? {
return try query.rowAdapter(db, fromIndex: startIndex, forKeyPath: keyPath)
func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? {
return try query.finalizedRowAdapter(db, fromIndex: startIndex, forKeyPath: keyPath)
}
/// precondition: query is the result of finalizedQuery
func joinSQL(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String {
var isRequiredAllowed = isRequiredAllowed
var sql = ""