diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index 535166789..cef9bcbe6 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -61,6 +61,13 @@ extension ColumnExpression { extension ColumnExpression where Self == Column { /// The hidden rowID column. + /// + /// For example: + /// + /// ```swift + /// // SELECT rowid FROM player + /// let rowids = try Player.select(.rowID).fetchSet(db) + /// ``` public static var rowID: Self { Column.rowID } } diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 9f26b9983..a4955fcad 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -2136,7 +2136,14 @@ public protocol SQLExpressible { } extension SQLExpressible where Self == Column { - /// The hidden rowID column + /// The hidden rowID column. + /// + /// For example: + /// + /// ```swift + /// // SELECT rowid FROM player + /// let rowids = try Player.select(.rowID).fetchSet(db) + /// ``` public static var rowID: Self { Column.rowID } } diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index a04883dc5..95ccd4ce7 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -26,6 +26,12 @@ public struct SQLSelection: Sendable { /// All columns, qualified: `player.*` case qualifiedAllColumns(TableAlias) + /// All columns but the specified ones + case allColumnsExcluding(Set) + + /// All columns but the specified ones, qualified. + case qualifiedAllColumnsExcluding(TableAlias, Set) + /// An expression case expression(SQLExpression) @@ -41,11 +47,21 @@ public struct SQLSelection: Sendable { /// All columns: `*` static let allColumns = SQLSelection(impl: .allColumns) + /// All columns but the specified ones. + static func allColumnsExcluding(_ excludedColumns: Set) -> Self { + SQLSelection(impl: .allColumnsExcluding(excludedColumns)) + } + /// All columns, qualified: `player.*` static func qualifiedAllColumns(_ alias: TableAlias) -> Self { self.init(impl: .qualifiedAllColumns(alias)) } + /// All columns but the specified ones, qualified. + static func qualifiedAllColumnsExcluding(_ alias: TableAlias, _ excludedColumns: Set) -> Self { + self.init(impl: .qualifiedAllColumnsExcluding(alias, excludedColumns)) + } + /// An expression static func expression(_ expression: SQLExpression) -> Self { self.init(impl: .expression(expression)) @@ -70,13 +86,16 @@ extension SQLSelection { /// Returns nil when the number of columns is unknown. func columnCount(_ context: SQLGenerationContext) throws -> Int? { switch impl { - case .allColumns: + case .allColumns, .allColumnsExcluding: // Likely a GRDB bug: we can't count the number of columns in an // unqualified table. return nil case let .qualifiedAllColumns(alias): - return try context.columnCount(in: alias.tableName) + return try context.columnCount(in: alias.tableName, excluding: []) + + case let .qualifiedAllColumnsExcluding(alias, excludedColumns): + return try context.columnCount(in: alias.tableName, excluding: excludedColumns) case .expression, .aliasedExpression: @@ -104,7 +123,28 @@ extension SQLSelection { // SELECT COUNT(*) FROM tableName ... return .all - case .qualifiedAllColumns: + case .allColumnsExcluding: + // SELECT DISTINCT a, b, c FROM tableName ... + if distinct { + // TODO: if the selection were qualified, and if we had a + // database connection, we could detect the case where there + // remains only one column, and we could perform a + // SELECT COUNT(DISTINCT remainingColumn) FROM tableName + // + // Since most people will not use `.allColumns(excluding:)` + // when they want to select only one column, I guess that + // this optimization has little chance to be needed. + // + // Can't count + return nil + } + + // SELECT a, b, c FROM tableName ... + // -> + // SELECT COUNT(*) FROM tableName ... + return .all + + case .qualifiedAllColumns, .qualifiedAllColumnsExcluding: return nil case let .expression(expression), @@ -144,11 +184,38 @@ extension SQLSelection { case .allColumns: return "*" + case .allColumnsExcluding: + // Likely a GRDB bug: we don't know the table name so we can't + // load remaining columns. This selection should have been + // turned into a `.qualifiedAllColumnsExcluding`. + fatalError("Not implemented, or invalid query") + case let .qualifiedAllColumns(alias): if let qualifier = context.qualifier(for: alias) { return qualifier.quotedDatabaseIdentifier + ".*" } return "*" + + case let .qualifiedAllColumnsExcluding(alias, excludedColumns): + let columnsNames = try context.columnNames(in: alias.tableName) + let remainingColumnsNames = if excludedColumns.isEmpty { + columnsNames + } else { + columnsNames.filter { + !excludedColumns.contains(CaseInsensitiveIdentifier(rawValue: $0)) + } + } + if columnsNames.count == remainingColumnsNames.count { + // We're not excluding anything + if let qualifier = context.qualifier(for: alias) { + return qualifier.quotedDatabaseIdentifier + ".*" + } + return "*" + } else { + return try remainingColumnsNames + .map { try SQLExpression.column($0).qualified(with: alias).sql(context) } + .joined(separator: ", ") + } case let .expression(expression): return try expression.sql(context) @@ -193,12 +260,15 @@ extension SQLSelection { /// Returns a qualified selection func qualified(with alias: TableAlias) -> SQLSelection { switch impl { - case .qualifiedAllColumns: + case .qualifiedAllColumns, .qualifiedAllColumnsExcluding: return self case .allColumns: return .qualifiedAllColumns(alias) + case let .allColumnsExcluding(excludedColumns): + return .qualifiedAllColumnsExcluding(alias, excludedColumns) + case let .expression(expression): return .expression(expression.qualified(with: alias)) @@ -227,6 +297,8 @@ extension SQLSelection { return true case .allColumns, .qualifiedAllColumns: return false + case .allColumnsExcluding, .qualifiedAllColumnsExcluding: + return false case .expression: return false } @@ -272,15 +344,41 @@ enum SQLCount { /// /// ## Topics /// +/// ### Standard Selections +/// +/// - ``rowID`` +/// - ``allColumns`` +/// - ``allColumns(excluding:)-3sg4w`` +/// - ``allColumns(excluding:)-3blq4`` +/// /// ### Supporting Types /// /// - ``AllColumns`` +/// - ``AllColumnsExcluding`` /// - ``SQLSelection`` public protocol SQLSelectable { /// Returns an SQL selection. var sqlSelection: SQLSelection { get } } +extension SQLSelectable where Self == Column { + /// The hidden rowID column. + /// + /// For example: + /// + /// ```swift + /// struct Player: FetchableRecord, TableRecord { + /// static var databaseSelection: [any SQLSelectable] { + /// [.allColumns, .rowID] + /// } + /// } + /// + /// // SELECT *, rowid FROM player + /// Player.fetchAll(db) + /// ``` + public static var rowID: Self { Column.rowID } +} + extension SQLSelection: SQLSelectable { // Not a real deprecation, just a usage warning @available(*, deprecated, message: "Already SQLSelection") @@ -294,10 +392,14 @@ extension SQLSelection: SQLSelectable { /// For example: /// /// ```swift -/// try dbQueue.read { db in -/// // SELECT * FROM player -/// let players = try Player.select(AllColumns()).fetchAll(db) +/// struct Player: FetchableRecord, TableRecord { +/// static var databaseSelection: [any SQLSelectable] { +/// [.allColumns, .rowID] +/// } /// } +/// +/// // SELECT *, rowid FROM player +/// Player.fetchAll(db) /// ``` public struct AllColumns: Sendable { /// The `*` selection. @@ -309,3 +411,92 @@ extension AllColumns: SQLSelectable { .allColumns } } + +extension SQLSelectable where Self == AllColumns { + /// All columns of the requested table. + /// + /// For example: + /// + /// ```swift + /// struct Player: FetchableRecord, TableRecord { + /// static var databaseSelection: [any SQLSelectable] { + /// [.allColumns, .rowID] + /// } + /// } + /// + /// // SELECT *, rowid FROM player + /// Player.fetchAll(db) + /// ``` + public static var allColumns: AllColumns { AllColumns() } +} + +// MARK: - AllColumnsExcluding + +/// `AllColumnsExcluding` selects all columns in a database table, but the +/// ones you specify. +/// +/// For example: +/// +/// ```swift +/// struct Player: TableRecord { +/// static var databaseSelection: [any SQLSelectable] { +/// [.allColumns(excluding: ["computedColumn"])] +/// } +/// } +/// +/// // SELECT id, name, score FROM player +/// Player.fetchAll(db) +/// ``` +public struct AllColumnsExcluding: Sendable { + var excludedColumns: Set + + public init(_ excludedColumns: some Collection) { + self.excludedColumns = Set(excludedColumns.lazy.map { + CaseInsensitiveIdentifier(rawValue: $0) + }) + } +} + +extension AllColumnsExcluding: SQLSelectable { + public var sqlSelection: SQLSelection { + .allColumnsExcluding(excludedColumns) + } +} + +extension SQLSelectable where Self == AllColumnsExcluding { + /// All columns of the requested table, excluding the provided columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// static var databaseSelection: [any SQLSelectable] { + /// [.allColumns(excluding: ["computedColumn"])] + /// } + /// } + /// + /// // SELECT id, name, score FROM player + /// Player.fetchAll(db) + /// ``` + public static func allColumns(excluding excludedColumns: some Collection) -> Self { + AllColumnsExcluding(excludedColumns) + } + + /// All columns of the requested table, excluding the provided columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// static var databaseSelection: [any SQLSelectable] { + /// [.allColumns(excluding: [Column("computedColumn")])] + /// } + /// } + /// + /// // SELECT id, name, score FROM player + /// Player.fetchAll(db) + /// ``` + public static func allColumns(excluding excludedColumns: some Collection) -> Self { + AllColumnsExcluding(excludedColumns.map(\.name)) + } +} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index ed1470ecd..8da9ed9f4 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -153,15 +153,50 @@ final class SQLGenerationContext { return nil } - func columnCount(in tableName: String) throws -> Int { + /// Return the number of columns in the table or CTE identified + /// by `tableName`. + /// + /// - parameter tableName: The table name. + /// - parameter excludedColumns: The eventual set of excluded columns. + func columnCount( + in tableName: String, + excluding excludedColumns: Set + ) throws -> Int { if let cte = ownCTEs[tableName.lowercased()] { - return try cte.columnCount(db) + if excludedColumns.isEmpty { + return try cte.columnCount(db) + } else { + fatalError("Not implemented: counting CTE columns with excluded columns") + } } switch parent { case let .context(context): - return try context.columnCount(in: tableName) + return try context.columnCount(in: tableName, excluding: excludedColumns) case let .none(db: db, argumentsSink: _): - return try db.columns(in: tableName).count + if excludedColumns.isEmpty { + return try db.columns(in: tableName).count + } else { + return try db + .columns(in: tableName) + .filter { !excludedColumns.contains(CaseInsensitiveIdentifier(rawValue: $0.name)) } + .count + } + } + } + + /// Return the names of the columns in the table or CTE identified + /// by `tableName`. + /// + /// - parameter tableName: The table name. + func columnNames(in tableName: String) throws -> [String] { + if ownCTEs[tableName.lowercased()] != nil { + fatalError("Not implemented: extracing CTE column names") + } + switch parent { + case let .context(context): + return try context.columnNames(in: tableName) + case let .none(db: db, argumentsSink: _): + return try db.columns(in: tableName).map(\.name) } } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 5b37ead62..e18a46c32 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -235,7 +235,11 @@ struct SQLQueryGenerator: Refinable { sql += " LIMIT " + limit.sql } - return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection) + return try makeStatement( + db, sql: sql, + arguments: context.arguments, + returning: selection, + from: relation.source.tableName) case .unique: return try makeTrivialDeleteStatement(db, selection: selection) @@ -264,7 +268,11 @@ struct SQLQueryGenerator: Refinable { sql += try selectPrimaryKey.requestSQL(subqueryContext) sql += ")" - return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection) + return try makeStatement( + db, sql: sql, + arguments: context.arguments, + returning: selection, + from: tableName) } /// Returns an `UPDATE` statement, with `RETURNING` clause if `selection` @@ -323,7 +331,11 @@ struct SQLQueryGenerator: Refinable { sql += " LIMIT " + limit.sql } - return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection) + return try makeStatement( + db, sql: sql, + arguments: context.arguments, + returning: selection, + from: relation.source.tableName) case .unique: return try makeTrivialUpdateStatement( @@ -380,7 +392,11 @@ struct SQLQueryGenerator: Refinable { sql += try selectPrimaryKey.requestSQL(subqueryContext) sql += ")" - return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection) + return try makeStatement( + db, sql: sql, + arguments: context.arguments, + returning: selection, + from: tableName) } // Support for the RETURNING clause @@ -388,7 +404,8 @@ struct SQLQueryGenerator: Refinable { _ db: Database, sql: String, arguments: StatementArguments, - returning selection: [any SQLSelectable]) + returning selection: [any SQLSelectable], + from tableName: String) throws -> Statement { if selection.isEmpty { @@ -396,12 +413,17 @@ struct SQLQueryGenerator: Refinable { statement.arguments = arguments return statement } else { - let context = SQLGenerationContext(db) + // Generate the RETURNING clause by turning selection into SQL. + // Make sure the selection is qualified with a table alias, so + // that selectables such as `.allColumns(excluding:)` can query + // the database about the database table. + let alias = TableAlias(tableName: tableName) + let context = SQLGenerationContext(db, aliases: [alias]) var sql = sql var arguments = arguments sql += " RETURNING " sql += try selection - .map { try $0.sqlSelection.sql(context) } + .map { try $0.sqlSelection.qualified(with: alias).sql(context) } .joined(separator: ", ") arguments += context.arguments let statement = try db.makeStatement(sql: sql) diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 35a9912b1..b12f4f47d 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -67,7 +67,12 @@ extension SQLInterpolation { /// let player: Player = ... /// let request: SQLRequest = "SELECT \(columnsOf: Player.self, tableAlias: "p") FROM player p" public mutating func appendInterpolation(columnsOf recordType: (some TableRecord).Type, tableAlias: String? = nil) { - let alias = TableAlias(name: tableAlias ?? recordType.databaseTableName) + // Make sure we provide the tableName, so that we can interpolate + // the columns of a type whose `databaseSelection` contains an + // instance of `AllColumnsExcluding`. + let alias = TableAlias( + tableName: recordType.databaseTableName, + userName: tableAlias ?? recordType.databaseTableName) elements.append(contentsOf: recordType.databaseSelection .map { CollectionOfOne(.selection($0.sqlSelection.qualified(with: alias))) } .joined(separator: CollectionOfOne(.sql(", ")))) @@ -79,7 +84,7 @@ extension SQLInterpolation { /// /// // SELECT * FROM player /// let request: SQLRequest = """ - /// SELECT \(AllColumns()) FROM player + /// SELECT \(.allColumns) FROM player /// """ public mutating func appendInterpolation(_ selection: some SQLSelectable) { elements.append(.selection(selection.sqlSelection)) @@ -89,7 +94,7 @@ extension SQLInterpolation { /// /// // SELECT * FROM player /// let request: SQLRequest = """ - /// SELECT \(AllColumns()) FROM player + /// SELECT \(.allColumns) FROM player /// """ @_disfavoredOverload public mutating func appendInterpolation(_ selection: (any SQLSelectable)?) { diff --git a/GRDB/Record/MutablePersistableRecord+DAO.swift b/GRDB/Record/MutablePersistableRecord+DAO.swift index 89efd4cd7..82d8b199d 100644 --- a/GRDB/Record/MutablePersistableRecord+DAO.swift +++ b/GRDB/Record/MutablePersistableRecord+DAO.swift @@ -249,12 +249,17 @@ final class DAO { statement.setUncheckedArguments(arguments) return statement } else { - let context = SQLGenerationContext(db) + // Generate the RETURNING clause by turning selection into SQL. + // Make sure the selection is qualified with a table alias, so + // that selectables such as `.allColumns(excluding:)` can query + // the database about the database table. + let alias = TableAlias(tableName: databaseTableName) + let context = SQLGenerationContext(db, aliases: [alias]) var sql = sql var arguments = arguments sql += " RETURNING " sql += try selection - .map { try $0.sqlSelection.sql(context) } + .map { try $0.sqlSelection.qualified(with: alias).sql(context) } .joined(separator: ", ") arguments += context.arguments let statement = try db.internalCachedStatement(sql: sql) diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index eed3a1292..443ddf728 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -107,7 +107,7 @@ open class Record { /// try PartialPlayer.fetchAll(db) /// ``` open class var databaseSelection: [any SQLSelectable] { - [AllColumns()] + [.allColumns] } /// Encodes the record into the provided persistence container. diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 72719873c..f246419d5 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -135,7 +135,7 @@ public protocol TableRecord { /// ```swift /// struct Player: TableRecord { /// static var databaseSelection: [any SQLSelectable] { - /// [AllColumns()] + /// [.allColumns] /// } /// } /// @@ -168,7 +168,7 @@ public protocol TableRecord { /// > // concurrency-safe because non-'Sendable' type /// > // '[any SQLSelectable]' may have shared /// > // mutable state. - /// > static let databaseSelection: [any SQLSelectable] = [AllColumns()] + /// > static let databaseSelection: [any SQLSelectable] = [.allColumns] /// > ``` static var databaseSelection: [any SQLSelectable] { get } } @@ -215,9 +215,9 @@ extension TableRecord { defaultDatabaseTableName } - /// The default selection is all columns: `[AllColumns()]`. + /// The default selection is all columns: `[.allColumns]`. public static var databaseSelection: [any SQLSelectable] { - [AllColumns()] + [.allColumns] } }