diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index fc6fddf57..a562d5b94 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -251,8 +251,7 @@ extension CommonTableExpression where RowDecoder == Row { extension CommonTableExpression { var relationForAll: SQLRelation { - let cte = self.cte - return .all(fromTable: tableName, selection: { _ in [.allCTEColumns(cte)] }) + .all(fromTable: tableName) } /// Creates a request for all rows of the common table expression. @@ -327,13 +326,13 @@ struct SQLCTE { var isRecursive: Bool /// The number of columns in the common table expression. - func columnsCount(_ db: Database) throws -> Int { + func columnCount(_ db: Database) throws -> Int { if let columns = columns { // No need to hit the database return columns.count } - return try sqlSubquery.columnsCount(db) + return try sqlSubquery.columnCount(db) } } diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index a1faad292..7603b1827 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -11,26 +11,6 @@ public struct SQLSelection { /// All columns, qualified: `player.*` case qualifiedAllColumns(TableAlias) - // As long as the CTE is embedded here, the following request will fail - // at runtime, in `columnCount(_:)`, because we can't access the number of - // columns in the CTE: - // - // let association = Player.association(to: cte) - // Player.including(required: association.select(AllColumns(), ...)) - // - // The need for this should not be frequent. And the user has - // two workarounds: - // - // - provide explicit columns in the CTE definition. - // - prefer `annotated(with:)` when she wants to extend the selection. - // - // TODO: Make `cteRequestOrAssociation.select(AllColumns())` possible. - /// All columns of a common table expression - case allCTEColumns(SQLCTE) - - /// All columns of a common table expression, qualified - case qualifiedAllCTEColumns(SQLCTE, TableAlias) - /// An expression case expression(SQLExpression) @@ -51,16 +31,6 @@ public struct SQLSelection { self.init(impl: .qualifiedAllColumns(alias)) } - /// All columns of a common table expression - static func allCTEColumns(_ cte: SQLCTE) -> Self { - self.init(impl: .allCTEColumns(cte)) - } - - /// All columns of a common table expression, qualified - static func qualifiedAllCTEColumns(_ cte: SQLCTE, _ alias: TableAlias) -> Self { - self.init(impl: .qualifiedAllCTEColumns(cte, alias)) - } - /// An expression static func expression(_ expression: SQLExpression) -> Self { self.init(impl: .expression(expression)) @@ -83,21 +53,15 @@ extension SQLSelection { /// Returns the number of columns in the selection. /// /// Returns nil when the number of columns is unknown. - func columnCount(_ db: Database) throws -> Int? { + func columnCount(_ context: SQLGenerationContext) throws -> Int? { switch impl { case .allColumns: // Likely a GRDB bug: we can't count the number of columns in an // unqualified table. return nil - + case let .qualifiedAllColumns(alias): - return try db.columns(in: alias.tableName).count - - case let .allCTEColumns(cte): - return try cte.columnsCount(db) - - case let .qualifiedAllCTEColumns(cte, _): - return try cte.columnsCount(db) + return try context.columnCount(in: alias.tableName) case .expression, .aliasedExpression: @@ -114,12 +78,10 @@ extension SQLSelection { /// TODO: deprecate `count(selection)`, and get rid of this property. var countExpression: SQLExpression { switch impl { - case .allColumns, - .allCTEColumns: + case .allColumns: return .countAll - case .qualifiedAllColumns, - .qualifiedAllCTEColumns: + case .qualifiedAllColumns: // COUNT(player.*) is not valid SQL fatalError("Uncountable selection") @@ -135,8 +97,7 @@ extension SQLSelection { /// If the selection can be counted, return how to count it. func count(distinct: Bool) -> SQLCount? { switch impl { - case .allColumns, - .allCTEColumns: + case .allColumns: // SELECT DISTINCT * FROM tableName ... if distinct { // Can't count @@ -148,8 +109,7 @@ extension SQLSelection { // SELECT COUNT(*) FROM tableName ... return .all - case .qualifiedAllColumns, - .qualifiedAllCTEColumns: + case .qualifiedAllColumns: return nil case let .expression(expression), @@ -183,12 +143,10 @@ extension SQLSelection { /// statement arguments. func countedSQL(_ context: SQLGenerationContext) throws -> String { switch impl { - case .allColumns, - .allCTEColumns: + case .allColumns: return "*" - case let .qualifiedAllColumns(alias), - let .qualifiedAllCTEColumns(_, alias): + case let .qualifiedAllColumns(alias): if context.qualifier(for: alias) != nil { // SELECT COUNT(t.*) is invalid SQL fatalError("Not implemented, or invalid query") @@ -223,12 +181,10 @@ extension SQLSelection { /// statement arguments. func sql(_ context: SQLGenerationContext) throws -> String { switch impl { - case .allColumns, - .allCTEColumns: + case .allColumns: return "*" - case let .qualifiedAllColumns(alias), - let .qualifiedAllCTEColumns(_, alias): + case let .qualifiedAllColumns(alias): if let qualifier = context.qualifier(for: alias) { return qualifier.quotedDatabaseIdentifier + ".*" } @@ -277,16 +233,12 @@ extension SQLSelection { /// Returns a qualified selection func qualified(with alias: TableAlias) -> SQLSelection { switch impl { - case .qualifiedAllColumns, - .qualifiedAllCTEColumns: + case .qualifiedAllColumns: return self case .allColumns: return .qualifiedAllColumns(alias) - case let .allCTEColumns(cte): - return .qualifiedAllCTEColumns(cte, alias) - case let .expression(expression): return .expression(expression.qualified(with: alias)) @@ -305,9 +257,9 @@ extension Array where Element == SQLSelection { /// This method raises a fatal error if the selection contains a literal, /// /// See `SQLSelection.columnCount(_:)` for testability. - func columnCount(_ db: Database) throws -> Int { + func columnCount(_ context: SQLGenerationContext) throws -> Int { try reduce(0) { acc, selection in - guard let count = try selection.columnCount(db) else { + guard let count = try selection.columnCount(context) else { // Found an SQL literal: // - Player.select(sql: "id, name, score") // - Player.select(literal: "id, name, score") diff --git a/GRDB/QueryInterface/SQL/SQLSubquery.swift b/GRDB/QueryInterface/SQL/SQLSubquery.swift index cc5403c46..5c973e34a 100644 --- a/GRDB/QueryInterface/SQL/SQLSubquery.swift +++ b/GRDB/QueryInterface/SQL/SQLSubquery.swift @@ -38,7 +38,7 @@ extension SQLSubquery { /// // We know that "SELECT 1 AS a, 2 AS b" selects two columns, /// // so we can find cte columns in the row: /// row.scopes["cte"] // [a:1, b:2] - func columnsCount(_ db: Database) throws -> Int { + func columnCount(_ db: Database) throws -> Int { switch impl { case let .literal(sqlLiteral): // Compile request. We can freely use the statement cache because we @@ -49,7 +49,7 @@ extension SQLSubquery { return statement.columnCount case let .relation(relation): - return try SQLQueryGenerator(relation: relation).columnsCount(db) + return try SQLQueryGenerator(relation: relation).columnCount(db) } } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 4d1c65d38..f336278e5 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -26,7 +26,7 @@ final class SQLGenerationContext { /// All gathered arguments var arguments: StatementArguments { argumentsSink.arguments } - /// Access to the database connection, the arguments sink, and resolved + /// Access to the database connection, the arguments sink, ctes, and resolved /// names of table aliases from outer contexts (useful in case of /// subquery generation). private let parent: Parent @@ -41,38 +41,48 @@ final class SQLGenerationContext { private let resolvedNames: [TableAlias: String] private let ownAliases: Set + private let ownCTEs: [String: SQLCTE] /// Creates a generation context. /// /// - parameter db: A database connection. /// - parameter argumentsSink: An arguments sink. /// - parameter aliases: An array of table aliases to disambiguate. + /// - parameter ctes: An dictionary of available CTEs. init( _ db: Database, argumentsSink: StatementArgumentsSink = StatementArgumentsSink(), - aliases: [TableAlias] = []) + aliases: [TableAlias] = [], + ctes: OrderedDictionary = [:]) { self.parent = .none(db: db, argumentsSink: argumentsSink) self.resolvedNames = aliases.resolvedNames self.ownAliases = Set(aliases) + self.ownCTEs = Dictionary(uniqueKeysWithValues: ctes.lazy.map { ($0.lowercased(), $1) }) } /// Creates a generation context. /// /// - parameter parent: A parent context. /// - parameter aliases: An array of table aliases to disambiguate. + /// - parameter ctes: An dictionary of available CTEs. private init( parent: SQLGenerationContext, - aliases: [TableAlias]) + aliases: [TableAlias], + ctes: OrderedDictionary) { self.parent = .context(parent) self.resolvedNames = aliases.resolvedNames self.ownAliases = Set(aliases) + self.ownCTEs = Dictionary(uniqueKeysWithValues: ctes.lazy.map { ($0.lowercased(), $1) }) } /// Returns a generation context suitable for subqueries. - func subqueryContext(aliases: [TableAlias] = []) -> SQLGenerationContext { - SQLGenerationContext(parent: self, aliases: aliases) + func subqueryContext( + aliases: [TableAlias] = [], + ctes: OrderedDictionary = [:]) -> SQLGenerationContext + { + SQLGenerationContext(parent: self, aliases: aliases, ctes: ctes) } /// Returns whether arguments could be appended. @@ -124,6 +134,18 @@ final class SQLGenerationContext { } return nil } + + func columnCount(in tableName: String) throws -> Int { + if let cte = ownCTEs[tableName.lowercased()] { + return try cte.columnCount(db) + } + switch parent { + case let .context(context): + return try context.columnCount(in: tableName) + case let .none(db: db, argumentsSink: _): + return try db.columns(in: tableName).count + } + } } /// A class that gathers statement arguments, and can be shared between diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 088579bc7..4fbc9b311 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -19,7 +19,7 @@ struct SQLQueryGenerator: Refinable { } func requestSQL(_ context: SQLGenerationContext) throws -> String { - let context = context.subqueryContext(aliases: relation.allAliases) + let context = context.subqueryContext(aliases: relation.allAliases, ctes: relation.ctes) var sql = try commonTableExpressionsPrefix(context) sql += "SELECT" @@ -94,15 +94,15 @@ struct SQLQueryGenerator: Refinable { func makePreparedRequest(_ db: Database) throws -> PreparedRequest { try PreparedRequest( statement: makeSelectStatement(db), - adapter: rowAdapter(db)) + adapter: rowAdapter(SQLGenerationContext(db, ctes: relation.ctes))) } /// The number of fetched columns. - func columnsCount(_ db: Database) throws -> Int { + func columnCount(_ db: Database) throws -> Int { try relation .selectionPromise .resolve(db) - .columnCount(db) + .columnCount(SQLGenerationContext(db, ctes: relation.ctes)) } /// Returns a select statement @@ -206,7 +206,7 @@ struct SQLQueryGenerator: Refinable { return try makeTrivialDeleteStatement(db) } - let context = SQLGenerationContext(db, aliases: relation.allAliases) + let context = SQLGenerationContext(db, aliases: relation.allAliases, ctes: relation.ctes) var sql = try commonTableExpressionsPrefix(context) sql += try "DELETE FROM " + relation.source.sql(context) @@ -245,7 +245,7 @@ struct SQLQueryGenerator: Refinable { let tableName = relation.source.tableName let alias = TableAlias(tableName: tableName) let context = SQLGenerationContext(db, aliases: [alias]) - let subqueryContext = context.subqueryContext(aliases: relation.allAliases) + let subqueryContext = context.subqueryContext(aliases: relation.allAliases, ctes: relation.ctes) let primaryKey = SQLExpression.fastPrimaryKey var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE " @@ -281,7 +281,7 @@ struct SQLQueryGenerator: Refinable { return nil } - let context = SQLGenerationContext(db, aliases: relation.allAliases) + let context = SQLGenerationContext(db, aliases: relation.allAliases, ctes: relation.ctes) var sql = try commonTableExpressionsPrefix(context) sql += "UPDATE " @@ -343,7 +343,7 @@ struct SQLQueryGenerator: Refinable { let tableName = relation.source.tableName let alias = TableAlias(tableName: tableName) let context = SQLGenerationContext(db, aliases: [alias]) - let subqueryContext = context.subqueryContext(aliases: relation.allAliases) + let subqueryContext = context.subqueryContext(aliases: relation.allAliases, ctes: relation.ctes) let primaryKey = SQLExpression.fastPrimaryKey // UPDATE table... @@ -469,8 +469,8 @@ struct SQLQueryGenerator: Refinable { /// row.scopes["author"] // [id:12, name:"Herman Melville"] /// let author: Author = row["author"] /// } - private func rowAdapter(_ db: Database) throws -> RowAdapter? { - try relation.rowAdapter(db, fromIndex: 0)?.adapter + private func rowAdapter(_ context: SQLGenerationContext) throws -> RowAdapter? { + try relation.rowAdapter(context, fromIndex: 0)?.adapter } } @@ -590,7 +590,6 @@ private struct SQLQualifiedRelation { /// See SQLQueryGenerator.rowAdapter(_:) /// - /// - parameter db: A database connection. /// - parameter startIndex: The index of the leftmost selected column of /// this relation in a full SQL query. `startIndex` is 0 for the relation /// at the root of a SQLQueryGenerator (as opposed to the @@ -598,7 +597,11 @@ private struct SQLQualifiedRelation { /// - returns: An optional tuple made of a RowAdapter and the index past the /// rightmost selected column of this relation. Nil is returned if this /// relations does not need any row adapter. - func rowAdapter(_ db: Database, fromIndex startIndex: Int) throws -> (adapter: RowAdapter, endIndex: Int)? { + func rowAdapter( + _ context: SQLGenerationContext, + fromIndex startIndex: Int) throws + -> (adapter: RowAdapter, endIndex: Int)? + { // Root relation && no join => no need for any adapter if startIndex == 0 && joins.isEmpty { return nil @@ -606,14 +609,14 @@ private struct SQLQualifiedRelation { // The number of columns in source selection. Columns selected by joined // relations are appended after. - let sourceSelectionWidth = try sourceSelectionPromise.resolve(db).columnCount(db) + let sourceSelectionWidth = try sourceSelectionPromise.resolve(context.db).columnCount(context) // Recursively build adapters for each joined relation with a selection. // Name them according to the join keys. var endIndex = startIndex + sourceSelectionWidth var scopes: [String: RowAdapter] = [:] for (key, join) in joins { - if let (joinAdapter, joinEndIndex) = try join.relation.rowAdapter(db, fromIndex: endIndex) { + if let (joinAdapter, joinEndIndex) = try join.relation.rowAdapter(context, fromIndex: endIndex) { scopes[key] = joinAdapter endIndex = joinEndIndex } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 120e42d20..f6d658e6f 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -133,9 +133,10 @@ extension TableRecord { public static func numberOfSelectedColumns(_ db: Database) throws -> Int { // The alias makes it possible to count the columns in `SELECT *`: let alias = TableAlias(tableName: databaseTableName) + let context = SQLGenerationContext(db) return try databaseSelection .map { $0.sqlSelection.qualified(with: alias) } - .columnCount(db) + .columnCount(context) } }