From 430141344dd51764d6665b9fe1fd06faed34d4f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 10 May 2025 09:35:53 +0200 Subject: [PATCH] Update more documentation with the closure syntax --- Documentation/CommonTableExpressions.md | 6 +- Documentation/FullTextSearch.md | 4 +- Documentation/QueryInterfaceOrganization.md | 17 +++-- Documentation/SQLInterpolation.md | 2 +- Documentation/WhyAdoptGRDB.md | 4 +- GRDB/Core/Configuration.swift | 4 +- GRDB/Documentation.docc/JSON.md | 16 +++- GRDB/JSON/JSONColumn.swift | 2 +- GRDB/JSON/SQLJSONExpressible.swift | 76 +++++++++++++------ .../Request/QueryInterfaceRequest.swift | 8 +- GRDB/QueryInterface/SQL/SQLExpression.swift | 15 ++-- 11 files changed, 105 insertions(+), 49 deletions(-) diff --git a/Documentation/CommonTableExpressions.md b/Documentation/CommonTableExpressions.md index 4f447ad2b..d0432bfa3 100644 --- a/Documentation/CommonTableExpressions.md +++ b/Documentation/CommonTableExpressions.md @@ -123,7 +123,7 @@ And we can then filter the `player` table with a subquery: // WHERE name = (SELECT * FROM playerName) let request = Player .with(playerNameCTE) - .filter(Column("name") == playerNameCTE.all()) + .filter { $0.name == playerNameCTE.all() } ``` > **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request. @@ -167,13 +167,13 @@ Common table expressions can also be used as subqueries, when you update or dele // UPDATE player SET name = (SELECT * FROM playerName) try Player .with(playerNameCTE) - .updateAll(db, Column("name").set(to: playerNameCTE.all())) + .updateAll(db) { $0.name.set(to: playerNameCTE.all()) } // WITH playerName AS (SELECT 'O''Brien') // DELETE FROM player WHERE name = (SELECT * FROM playerName) try Player .with(playerNameCTE) - .filter(Column("name") == playerNameCTE.all()) + .filter { $0.name == playerNameCTE.all() } .deleteAll(db) ``` diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 447e5cc17..a3b93112d 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -316,7 +316,7 @@ Use them in the [query interface](../README.md#the-query-interface): let documents = try Document.matching(pattern).fetchAll(db) // Search in a specific column: -let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db) +let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db) ``` @@ -565,7 +565,7 @@ Use them in the [query interface](../README.md#the-query-interface): let documents = try Document.matching(pattern).fetchAll(db) // Search in a specific column: -let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db) +let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db) ``` diff --git a/Documentation/QueryInterfaceOrganization.md b/Documentation/QueryInterfaceOrganization.md index a86470be5..4a3b44d62 100644 --- a/Documentation/QueryInterfaceOrganization.md +++ b/Documentation/QueryInterfaceOrganization.md @@ -93,7 +93,7 @@ Columns are special expressions that allow some optimizations and niceties: ValueObservation.tracking { db in try Player.fetchOne(db, id: 1) // or - try Player.filter(Column("id") == 1).fetchOne(db) + try Player.filter { $0.id == 1 }.fetchOne(db) } // Non-optimized observations @@ -110,7 +110,7 @@ Columns are special expressions that allow some optimizations and niceties: // Nicer SQL // SELECT * FROM player WHERE id = 1 try Player.fetchOne(db, id: 1) - try Player.filter(Column("id") == 1).fetchOne(db) + try Player.filter { $0.id == 1 }.fetchOne(db) // Less nice SQL // SELECT * FROM player WHERE id = 1 LIMIT 1 @@ -261,7 +261,7 @@ The basic value types conform to [DatabaseValueConvertible] so that they can fee ```swift // SELECT * FROM player WHERE name = 'O''Brien' // ~~~~~~~~~~ -Player.filter(Column("name") == "O'Brien") +Player.filter { $0.name == "O'Brien" } ``` ### QueryInterfaceRequest @@ -346,8 +346,9 @@ Functions and methods that build an SQL expression should return an SQLExpressio ```swift // SELECT * FROM player WHERE LENGTH(name) > 0 -let expression = length(Column("name")) > 0 // SQLExpression -Player.filter(expression) +Player.filter { + length($0.name) > 0 // SQLExpression +} ``` When it looks like GRDB APIs are unable to build a particular expression, use [SQL]: @@ -358,7 +359,7 @@ func date(_ value: SQLSpecificExpressible) -> SQLExpression { } // SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23' -let request = Player.filter(date(Column("createdAt")) == "2020-01-23") +let request = Player.filter { date($0.createdAt) == "2020-01-23" } ``` This technique, based on [SQL Interpolation], is composable and works well even when several tables are involved. See how the `createdAt` column below is correctly attributed to the `player` table: @@ -368,7 +369,7 @@ This technique, based on [SQL Interpolation], is composable and works well even // JOIN team ON team.id = player.teamId // WHERE DATE(player.createdAt) = '2020-01-23' let request = Player - .filter(date(Column("createdAt")) == "2020-01-23") + .filter { date($0.createdAt) == "2020-01-23" } .including(required: Player.team) ``` @@ -583,7 +584,7 @@ SQLSubqueryable provides the GRDB support for subqueries. Its [SQLSpecificExpres // SELECT * FROM player // WHERE score >= (SELECT AVG(score) FROM player) let averageScore = Player.select(average(Column("score"))) -Player.filter(Column("score") >= averageScore) +Player.filter { $0.score >= averageScore } ``` SQLSubqueryable has the `contains(_:)` and `exists()` methods that support the `value IN (subquery)` and `EXISTS (subquery)` expressions. diff --git a/Documentation/SQLInterpolation.md b/Documentation/SQLInterpolation.md index 1198964e3..0de946d3c 100644 --- a/Documentation/SQLInterpolation.md +++ b/Documentation/SQLInterpolation.md @@ -175,7 +175,7 @@ func date(_ expression: SQLExpressible) -> SQLExpression { SQL("DATE(\(expression))").sqlExpression } -let request = Player.filter(date(Column("createdAt")) == "2020-01-23") +let request = Player.filter { date($0.createdAt) == "2020-01-23" } ``` diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 21205b5d3..e3e3ad402 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -207,13 +207,13 @@ try player.updateChanges { // SELECT * FROM player ORDER BY score DESC LIMIT 10 let bestPlayers: [Player] = try Player - .order(scoreColumn.desc) + .order { $0.score.desc } .limit(10) .fetchAll(db) // SELECT MAX(score) FROM player let maximumScore: Int? = try Player - .select(max(scoreColumn)) + .select { max($0.score) } .asRequestOf(Int.self) .fetchOne(db) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 9e4e16501..067260d62 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -144,7 +144,7 @@ public struct Configuration: Sendable { /// do { /// // The sensitive information to protect /// let email = "..." - /// let player = try Player.filter(Column("email") == email).fetchOne(db) + /// let player = try Player.filter { $0.email == email }.fetchOne(db) /// } catch { /// // By default, sensitive information is NOT printed /// // when an error occurs: @@ -173,7 +173,7 @@ public struct Configuration: Sendable { /// do { /// // The sensitive information to protect /// let email = "..." - /// let player = try Player.filter(Column("email") == email).fetchOne(db) + /// let player = try Player.filter { $0.email == email }.fetchOne(db) /// } catch { /// // Sensitive information is printed in DEBUG builds: /// print(error) diff --git a/GRDB/Documentation.docc/JSON.md b/GRDB/Documentation.docc/JSON.md index d4964bc76..9b11e9873 100644 --- a/GRDB/Documentation.docc/JSON.md +++ b/GRDB/Documentation.docc/JSON.md @@ -36,10 +36,16 @@ try db.create(table: "player") { t in > JSONColumn("address")["country"], > ]) > +> struct Player: FetchableRecord, TableRecord { +> enum Columns { +> static let address = JSONColumn("address") +> } +> } +> > // SELECT * FROM player > // WHERE address ->> 'country' = 'DE' > let germanPlayers = try Player -> .filter(JSONColumn("address")["country"] == "DE") +> .filter { $0.address["country"] == "DE" } > .fetchAll(db) > ``` @@ -104,10 +110,16 @@ extension Team: FetchableRecord, PersistableRecord { > struct Address: Codable { ... } > extension Address: DatabaseValueConvertible {} > +> struct Player: FetchableRecord, TableRecord { +> enum Columns { +> static let address = JSONColumn("address") +> } +> } +> > // SELECT * FROM player > // WHERE address = '{"street": "...", "city": "...", "country": "..."}' > let players = try Player -> .filter(JSONColumn("address") == Address(...)) +> .filter { $0.address == Address(...) } > .fetchAll(db) > ``` > diff --git a/GRDB/JSON/JSONColumn.swift b/GRDB/JSON/JSONColumn.swift index 5a9b86080..e082d0cad 100644 --- a/GRDB/JSON/JSONColumn.swift +++ b/GRDB/JSON/JSONColumn.swift @@ -28,7 +28,7 @@ /// enum Columns { /// static let id = Column(CodingKeys.id) /// static let name = Column(CodingKeys.name) -/// static let address = JSONColumn(CodingKeys.address) // JSONColumn! +/// static let address = JSONColumn(CodingKeys.address) // JSONColumn /// } /// } /// diff --git a/GRDB/JSON/SQLJSONExpressible.swift b/GRDB/JSON/SQLJSONExpressible.swift index e2c402283..39985114c 100644 --- a/GRDB/JSON/SQLJSONExpressible.swift +++ b/GRDB/JSON/SQLJSONExpressible.swift @@ -157,18 +157,22 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT info ->> 'firstName' FROM player /// // → 'Arthur' /// let firstName = try Player - /// .select(info["firstName"], as: String.self) + /// .select({ $0.info["firstName"] }, as: String.self) /// .fetchOne(db) /// /// // SELECT info ->> 'address' FROM player /// // → '{"street":"Rue de Belleville","city":"Paris"}' /// let address = try Player - /// .select(info["address"], as: String.self) + /// .select({ $0.info["address"] }, as: String.self) /// .fetchOne(db) /// ``` /// @@ -185,18 +189,22 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player /// // → 'Arthur' /// let firstName = try Player - /// .select(info.jsonExtract(atPath: "$.firstName"), as: String.self) + /// .select({ $0.info.jsonExtract(atPath: "$.firstName") }, as: String.self) /// .fetchOne(db) /// /// // SELECT JSON_EXTRACT(info, '$.address') FROM player /// // → '{"street":"Rue de Belleville","city":"Paris"}' /// let address = try Player - /// .select(info.jsonExtract(atPath: "$.address"), as: String.self) + /// .select({ $0.info.jsonExtract(atPath: "$.address") }, as: String.self) /// .fetchOne(db) /// ``` /// @@ -212,12 +220,16 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player /// // → '["Arthur","Miller"]' /// let nameComponents = try Player - /// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self) + /// .select({ $0.info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]) }, as: String.self) /// .fetchOne(db) /// ``` /// @@ -235,18 +247,22 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT info -> 'firstName' FROM player /// // → '"Arthur"' /// let name = try Player - /// .select(info.jsonRepresentation(atPath: "firstName"), as: String.self) + /// .select({ $0.info.jsonRepresentation(atPath: "firstName") }, as: String.self) /// .fetchOne(db) /// /// // SELECT info -> 'address' FROM player /// // → '{"street":"Rue de Belleville","city":"Paris"}' /// let name = try Player - /// .select(info.jsonRepresentation(atPath: "address"), as: String.self) + /// .select({ $0.info.jsonRepresentation(atPath: "address") }, as: String.self) /// .fetchOne(db) /// ``` /// @@ -265,18 +281,22 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT info ->> 'firstName' FROM player /// // → 'Arthur' /// let firstName = try Player - /// .select(info["firstName"], as: String.self) + /// .select({ $0.info["firstName"] }, as: String.self) /// .fetchOne(db) /// /// // SELECT info ->> 'address' FROM player /// // → '{"street":"Rue de Belleville","city":"Paris"}' /// let address = try Player - /// .select(info["address"], as: String.self) + /// .select({ $0.info["address"] }, as: String.self) /// .fetchOne(db) /// ``` /// @@ -294,18 +314,22 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player /// // → 'Arthur' /// let firstName = try Player - /// .select(info.jsonExtract(atPath: "$.firstName"), as: String.self) + /// .select({ $0.info.jsonExtract(atPath: "$.firstName") }, as: String.self) /// .fetchOne(db) /// /// // SELECT JSON_EXTRACT(info, '$.address') FROM player /// // → '{"street":"Rue de Belleville","city":"Paris"}' /// let address = try Player - /// .select(info.jsonExtract(atPath: "$.address"), as: String.self) + /// .select({ $0.info.jsonExtract(atPath: "$.address") }, as: String.self) /// .fetchOne(db) /// ``` /// @@ -322,12 +346,16 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player /// // → '["Arthur","Miller"]' /// let nameComponents = try Player - /// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self) + /// .select({ $0.info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]) }, as: String.self) /// .fetchOne(db) /// ``` /// @@ -346,18 +374,22 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT info -> 'firstName' FROM player /// // → '"Arthur"' /// let name = try Player - /// .select(info.jsonRepresentation(atPath: "firstName"), as: String.self) + /// .select({ $0.info.jsonRepresentation(atPath: "firstName") }, as: String.self) /// .fetchOne(db) /// /// // SELECT info -> 'address' FROM player /// // → '{"street":"Rue de Belleville","city":"Paris"}' /// let name = try Player - /// .select(info.jsonRepresentation(atPath: "address"), as: String.self) + /// .select({ $0.info.jsonRepresentation(atPath: "address") }, as: String.self) /// .fetchOne(db) /// ``` /// diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 223c3a213..f6e40d3d0 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -541,9 +541,15 @@ extension QueryInterfaceRequest { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// /// try dbQueue.read { db in /// let maxScore: Int? = try Player - /// .select(max(scoreColumn)) + /// .select { max($0.score) } /// .asRequest(of: Int.self) // <-- /// .fetchOne(db) /// } diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index a3c0ea0e2..7ea83a19a 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -316,12 +316,17 @@ public struct SQLExpression: Sendable { /// Use it with the `joined(operator:)` method. For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let bonus = Column("bonus") + /// } + /// } + /// /// // SELECT score + bonus + 1000 FROM player - /// let values = [ - /// scoreColumn, - /// bonusColumn, - /// 1000.databaseValue] - /// let request = Player.select(values.joined(operator: .add)) + /// let request = Player.select { + /// [$0.score, $0.bonus, 1000.databaseValue].joined(operator: .add) + /// } /// ``` public struct AssociativeBinaryOperator: Hashable, Sendable { /// The SQL operator