From ce238b6643fc5c075b655e9fa15e9310dc18267f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 12 Apr 2025 13:23:46 +0200 Subject: [PATCH] Build requests from ColumnsProvider --- .../Association/AssociationAggregate.swift | 1 + .../Request/QueryInterfaceRequest.swift | 2 + .../Request/RequestProtocols.swift | 189 ++++++++++++++++++ .../SQLGeneration/SQLGenerationContext.swift | 1 + .../TableRecord+QueryInterfaceRequest.swift | 125 ++++++++++++ .../MutablePersistableRecord+Update.swift | 1 + 6 files changed, 319 insertions(+) diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 944d5c0f8..4d17fce13 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -89,6 +89,7 @@ extension AssociationToMany { .forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") } + // TODO: provide a ColumnsProvider version /// Returns the average of the given expression in associated records. /// /// For example: diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 6f777c8aa..773a226a6 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -702,6 +702,7 @@ extension QueryInterfaceRequest { return try RowDecoder.ID.fetchSet(statement) } #else + // TODO: provide a ColumnsProvider version /// Returns a `DELETE RETURNING` prepared statement. /// /// For example: @@ -907,6 +908,7 @@ extension QueryInterfaceRequest { return db.changesCount } + // TODO: provide a ColumnsProvider version /// Updates matching rows, and returns the number of updated rows. /// /// For example: diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 29d6a3a58..17dc1a7b7 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -209,6 +209,100 @@ extension SelectionRequest { } } +extension SelectionRequest { + /// Defines the result column. + /// + /// For example: + /// + /// ```swift + /// // SELECT score FROM player + /// let request = Player.all().select { $0.score } + /// ``` + /// + /// Any previous selection is replaced: + /// + /// ```swift + /// // SELECT score FROM player + /// let request = Player.all() + /// .select { $0.id } + /// .select { $0.score } + /// ``` + public func select( + _ selection: (Self.RowDecoder.ColumnsProvider) -> any SQLSelectable + ) -> Self + where Self: TypedRequest, Self.RowDecoder: TableRecord + { + select(selection(Self.RowDecoder.columns)) + } + + /// Defines the result columns. + /// + /// For example: + /// + /// ```swift + /// // SELECT id, score FROM player + /// let request = Player.all().select { [$0.id, $0.score] } + /// ``` + /// + /// Any previous selection is replaced: + /// + /// ```swift + /// // SELECT score FROM player + /// let request = Player.all() + /// .select { [$0.id] } + /// .select { [$0.score] } + /// ``` + public func select( + _ selection: (Self.RowDecoder.ColumnsProvider) -> [any SQLSelectable] + ) -> Self + where Self: TypedRequest, Self.RowDecoder: TableRecord + { + select(selection(Self.RowDecoder.columns)) + } + + /// Appends a result column to the selected columns. + /// + /// For example: + /// + /// ```swift + /// // SELECT *, score + bonus AS totalScore FROM player + /// let request = Player.all().annotated { + /// ($0.score + $0.bonus.forKey("totalScore") + /// } + /// ``` + /// + /// - parameter selection: A closure that accepts a database connection and + /// returns an array of result columns. + public func annotated( + with selection: (Self.RowDecoder.ColumnsProvider) -> any SQLSelectable + ) -> Self + where Self: TypedRequest, Self.RowDecoder: TableRecord + { + annotated(with: selection(Self.RowDecoder.columns)) + } + + /// Appends result columns to the selected columns. + /// + /// For example: + /// + /// ```swift + /// // SELECT *, score + bonus AS totalScore FROM player + /// let request = Player.all().annotated { + /// [($0.score + $0.bonus.forKey("totalScore")] + /// } + /// ``` + /// + /// - parameter selection: A closure that accepts a database connection and + /// returns an array of result columns. + public func annotated( + with selection: (Self.RowDecoder.ColumnsProvider) -> [any SQLSelectable] + ) -> Self + where Self: TypedRequest, Self.RowDecoder: TableRecord + { + annotated(with: selection(Self.RowDecoder.columns)) + } +} + // MARK: - FilteredRequest /// A request that can filter database rows. @@ -310,6 +404,28 @@ extension FilteredRequest { } } +extension FilteredRequest { + // Accept SQLSpecificExpressible instead of SQLExpressible, so that we + // prevent the `Player.filter { 42 }` misuse. + // See https://github.com/groue/GRDB.swift/pull/864 + /// Filters the fetched rows with a boolean SQL expression. + /// + /// For example: + /// + /// ```swift + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let name = "O'Brien" + /// let request = Player.all().filter { $0.name == name } + /// ``` + public func filter( + _ predicate: (Self.RowDecoder.ColumnsProvider) -> any SQLSpecificExpressible + ) -> Self + where Self: TypedRequest, Self.RowDecoder: TableRecord + { + filter(predicate(Self.RowDecoder.columns)) + } +} + // MARK: - TableRequest /// A request that feeds from a database table @@ -925,6 +1041,61 @@ extension AggregatingRequest { } } +extension AggregatingRequest { + /// Returns an aggregate request grouped on the given SQL expression. + /// + /// For example: + /// + /// ```swift + /// // SELECT teamId, MAX(score) + /// // FROM player + /// // GROUP BY teamId + /// let request = Player + /// .select { [$0.teamId, max($0.score)] } + /// .group { $0.teamId } + /// ``` + /// + /// Any previous grouping is discarded. + public func group( + _ expression: (Self.RowDecoder.ColumnsProvider) -> any SQLExpressible + ) -> Self + where Self: TypedRequest, Self.RowDecoder: TableRecord + { + group(expression(Self.RowDecoder.columns)) + } + + /// Returns an aggregate request grouped on the given SQL expressions. + public func group( + _ expressions: (Self.RowDecoder.ColumnsProvider) -> [any SQLExpressible] + ) -> Self + where Self: TypedRequest, Self.RowDecoder: TableRecord + { + group(expressions(Self.RowDecoder.columns)) + } + + /// Filters the aggregated groups with a boolean SQL expression. + /// + /// For example: + /// + /// ```swift + /// // SELECT teamId, MAX(score) + /// // FROM player + /// // GROUP BY teamId + /// // HAVING MAX(score) > 1000 + /// let request = Player + /// .select { [$0.teamId, max($0.score)] } + /// .group { $0.teamId } + /// .having { max($0.score) > 1000 } + /// ``` + public func having( + _ predicate: (Self.RowDecoder.ColumnsProvider) -> any SQLExpressible + ) -> Self + where Self: TypedRequest, Self.RowDecoder: TableRecord + { + having(predicate(Self.RowDecoder.columns)) + } +} + // MARK: - OrderedRequest /// A request that can sort database rows. @@ -1092,6 +1263,24 @@ extension OrderedRequest { } } +extension OrderedRequest { + public func order( + _ ordering: (Self.RowDecoder.ColumnsProvider) -> any SQLOrderingTerm + ) -> Self + where Self: TypedRequest, Self.RowDecoder: TableRecord + { + order(ordering(Self.RowDecoder.columns)) + } + + public func order( + _ orderings: (Self.RowDecoder.ColumnsProvider) -> [any SQLOrderingTerm] + ) -> Self + where Self: TypedRequest, Self.RowDecoder: TableRecord + { + order(orderings(Self.RowDecoder.columns)) + } +} + // MARK: - JoinableRequest /// A request that can join and prefetch associations. diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 8da9ed9f4..54b44f013 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -453,6 +453,7 @@ public class TableAlias: @unchecked Sendable { selectable.sqlSelection.qualified(with: self) } + // TODO: provide a ColumnsProvider version /// Returns an SQL expression that refers to the aliased table. /// /// For example, let's sort books by author name first, and then by title: diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index ad8fb1bb3..2a0c0fd8a 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -67,6 +67,38 @@ extension TableRecord { all().select(selection) } + /// Returns a request that selects the provided result columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT score FROM player + /// let request = Player.select { $0.score } + /// ``` + public static func select( + _ selection: (ColumnsProvider) -> any SQLSelectable + ) -> QueryInterfaceRequest { + all().select(selection) + } + + /// Returns a request that selects the provided result columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT id, score FROM player + /// let request = Player.select { [$0.id, $0.score] } + /// ``` + public static func select( + _ selection: (ColumnsProvider) -> [any SQLSelectable] + ) -> QueryInterfaceRequest { + all().select(selection) + } + /// Returns a request that selects the provided SQL string. /// /// For example: @@ -134,6 +166,7 @@ extension TableRecord { all().select(selection, as: type) } + // TODO: provide a ColumnsProvider version /// Returns a request that selects the provided result columns, and defines /// the type of decoded rows. /// @@ -319,6 +352,46 @@ extension TableRecord { all().annotated(with: selection) } + /// Returns a request with the provided result columns appended to the + /// record selection. + /// + /// The record selection is determined by + /// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT *, score + bonus AS totalScore FROM player + /// let request = Player.annotated { ($0.score + $0.bonus).forKey("totalScore") } + /// ``` + public static func annotated( + with selection: (ColumnsProvider) -> any SQLSelectable + ) -> QueryInterfaceRequest { + all().annotated(with: selection) + } + + /// Returns a request with the provided result columns appended to the + /// record selection. + /// + /// The record selection is determined by + /// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT *, score + bonus AS totalScore FROM player + /// let request = Player.annotated { [($0.score + $0.bonus).forKey("totalScore")] } + /// ``` + public static func annotated( + with selection: (ColumnsProvider) -> [any SQLSelectable] + ) -> QueryInterfaceRequest { + all().annotated(with: selection) + } + // Accept SQLSpecificExpressible instead of SQLExpressible, so that we // prevent the `Player.filter(42)` misuse. // See https://github.com/groue/GRDB.swift/pull/864 @@ -337,6 +410,26 @@ extension TableRecord { all().filter(predicate) } + // Accept SQLSpecificExpressible instead of SQLExpressible, so that we + // prevent the `Player.filter(42)` misuse. + // See https://github.com/groue/GRDB.swift/pull/864 + /// Returns a request filtered with a boolean SQL expression. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let name = "O'Brien" + /// let request = Player.filter { $0.name == name } + /// ``` + public static func filter( + _ predicate: (ColumnsProvider) -> any SQLSpecificExpressible + ) -> QueryInterfaceRequest { + all().filter(predicate) + } + /// Returns a request filtered by primary key. /// /// All single-column primary keys are supported: @@ -500,6 +593,38 @@ extension TableRecord { all().order(orderings) } + /// Returns a request sorted according to the given SQL ordering term. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT * FROM player ORDER BY score DESC + /// let request = Player.order { $0.score.desc } + /// ``` + public static func order( + _ orderings: (ColumnsProvider) -> any SQLOrderingTerm + ) -> QueryInterfaceRequest { + all().order(orderings) + } + + /// Returns a request sorted according to the given SQL ordering terms. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = Player.order { [$0.score.desc, $0.name] } + /// ``` + public static func order( + _ orderings: (ColumnsProvider) -> [any SQLOrderingTerm] + ) -> QueryInterfaceRequest { + all().order(orderings) + } + /// Returns a request sorted by primary key. /// /// All primary keys are supported: diff --git a/GRDB/Record/MutablePersistableRecord+Update.swift b/GRDB/Record/MutablePersistableRecord+Update.swift index 89d81d817..634aeae4b 100644 --- a/GRDB/Record/MutablePersistableRecord+Update.swift +++ b/GRDB/Record/MutablePersistableRecord+Update.swift @@ -60,6 +60,7 @@ extension MutablePersistableRecord { didSave(updated) } + // TODO: provide a ColumnsProvider version /// Executes an `UPDATE` statement on the provided columns. /// /// For example: