From e924587236f717326f0d83c37f1f60f325e2eb7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 3 Feb 2019 14:31:59 +0100 Subject: [PATCH] Extract generation of SQL SELECT queries into SQLSelectQueryGenerator --- GRDB.xcodeproj/project.pbxproj | 8 + .../Association/Association.swift | 2 +- .../QueryInterfaceRequest.swift | 6 +- GRDB/QueryInterface/SQLRelation.swift | 198 ++-------- GRDB/QueryInterface/SQLSelectQuery.swift | 194 +--------- .../SQLSelectQueryGenerator.swift | 342 ++++++++++++++++++ GRDBCipher.xcodeproj/project.pbxproj | 6 + GRDBCustom.xcodeproj/project.pbxproj | 6 + .../QueryInterfaceRequestTests.swift | 9 + 9 files changed, 423 insertions(+), 348 deletions(-) create mode 100644 GRDB/QueryInterface/SQLSelectQueryGenerator.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index b5fe20bb8..e06acb792 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -446,6 +446,9 @@ 56873BEC1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 56873BEF1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 56873BF21F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; + 568D131F2207213E00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */; }; + 568D13202207213E00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */; }; + 568D13212207213F00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */; }; 5690AFD82120589A001530EA /* InsertRecordCodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */; }; 5690AFD92120589A001530EA /* InsertRecordCodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */; }; 5690AFDB212058CB001530EA /* FetchRecordCodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordCodableTests.swift */; }; @@ -1074,6 +1077,7 @@ 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = ""; }; + 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQueryGenerator.swift; sourceTree = ""; }; 5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordCodableTests.swift; sourceTree = ""; }; 5690AFDA212058CB001530EA /* FetchRecordCodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRecordCodableTests.swift; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; @@ -1537,6 +1541,7 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, 56D91AAF2205F8AC00770D8D /* SQLSelectQuery.swift */, + 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, 566475C91D981D5E00FF74B8 /* Support */, 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */, @@ -2564,6 +2569,7 @@ 5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 5653EC142098738B00F46237 /* SQLGenerationContext.swift in Sources */, 56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, + 568D13212207213F00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */, 5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 565490C61D5AE236005622CB /* Statement.swift in Sources */, @@ -2651,6 +2657,7 @@ 56CEB51C1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 5698AC3A1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 5664759D1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, + 568D13202207213E00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 563EF416215F87EB007DAACD /* OrderedDictionary.swift in Sources */, 563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */, @@ -3196,6 +3203,7 @@ 56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, + 568D131F2207213E00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 56BF6D361DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56193E8E1CD8A3E200F95862 /* FetchedRecordsController.swift in Sources */, diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 3a95ad8e4..d38f4cdcb 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -398,7 +398,7 @@ public /* TODO: internal */ struct JoinAssociationImpl: AssociationImpl { } public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { - let join = Join( + let join = SQLJoin( joinOperator: joinOperator, joinCondition: joinCondition, relation: self.relation) diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index d41bdf733..5d155f840 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -34,7 +34,7 @@ extension QueryInterfaceRequest : FetchRequest { /// - returns: A prepared statement and an eventual row adapter. /// :nodoc: public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try query.finalizedQuery.prepare(db) + return try SQLSelectQueryGenerator(query).prepare(db) } /// Returns the number of rows fetched by the request. @@ -50,7 +50,7 @@ extension QueryInterfaceRequest : FetchRequest { /// - parameter db: A database connection. /// :nodoc: public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - return try query.finalizedQuery.databaseRegion(db) + return try SQLSelectQueryGenerator(query).databaseRegion(db) } } @@ -290,7 +290,7 @@ extension QueryInterfaceRequest where T: MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @discardableResult public func deleteAll(_ db: Database) throws -> Int { - try query.makeDeleteStatement(db).execute() + try SQLSelectQueryGenerator(query).makeDeleteStatement(db).execute() return db.changesCount } } diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index 9b347cb2d..269310d13 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -6,22 +6,22 @@ /// /// :nodoc: public /* TODO: internal */ struct SQLRelation { - var source: SQLRelation.Source + var source: SQLSource var selection: [SQLSelectable] var filterPromise: DatabasePromise var ordering: SQLRelation.Ordering - var joins: OrderedDictionary + var joins: OrderedDictionary var alias: TableAlias? { return source.alias } init( - source: SQLRelation.Source, + source: SQLSource, selection: [SQLSelectable] = [], filterPromise: DatabasePromise = DatabasePromise(value: nil), ordering: SQLRelation.Ordering = SQLRelation.Ordering(), - joins: OrderedDictionary = [:]) + joins: OrderedDictionary = [:]) { self.source = source self.selection = selection @@ -74,7 +74,7 @@ extension SQLRelation { return order(SQLRelation.Ordering()) } - func appendingJoin(_ join: Join, forKey key: String) -> SQLRelation { + func appendingJoin(_ join: SQLJoin, forKey key: String) -> SQLRelation { var relation = self if let existingJoin = relation.joins.removeValue(forKey: key) { guard let mergedJoin = existingJoin.merged(with: join) else { @@ -95,48 +95,33 @@ extension SQLRelation { } } -// MARK: - SQLRelation.Source +// MARK: - SQLSource -extension SQLRelation { - enum Source { - case table(tableName: String, alias: TableAlias?) - indirect case query(SQLSelectQuery) - - var alias: TableAlias? { - switch self { - case .table(_, let alias): - return alias - case .query(let query): - return query.alias - } +enum SQLSource { + case table(tableName: String, alias: TableAlias?) + indirect case query(SQLSelectQuery) + + var alias: TableAlias? { + switch self { + case .table(_, let alias): + return alias + case .query(let query): + return query.alias } - - func sourceSQL(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { - switch self { - case .table(let tableName, let alias): - if let alias = alias, let aliasName = context.aliasName(for: alias) { - return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)" - } else { - return "\(tableName.quotedDatabaseIdentifier)" - } - case .query(let query): - return try "(\(query.sql(db, &context)))" - } - } - - func qualified(with alias: TableAlias) -> Source { - switch self { - case .table(let tableName, let sourceAlias): - if let sourceAlias = sourceAlias { - alias.becomeProxy(of: sourceAlias) - return self - } else { - alias.setTableName(tableName) - return .table(tableName: tableName, alias: alias) - } - case .query(let query): - return .query(query.qualified(with: alias)) + } + + func qualified(with alias: TableAlias) -> SQLSource { + switch self { + case .table(let tableName, let sourceAlias): + if let sourceAlias = sourceAlias { + alias.becomeProxy(of: sourceAlias) + return self + } else { + alias.setTableName(tableName) + return .table(tableName: tableName, alias: alias) } + case .query(let query): + return .query(query.qualified(with: alias)) } } } @@ -230,7 +215,7 @@ extension SQLRelation { } } -// MARK: - Join +// MARK: - SQLJoin /// Not to be mismatched with SQL join operators (inner join, left join). /// @@ -357,50 +342,10 @@ public /* TODO: internal */ struct JoinCondition: Equatable { } } -struct Join { +struct SQLJoin { var joinOperator: JoinOperator var joinCondition: JoinCondition var relation: SQLRelation - - var finalizedJoin: Join { - var join = self - join.relation = relation.finalizedRelation - return join - } - - /// - precondition: relation is the result of finalizedRelation - func joinSQL(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String { - var isRequiredAllowed = isRequiredAllowed - var sql = "" - switch joinOperator { - case .optional: - isRequiredAllowed = false - sql += "LEFT JOIN" - case .required: - guard isRequiredAllowed else { - // TODO: chainOptionalRequired - fatalError("Not implemented: chaining a required association behind an optional association") - } - sql += "JOIN" - } - - sql += try " " + relation.source.sourceSQL(db, &context) - - let rightAlias = relation.alias! - let filters = try [ - joinCondition.sqlExpression(db, leftAlias: leftAlias, rightAlias: rightAlias), - relation.filterPromise.resolve(db) - ].compactMap { $0 } - if !filters.isEmpty { - sql += " ON " + filters.joined(operator: .and).expressionSQL(&context) - } - - for (_, join) in relation.joins { - sql += try " " + join.joinSQL(db, &context, leftAlias: rightAlias, isRequiredAllowed: isRequiredAllowed) - } - - return sql - } } // MARK: - Merging @@ -435,7 +380,7 @@ extension SQLRelation { return expressions.joined(operator: .and) } - var mergedJoins: OrderedDictionary = [:] + var mergedJoins: OrderedDictionary = [:] for (key, join) in joins { if let otherJoin = other.joins[key] { guard let mergedJoin = join.merged(with: otherJoin) else { @@ -466,9 +411,9 @@ extension SQLRelation { } } -extension SQLRelation.Source { +extension SQLSource { /// Returns nil if sources can't be merged (conflict in tables, aliases...) - func merged(with other: SQLRelation.Source) -> SQLRelation.Source? { + func merged(with other: SQLSource) -> SQLSource? { switch (self, other) { case let (.table(tableName: tableName, alias: alias), .table(tableName: otherTableName, alias: otherAlias)): guard tableName == otherTableName else { @@ -494,9 +439,9 @@ extension SQLRelation.Source { } } -extension Join { +extension SQLJoin { /// Returns nil if joins can't be merged (conflict in condition, relation...) - func merged(with other: Join) -> Join? { + func merged(with other: SQLJoin) -> SQLJoin? { guard joinCondition == other.joinCondition else { // can't merge return nil @@ -515,78 +460,9 @@ extension Join { mergedJoinOperator = .optional } - return Join( + return SQLJoin( joinOperator: mergedJoinOperator, joinCondition: joinCondition, relation: mergedRelation) } } - -// MARK: - Finalization -// -// "Finalization" is the operation which gathers all information required -// for SQL generation. - -extension SQLRelation { - /// A finalized relation is ready for SQL generation - var finalizedRelation: SQLRelation { - var relation = self - - let alias = TableAlias() - relation.source = source.qualified(with: alias) - relation.selection = selection.map { $0.qualifiedSelectable(with: alias) } - relation.filterPromise = filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } - relation.ordering = ordering.qualified(with: alias) - relation.joins = joins.mapValues { $0.finalizedJoin } - - return relation - } - - /// - precondition: self is the result of finalizedRelation - var finalizedAliases: [TableAlias] { - var aliases: [TableAlias] = [] - if let alias = alias { - aliases.append(alias) - } - return joins.reduce(into: aliases) { - $0.append(contentsOf: $1.value.relation.finalizedAliases) - } - } - - /// - precondition: self is the result of finalizedRelation - var finalizedSelection: [SQLSelectable] { - return joins.reduce(into: selection) { - $0.append(contentsOf: $1.value.relation.finalizedSelection) - } - } - - /// - precondition: self is the result of finalizedRelation - var finalizedOrdering: SQLRelation.Ordering { - return joins.reduce(ordering) { - $0.appending($1.value.relation.finalizedOrdering) - } - } - - /// - precondition: self is the result of finalizedRelation - func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { - let selectionWidth = try selection - .map { try $0.columnCount(db) } - .reduce(0, +) - - var endIndex = startIndex + selectionWidth - var scopes: [String: RowAdapter] = [:] - for (key, join) in joins { - if let (joinAdapter, joinEndIndex) = try join.relation.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [key]) { - scopes[key] = joinAdapter - endIndex = joinEndIndex - } - } - - if selectionWidth == 0 && scopes.isEmpty { - return nil - } - - let adapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth)) - return (adapter: adapter.addingScopes(scopes), endIndex: endIndex) - } -} diff --git a/GRDB/QueryInterface/SQLSelectQuery.swift b/GRDB/QueryInterface/SQLSelectQuery.swift index 1247d8130..15e62f6b0 100644 --- a/GRDB/QueryInterface/SQLSelectQuery.swift +++ b/GRDB/QueryInterface/SQLSelectQuery.swift @@ -1,4 +1,6 @@ -/// SQLSelectQuery generates SQL for query interface requests. +/// SQLSelectQuery is a representation of an SQL SELECT query. +/// +/// See SQLSelectQueryGenerator for actual SQL generation. struct SQLSelectQuery { var relation: SQLRelation var isDistinct: Bool @@ -91,180 +93,11 @@ extension SQLSelectQuery: SelectionRequest, FilteredRequest, OrderedRequest { } extension SQLSelectQuery { - /// A finalized query is ready for SQL generation - var finalizedQuery: SQLSelectQuery { - var query = self - - query.relation = query.relation.finalizedRelation - let alias = query.relation.alias! - query.groupPromise = query.groupPromise?.map { [alias] (_, exprs) in exprs.map { $0.qualifiedExpression(with: alias) } } - query.havingExpression = query.havingExpression?.qualifiedExpression(with: alias) - - return query - } - - /// - precondition: self is the result of finalizedQuery - private func finalizedRowAdapter(_ db: Database) throws -> RowAdapter? { - // No join => no adapter - if relation.joins.isEmpty { - return nil - } - - guard let (adapter, _) = try relation.finalizedRowAdapter(db, fromIndex: 0, forKeyPath: []) else { - return nil - } - - return adapter - } -} - -extension SQLSelectQuery { - /// - precondition: self is the result of finalizedQuery - func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { - var sql = "SELECT" - - if isDistinct { - sql += " DISTINCT" - } - - let selection = relation.finalizedSelection - GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") - sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") - - sql += try " FROM " + relation.source.sourceSQL(db, &context) - - for (_, join) in relation.joins { - sql += try " " + join.joinSQL(db, &context, leftAlias: alias!, isRequiredAllowed: true) - } - - if let filter = try relation.filterPromise.resolve(db) { - sql += " WHERE " + filter.expressionSQL(&context) - } - - if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { - sql += " GROUP BY " - sql += groupExpressions.map { $0.expressionSQL(&context) } - .joined(separator: ", ") - } - - if let havingExpression = havingExpression { - sql += " HAVING " + havingExpression.expressionSQL(&context) - } - - let orderings = try relation.finalizedOrdering.resolve(db) - 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: relation.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 { - if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { - // 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 relation.joins.isEmpty else { - // Programmer error - fatalError("Can't delete query with JOIN clause") - } - - guard case .table = relation.source else { - // Programmer error - fatalError("Can't delete without any database table") - } - - var context = SQLGenerationContext.queryGenerationContext(aliases: relation.finalizedAliases) - - var sql = try "DELETE FROM " + relation.source.sourceSQL(db, &context) - - if let filter = try relation.filterPromise.resolve(db) { - sql += " WHERE " + filter.expressionSQL(&context) - } - - if let limit = limit { - let orderings = try relation.finalizedOrdering.resolve(db) - 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) + let (statement, adapter) = try SQLSelectQueryGenerator(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 databaseRegion(_ db: Database) throws -> DatabaseRegion { - let statement = try makeSelectStatement(db) - let databaseRegion = statement.databaseRegion - - // Can we intersect the region with rowIds? - // - // Give up unless request feeds from a single database table - guard case .table(tableName: let tableName, alias: _) = relation.source else { - // TODO: try harder - return databaseRegion - } - - // Give up unless primary key is rowId - let primaryKeyInfo = try db.primaryKey(tableName) - guard primaryKeyInfo.isRowID else { - return databaseRegion - } - - // Give up unless there is a where clause - guard let filter = try relation.filterPromise.resolve(db) else { - return databaseRegion - } - - // The filter knows better - guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { - return databaseRegion - } - - // Database regions are case-insensitive: use the canonical table name - let canonicalTableName = try db.canonicalTableName(tableName) - return databaseRegion.tableIntersection(canonicalTableName, rowIds: rowIds) - } - private var countQuery: SQLSelectQuery { guard groupPromise == nil && limit == nil else { // SELECT ... GROUP BY ... @@ -282,8 +115,14 @@ extension SQLSelectQuery { guard let count = relation.selection[0].count(distinct: isDistinct) else { return trivialCountQuery } - var countQuery = self.unordered().select(count.sqlSelectable) + var countQuery = self.unordered() countQuery.isDistinct = false + switch count { + case .all: + countQuery = countQuery.select(SQLExpressionCount(AllColumns())) + case .distinct(let expression): + countQuery = countQuery.select(SQLExpressionCountDistinct(expression)) + } return countQuery } else { // SELECT [DISTINCT] expr1, expr2, ... FROM tableName ... @@ -320,14 +159,3 @@ struct SQLLimit { } } } - -extension SQLCount { - fileprivate var sqlSelectable: SQLSelectable { - switch self { - case .all: - return SQLExpressionCount(AllColumns()) - case .distinct(let expression): - return SQLExpressionCountDistinct(expression) - } - } -} diff --git a/GRDB/QueryInterface/SQLSelectQueryGenerator.swift b/GRDB/QueryInterface/SQLSelectQueryGenerator.swift new file mode 100644 index 000000000..2947fb98f --- /dev/null +++ b/GRDB/QueryInterface/SQLSelectQueryGenerator.swift @@ -0,0 +1,342 @@ +/// SQLSelectQueryGenerator is able to generate an SQL SELECT query. +struct SQLSelectQueryGenerator { + private let relation: SQLQualifiedRelation + private let isDistinct: Bool + private let groupPromise: DatabasePromise<[SQLExpression]>? + private let havingExpression: SQLExpression? + private let limit: SQLLimit? + + init(_ query: SQLSelectQuery) { + // 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, as in the example below: + // + // // SELECT book.*, person1.*, person2.*, COUNT(DISTINCT awards.id) + // // FROM book + // // LEFT JOIN person person1 WHERE person1.id = book.authorId + // // LEFT JOIN person person2 WHERE person2.id = book.translatorId + // // LEFT JOIN award WHERE award.bookId = book.id + // let request = Book + // .including(optional: Book.author) + // .including(optional: Book.translator) + // .annotated(with: Book.awards.count) + 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 alias = relation.alias + groupPromise = query.groupPromise?.map { [alias] (_, exprs) in exprs.map { $0.qualifiedExpression(with: alias) } } + havingExpression = query.havingExpression?.qualifiedExpression(with: alias) + + // Preserve other flags + isDistinct = query.isDistinct + limit = query.limit + } + + func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { + var sql = "SELECT" + + if isDistinct { + sql += " DISTINCT" + } + + let selection = relation.fullSelection + GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") + sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") + + sql += try " FROM " + relation.source.sql(db, &context) + + for (_, join) in relation.joins { + sql += try " " + join.sql(db, &context, leftAlias: relation.alias, isRequiredAllowed: true) + } + + if let filter = try relation.filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&context) + } + + if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { + sql += " GROUP BY " + sql += groupExpressions.map { $0.expressionSQL(&context) } + .joined(separator: ", ") + } + + if let havingExpression = havingExpression { + sql += " HAVING " + havingExpression.expressionSQL(&context) + } + + let orderings = try relation.ordering.resolve(db) + if !orderings.isEmpty { + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") + } + + if let limit = limit { + sql += " LIMIT " + limit.sql + } + + return sql + } + + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (makeSelectStatement(db), rowAdapter(db)) + } + + func databaseRegion(_ db: Database) throws -> DatabaseRegion { + let statement = try makeSelectStatement(db) + let databaseRegion = statement.databaseRegion + + // Can we intersect the region with rowIds? + // + // Give up unless request feeds from a single database table + guard case .table(tableName: let tableName, alias: _) = relation.source else { + // TODO: try harder + return databaseRegion + } + + // Give up unless primary key is rowId + let primaryKeyInfo = try db.primaryKey(tableName) + guard primaryKeyInfo.isRowID else { + return databaseRegion + } + + // Give up unless there is a where clause + guard let filter = try relation.filterPromise.resolve(db) else { + return databaseRegion + } + + // The filter knows better + guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { + return databaseRegion + } + + // Database regions are case-insensitive: use the canonical table name + let canonicalTableName = try db.canonicalTableName(tableName) + return databaseRegion.tableIntersection(canonicalTableName, rowIds: rowIds) + } + + func makeDeleteStatement(_ db: Database) throws -> UpdateStatement { + if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { + // 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 relation.joins.isEmpty else { + // Programmer error + fatalError("Can't delete query with JOIN clause") + } + + guard case .table = relation.source else { + // Programmer error + fatalError("Can't delete without any database table") + } + + var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases) + + var sql = try "DELETE FROM " + relation.source.sql(db, &context) + + if let filter = try relation.filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&context) + } + + if let limit = limit { + let orderings = try relation.ordering.resolve(db) + 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 + } + + private func makeSelectStatement(_ db: Database) throws -> SelectStatement { + var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases) + let statement = try db.makeSelectStatement(sql(db, &context)) + statement.arguments = context.arguments! + return statement + } + + private func rowAdapter(_ db: Database) throws -> RowAdapter? { + return try relation.rowAdapter(db, fromIndex: 0, forKeyPath: [])?.adapter + } +} + +/// A "qualified" relation, where all tables are identified with a table alias. +private struct SQLQualifiedRelation { + /// The alias for the source + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ alias + let alias: TableAlias + + /// Own alias plus aliases of all joined relations + let allAliases: [TableAlias] + + /// The source + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ source + let source: SQLQualifiedSource + + /// The selection, not including selection of joined relations + private let ownSelection: [SQLSelectable] + + /// The full selection, including selection of joined relations + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ fullSelection + let fullSelection: [SQLSelectable] + + /// The filtering clause + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ filterPromise + let filterPromise: DatabasePromise + + /// The ordering + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ ordering + let ordering: SQLRelation.Ordering + + /// The joins + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ joins + let joins: OrderedDictionary + + init(_ relation: SQLRelation) { + let alias = TableAlias() + self.alias = alias + source = SQLQualifiedSource(relation.source.qualified(with: alias)) + joins = relation.joins.mapValues(SQLQualifiedJoin.init) + ownSelection = relation.selection.map { $0.qualifiedSelectable(with: alias) } + fullSelection = joins.reduce(into: ownSelection) { + $0.append(contentsOf: $1.value.relation.fullSelection) + } + filterPromise = relation.filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } + let ownOrdering = relation.ordering.qualified(with: alias) + ordering = joins.reduce(ownOrdering) { + $0.appending($1.value.relation.ordering) + } + allAliases = joins.reduce(into: [alias]) { + $0.append(contentsOf: $1.value.relation.allAliases) + } + } + + func rowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { + if startIndex == 0 && joins.isEmpty { + // Root relation + no join => no adapter + return nil + } + + let selectionWidth = try ownSelection + .map { try $0.columnCount(db) } + .reduce(0, +) + + var endIndex = startIndex + selectionWidth + var scopes: [String: RowAdapter] = [:] + for (key, join) in joins { + if let (joinAdapter, joinEndIndex) = try join.relation.rowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [key]) { + scopes[key] = joinAdapter + endIndex = joinEndIndex + } + } + + if selectionWidth == 0 && scopes.isEmpty { + return nil + } + + let adapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth)) + return (adapter: adapter.addingScopes(scopes), endIndex: endIndex) + } +} + +/// A "qualified" source, where all tables are identified with a table alias. +private enum SQLQualifiedSource { + case table(tableName: String, alias: TableAlias) + indirect case query(SQLSelectQueryGenerator) + + init(_ source: SQLSource) { + switch source { + case .table(let tableName, let sourceAlias): + self = .table(tableName: tableName, alias: sourceAlias ?? TableAlias()) + case .query(let query): + self = .query(SQLSelectQueryGenerator(query)) + } + } + + func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { + switch self { + case .table(let tableName, let alias): + if let aliasName = context.aliasName(for: alias) { + return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)" + } else { + return "\(tableName.quotedDatabaseIdentifier)" + } + case .query(let query): + return try "(\(query.sql(db, &context)))" + } + } +} + +/// A "qualified" join, where all tables are identified with a table alias. +private struct SQLQualifiedJoin { + private let joinOperator: JoinOperator + private let joinCondition: JoinCondition + let relation: SQLQualifiedRelation + + init(_ join: SQLJoin) { + self.joinOperator = join.joinOperator + self.joinCondition = join.joinCondition + self.relation = SQLQualifiedRelation(join.relation) + } + + func sql(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String { + var isRequiredAllowed = isRequiredAllowed + var sql = "" + switch joinOperator { + case .optional: + isRequiredAllowed = false + sql += "LEFT JOIN" + case .required: + guard isRequiredAllowed else { + // TODO: chainOptionalRequired + fatalError("Not implemented: chaining a required association behind an optional association") + } + sql += "JOIN" + } + + sql += try " " + relation.source.sql(db, &context) + + let rightAlias = relation.alias + let filters = try [ + joinCondition.sqlExpression(db, leftAlias: leftAlias, rightAlias: rightAlias), + relation.filterPromise.resolve(db) + ].compactMap { $0 } + if !filters.isEmpty { + sql += " ON " + filters.joined(operator: .and).expressionSQL(&context) + } + + for (_, join) in relation.joins { + sql += try " " + join.sql(db, &context, leftAlias: rightAlias, isRequiredAllowed: isRequiredAllowed) + } + + return sql + } +} diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 14f84c3ef..71a9ec433 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -590,6 +590,8 @@ 56873BED1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 56873BF01F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 568BE5231CB0371D00270F93 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 560FC54D1CB003810014AA8E /* GRDBCipher.framework */; }; + 568D13242207214D00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13222207214D00674B58 /* SQLSelectQueryGenerator.swift */; }; + 568D13252207214D00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13222207214D00674B58 /* SQLSelectQueryGenerator.swift */; }; 568E1CB21CB037BA008D97A6 /* sqlite3.h in Headers */ = {isa = PBXBuildFile; fileRef = 568BE5191CB035A900270F93 /* sqlite3.h */; settings = {ATTRIBUTES = (Public, ); }; }; 568E1CB91CB03847008D97A6 /* GRDBCipher-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 568E1CB71CB03847008D97A6 /* GRDBCipher-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; 568E1CBA1CB03847008D97A6 /* GRDBCipher.h in Headers */ = {isa = PBXBuildFile; fileRef = 568E1CB81CB03847008D97A6 /* GRDBCipher.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -1189,6 +1191,7 @@ 568BE5191CB035A900270F93 /* sqlite3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sqlite3.h; path = SQLCipher/src/sqlite3.h; sourceTree = ""; }; 568BE51F1CB0360500270F93 /* GRDBCipher.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = GRDBCipher.xcconfig; path = SQLCipher/GRDBCipher.xcconfig; sourceTree = ""; }; 568BE5201CB0360500270F93 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; name = module.modulemap; path = SQLCipher/module.modulemap; sourceTree = ""; }; + 568D13222207214D00674B58 /* SQLSelectQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQueryGenerator.swift; sourceTree = ""; }; 568E1CB71CB03847008D97A6 /* GRDBCipher-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "GRDBCipher-Bridging.h"; path = "SQLCipher/GRDBCipher-Bridging.h"; sourceTree = ""; }; 568E1CB81CB03847008D97A6 /* GRDBCipher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = GRDBCipher.h; path = SQLCipher/GRDBCipher.h; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; @@ -1620,6 +1623,7 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, 56D91AB32205F8C000770D8D /* SQLSelectQuery.swift */, + 568D13222207214D00674B58 /* SQLSelectQueryGenerator.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, 566475C91D981D5E00FF74B8 /* Support */, 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */, @@ -2403,6 +2407,7 @@ 560FC5381CB003810014AA8E /* DatabaseDateComponents.swift in Sources */, 56BF6D371DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56193E961CD8A3E300F95862 /* FetchedRecordsController.swift in Sources */, + 568D13242207214D00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 56B964BA1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 560FC5391CB003810014AA8E /* DatabaseReader.swift in Sources */, 560FC53A1CB003810014AA8E /* NSNull.swift in Sources */, @@ -2890,6 +2895,7 @@ 56AFCA0D1CB1A8BB00F48B96 /* DatabaseDateComponents.swift in Sources */, 56BF6D3A1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56AFCA0E1CB1A8BB00F48B96 /* DatabaseReader.swift in Sources */, + 568D13252207214D00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 56B964BD1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 56AFCA0F1CB1A8BB00F48B96 /* NSNull.swift in Sources */, 56AFCA101CB1A8BB00F48B96 /* DatabaseQueue.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 77514725e..3fc2177d0 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -263,6 +263,8 @@ 568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 56873BEE1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 56873BF11F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; + 568D13152207210400674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13142207210400674B58 /* SQLSelectQueryGenerator.swift */; }; + 568D13162207210400674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13142207210400674B58 /* SQLSelectQueryGenerator.swift */; }; 5690C3291D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; }; 5690C32D1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; }; 5690C33A1D23E7D200E59934 /* FoundationDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */; }; @@ -820,6 +822,7 @@ 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = ""; }; + 568D13142207210400674B58 /* SQLSelectQueryGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelectQueryGenerator.swift; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateTests.swift; sourceTree = ""; }; 5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = ""; }; @@ -1228,6 +1231,7 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */, + 568D13142207210400674B58 /* SQLSelectQueryGenerator.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, 566475C91D981D5E00FF74B8 /* Support */, 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */, @@ -2040,6 +2044,7 @@ F3BA80111CFB2876003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */, F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */, + 568D13162207210400674B58 /* SQLSelectQueryGenerator.swift in Sources */, 56BF6D3B1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, @@ -2347,6 +2352,7 @@ F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */, F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */, + 568D13152207210400674B58 /* SQLSelectQueryGenerator.swift in Sources */, 56BF6D381DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index 231b703ac..7eaa646d8 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -41,6 +41,15 @@ class QueryInterfaceRequestTests: GRDBTestCase { try migrator.migrate(dbWriter) } + // MARK: - Preparation + + func testSimpleRequestDoesNotUseAnyRowAdapter() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let (statement, adapter) = try Reader.all().prepare(db) + XCTAssertNil(adapter) + } + } // MARK: - Fetch rows