From 5f2185a118dd74ae3decb07a9fdf82822eb4fed2 Mon Sep 17 00:00:00 2001 From: Dianna Date: Sun, 29 Sep 2024 21:44:34 +0000 Subject: [PATCH 01/15] use #if directives to conditionally @preconcurrency import the Dispatch module to enable building the package on linux --- GRDB/Core/Configuration.swift | 3 +++ GRDB/Core/SchedulingWatchdog.swift | 3 +++ GRDB/Utils/Utils.swift | 3 +++ 3 files changed, 9 insertions(+) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 059bbb86f..9e4e16501 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -7,6 +7,9 @@ import SQLCipher import SQLite3 #endif +#if !canImport(Darwin) +@preconcurrency +#endif import Dispatch import Foundation diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index 3c2ba702b..dfbdfdace 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -1,3 +1,6 @@ +#if !canImport(Darwin) +@preconcurrency +#endif import Dispatch /// SchedulingWatchdog makes sure that databases connections are used on correct diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 561c3b91f..d690b9eec 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -1,3 +1,6 @@ +#if !canImport(Darwin) +@preconcurrency import Dispatch +#endif import Foundation // MARK: - Public From d7754fa79c4e6862ddd378fcae912f1a71a59d2e Mon Sep 17 00:00:00 2001 From: Phil Mitchell Date: Mon, 30 Sep 2024 11:32:03 +1000 Subject: [PATCH 02/15] Add coalesce free function and Row method --- GRDB/Core/Row.swift | 39 +++++++++++++ GRDB/QueryInterface/SQL/SQLFunctions.swift | 12 ++++ README.md | 11 +++- Tests/GRDBTests/SimpleFunctionTests.swift | 67 ++++++++++++++++++++++ 4 files changed, 127 insertions(+), 2 deletions(-) create mode 100644 Tests/GRDBTests/SimpleFunctionTests.swift diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index f1e49e5f6..25432870b 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -671,6 +671,45 @@ extension Row { public func dataNoCopy(_ column: some ColumnExpression) -> Data? { dataNoCopy(named: column.name) } + + /// Returns the first non-null value, if any. Identical to SQL COALESCE function. + /// + /// For example: + /// + /// ```swift + /// let myInt: Int? = row.coalesce(["int_A", "int_B"]) + /// ``` + /// + /// Use of `coalesce` is essential, as nil-coalescing row values does not work: + /// + /// ```swift + /// let myInt: Int? = row["int_A"] ?? row["int_B"] // Won't work + /// ``` + public func coalesce(_ columns: [String]) -> T? { + for column in columns { + if let value = self[column] as T? { + return value + } + } + return nil + } + + /// Returns the first non-null value, if any. Identical to SQL COALESCE function. + /// + /// For example: + /// + /// ```swift + /// let myInt: Int? = row.coalesce([Column("int_A"), Column("int_B")]) + /// ``` + /// + /// Use of `coalesce` is essential, as nil-coalescing row values does not work: + /// + /// ```swift + /// let myInt: Int? = row[Column("int_A")] ?? row[Column("int_B")] // Won't work + /// ``` + public func coalesce(_ columns: [any ColumnExpression]) -> T? { + return coalesce(columns.lazy.map { $0.name }) + } } extension Row { diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index fab42b8e4..7e209e333 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -71,6 +71,18 @@ public func cast(_ expression: some SQLSpecificExpressible, as storageClass: Dat .cast(expression.sqlExpression, as: storageClass) } +/// The `COALESCE` SQL function. +/// +/// For example: +/// +/// ```swift +/// // COALESCE([value1, value2, ...]) +/// coalesce([Column("value1"), Column("value2"), ...]) +/// ``` +public func coalesce(_ values: [some SQLSpecificExpressible]) -> SQLExpression { + .function("COALESCE", values.map { $0.sqlExpression }) +} + /// The `COUNT` SQL function. /// /// For example: diff --git a/README.md b/README.md index ff9bcc965..5f338f8e6 100644 --- a/README.md +++ b/README.md @@ -841,6 +841,13 @@ row[...] as Int? > if let int = row[...] as Int? { ... } // GOOD > ``` +> **Warning**: avoid nil-coalescing row values: +> +> ```swift +> let myInt: Int? = row["int_A"] ?? row["int_B"] // BAD - doesn't work +> let myInt: Int? = row.coalesce(["int_A", "int_B"]) // GOOD +> ``` + Generally speaking, you can extract the type you need, provided it can be converted from the underlying SQLite value: - **Successful conversions include:** @@ -3936,9 +3943,9 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli GRDB comes with a Swift version of many SQLite [built-in functions](https://sqlite.org/lang_corefunc.html), listed below. But not all: see [Embedding SQL in Query Interface Requests] for a way to add support for missing SQL functions. -- `ABS`, `AVG`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`, `TOTAL`: +- `ABS`, `AVG`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`, `TOTAL`, `COALESCE`: - Those are based on the `abs`, `average`, `count`, `dateTime`, `julianDay`, `length`, `max`, `min`, `sum` and `total` Swift functions: + Those are based on the `abs`, `average`, `count`, `dateTime`, `julianDay`, `length`, `max`, `min`, `sum`, `total`, and `coalesce` Swift functions: ```swift // SELECT MIN(score), MAX(score) FROM player diff --git a/Tests/GRDBTests/SimpleFunctionTests.swift b/Tests/GRDBTests/SimpleFunctionTests.swift new file mode 100644 index 000000000..d9ccb1224 --- /dev/null +++ b/Tests/GRDBTests/SimpleFunctionTests.swift @@ -0,0 +1,67 @@ +import XCTest +import GRDB + +private struct Player: Codable, FetchableRecord, PersistableRecord { + var id: Int64 + var name: String? + var nickname: String? + var score: Int +} + +class SimpleFunctionTests: GRDBTestCase { + + override func setup(_ dbWriter: some DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "player") { t in + t.primaryKey("id", .integer) + t.column("name", .text) + t.column("nickname", .text) + t.column("score", .integer) + } + + try Player(id: 1, name: "Arthur", nickname: "Artie", score: 100).insert(db) + try Player(id: 2, name: "Jacob", nickname: nil, score: 200).insert(db) + try Player(id: 3, name: nil, nickname: nil, score: 200).insert(db) + } + } + + func testCoalesce() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + do { + let request = Player.annotated(with: coalesce([Column("nickname"), Column("name")])) + try assertEqualSQL(db, request, """ + SELECT *, COALESCE("nickname", "name") \ + FROM "player" + """) + } + do { + let request = Player.annotated(with: coalesce([Column("nickname"), Column("name")]).forKey("foo")) + try assertEqualSQL(db, request, """ + SELECT *, COALESCE("nickname", "name") AS "foo" \ + FROM "player" + """) + } + } + } + + func testRowCoalesce() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Player.all() + let rows = try Row.fetchAll(db, request) + var row = rows[0] + XCTAssertEqual(row.coalesce(["nickname", "name"]), "Artie") + XCTAssertEqual(row.coalesce([Column("nickname"), Column("name")]), "Artie") + row = rows[1] + XCTAssertEqual(row.coalesce(["nickname", "name"]), "Jacob") + XCTAssertEqual(row.coalesce([Column("nickname"), Column("name")]), "Jacob") + row = rows[2] + var result: String? = row.coalesce(["nickname", "name"]) + XCTAssertNil(result) + result = row.coalesce([Column("nickname"), Column("name")]) + XCTAssertNil(result) + } + } + +} From c6781f46d21d5441df8b8319c9968210c609b88e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Oct 2024 11:59:12 +0200 Subject: [PATCH 03/15] Prefer Collection over Array This allows the user to call those methods with an Array, or any other collection at hand (including lazy ones) This change makes `return coalesce(columns.lazy.map { $0.name })` iterate lazily. Before this commit, `map` was returning a non-lazy Array. --- GRDB/Core/Row.swift | 8 ++++++-- GRDB/QueryInterface/SQL/SQLFunctions.swift | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 25432870b..da8ef298e 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -685,7 +685,9 @@ extension Row { /// ```swift /// let myInt: Int? = row["int_A"] ?? row["int_B"] // Won't work /// ``` - public func coalesce(_ columns: [String]) -> T? { + public func coalesce( + _ columns: some Collection + ) -> T? { for column in columns { if let value = self[column] as T? { return value @@ -707,7 +709,9 @@ extension Row { /// ```swift /// let myInt: Int? = row[Column("int_A")] ?? row[Column("int_B")] // Won't work /// ``` - public func coalesce(_ columns: [any ColumnExpression]) -> T? { + public func coalesce( + _ columns: some Collection + ) -> T? { return coalesce(columns.lazy.map { $0.name }) } } diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 7e209e333..44f203aa5 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -79,7 +79,7 @@ public func cast(_ expression: some SQLSpecificExpressible, as storageClass: Dat /// // COALESCE([value1, value2, ...]) /// coalesce([Column("value1"), Column("value2"), ...]) /// ``` -public func coalesce(_ values: [some SQLSpecificExpressible]) -> SQLExpression { +public func coalesce(_ values: some Collection) -> SQLExpression { .function("COALESCE", values.map { $0.sqlExpression }) } From a13c1bec29b5105833aa0c35ca7ad53df432d0ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Oct 2024 12:01:40 +0200 Subject: [PATCH 04/15] Add coalesce in DocC --- GRDB/Core/Row.swift | 2 ++ GRDB/QueryInterface/SQL/SQLExpression.swift | 1 + 2 files changed, 3 insertions(+) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index da8ef298e..c94de1c8c 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -60,6 +60,8 @@ import Foundation /// - ``subscript(_:)-3tp8o`` /// - ``subscript(_:)-4k8od`` /// - ``subscript(_:)-9rbo7`` +/// - ``coalesce(_:)-359k7`` +/// - ``coalesce(_:)-6nbah`` /// - ``withUnsafeData(named:_:)`` /// - ``dataNoCopy(named:)`` /// diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 58acaf7c4..9f26b9983 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -2168,6 +2168,7 @@ extension SQLExpressible where Self == Column { /// - ``average(_:filter:)`` /// - ``capitalized`` /// - ``cast(_:as:)-1dmu3`` +/// - ``coalesce(_:)`` /// - ``count(_:)`` /// - ``count(distinct:)`` /// - ``dateTime(_:_:)`` From 8cac458efc6e4d0c99902310cac9fe017aebd2df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Oct 2024 12:18:02 +0200 Subject: [PATCH 05/15] Use "real" column names in examples. Also, remove "essential". --- GRDB/Core/Row.swift | 20 ++++++++++++-------- GRDB/QueryInterface/SQL/SQLFunctions.swift | 2 +- README.md | 6 +++--- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index c94de1c8c..8d39236bd 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -674,18 +674,20 @@ extension Row { dataNoCopy(named: column.name) } - /// Returns the first non-null value, if any. Identical to SQL COALESCE function. + /// Returns the first non-null value, if any. Identical to SQL `COALESCE` function. /// /// For example: /// /// ```swift - /// let myInt: Int? = row.coalesce(["int_A", "int_B"]) + /// let name: String? = row.coalesce(["nickname", "name"]) /// ``` /// - /// Use of `coalesce` is essential, as nil-coalescing row values does not work: + /// Prefer `coalesce` to nil-coalescing row values, which does not + /// return the expected value: /// /// ```swift - /// let myInt: Int? = row["int_A"] ?? row["int_B"] // Won't work + /// // INCORRECT + /// let name: String? = row["nickname"] ?? row["name"] /// ``` public func coalesce( _ columns: some Collection @@ -698,18 +700,20 @@ extension Row { return nil } - /// Returns the first non-null value, if any. Identical to SQL COALESCE function. + /// Returns the first non-null value, if any. Identical to SQL `COALESCE` function. /// /// For example: /// /// ```swift - /// let myInt: Int? = row.coalesce([Column("int_A"), Column("int_B")]) + /// let name: String? = row.coalesce([Column("nickname"), Column("name")]) /// ``` /// - /// Use of `coalesce` is essential, as nil-coalescing row values does not work: + /// Prefer `coalesce` to nil-coalescing row values, which does not + /// return the expected value: /// /// ```swift - /// let myInt: Int? = row[Column("int_A")] ?? row[Column("int_B")] // Won't work + /// // INCORRECT + /// let name: String? = row[Column("nickname")] ?? row[Column("name")] /// ``` public func coalesce( _ columns: some Collection diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 44f203aa5..dde4a4e16 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -76,7 +76,7 @@ public func cast(_ expression: some SQLSpecificExpressible, as storageClass: Dat /// For example: /// /// ```swift -/// // COALESCE([value1, value2, ...]) +/// // COALESCE(value1, value2, ...) /// coalesce([Column("value1"), Column("value2"), ...]) /// ``` public func coalesce(_ values: some Collection) -> SQLExpression { diff --git a/README.md b/README.md index 5f338f8e6..e682103ad 100644 --- a/README.md +++ b/README.md @@ -841,11 +841,11 @@ row[...] as Int? > if let int = row[...] as Int? { ... } // GOOD > ``` -> **Warning**: avoid nil-coalescing row values: +> **Warning**: avoid nil-coalescing row values, and prefer the `coalesce` method instead: > > ```swift -> let myInt: Int? = row["int_A"] ?? row["int_B"] // BAD - doesn't work -> let myInt: Int? = row.coalesce(["int_A", "int_B"]) // GOOD +> let name: String? = row["nickname"] ?? row["name"] // BAD - doesn't work +> let name: String? = row.coalesce(["nickname", "name"]) // GOOD > ``` Generally speaking, you can extract the type you need, provided it can be converted from the underlying SQLite value: From f38619ada8d5af4eab7572cdbae1ac73e6596db4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Oct 2024 12:19:41 +0200 Subject: [PATCH 06/15] Restore alphabetical order of SQL functions --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e682103ad..ab9e29495 100644 --- a/README.md +++ b/README.md @@ -3943,9 +3943,9 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli GRDB comes with a Swift version of many SQLite [built-in functions](https://sqlite.org/lang_corefunc.html), listed below. But not all: see [Embedding SQL in Query Interface Requests] for a way to add support for missing SQL functions. -- `ABS`, `AVG`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`, `TOTAL`, `COALESCE`: +- `ABS`, `AVG`, `COALESCE`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`, `TOTAL`: - Those are based on the `abs`, `average`, `count`, `dateTime`, `julianDay`, `length`, `max`, `min`, `sum`, `total`, and `coalesce` Swift functions: + Those are based on the `abs`, `average`, `coalesce`, `count`, `dateTime`, `julianDay`, `length`, `max`, `min`, `sum`, and `total` Swift functions: ```swift // SELECT MIN(score), MAX(score) FROM player From 06c3ab0d16e5be76b676f24b06a673656d877487 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Oct 2024 12:37:33 +0200 Subject: [PATCH 07/15] Test Row.coalesce on all variants of Row --- .../RowCopiedFromStatementTests.swift | 23 +++++++++++++++++++ .../RowFromDictionaryLiteralTests.swift | 19 +++++++++++++++ Tests/GRDBTests/RowFromDictionaryTests.swift | 19 +++++++++++++++ Tests/GRDBTests/RowFromStatementTests.swift | 23 +++++++++++++++++++ Tests/GRDBTests/SimpleFunctionTests.swift | 20 ---------------- 5 files changed, 84 insertions(+), 20 deletions(-) diff --git a/Tests/GRDBTests/RowCopiedFromStatementTests.swift b/Tests/GRDBTests/RowCopiedFromStatementTests.swift index 8bc077c5b..725618d64 100644 --- a/Tests/GRDBTests/RowCopiedFromStatementTests.swift +++ b/Tests/GRDBTests/RowCopiedFromStatementTests.swift @@ -287,4 +287,27 @@ class RowCopiedFromStatementTests: RowTestCase { XCTAssertEqual(row.debugDescription, "[null:NULL int:1 double:1.1 string:\"foo\" data:Data(6 bytes)]") } } + + func testCoalesce() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let values = try Row + .fetchAll(db, sql: """ + SELECT 'Artie' AS nickname, 'Arthur' AS name + UNION ALL SELECT NULL, 'Jacob' + UNION ALL SELECT NULL, NULL + """) + .map { row in + [ + row.coalesce(["nickname", "name"]) as String?, + row.coalesce([Column("nickname"), Column("name")]) as String?, + ] + } + XCTAssertEqual(values, [ + ["Artie", "Artie"], + ["Jacob", "Jacob"], + [nil, nil], + ]) + } + } } diff --git a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift index f840c437a..aabc43231 100644 --- a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift @@ -232,4 +232,23 @@ class RowFromDictionaryLiteralTests : RowTestCase { XCTAssertEqual(row.description, "[a:0 b:1 c:2]") XCTAssertEqual(row.debugDescription, "[a:0 b:1 c:2]") } + + func testCoalesce() throws { + let rows: [Row] = [ + ["nickname": "Artie", "name": "Arthur"], + ["nickname": nil, "name": "Jacob"], + ["nickname": nil, "name": nil], + ] + let values = rows.map { row in + [ + row.coalesce(["nickname", "name"]) as String?, + row.coalesce([Column("nickname"), Column("name")]) as String?, + ] + } + XCTAssertEqual(values, [ + ["Artie", "Artie"], + ["Jacob", "Jacob"], + [nil, nil], + ]) + } } diff --git a/Tests/GRDBTests/RowFromDictionaryTests.swift b/Tests/GRDBTests/RowFromDictionaryTests.swift index 08ddca00f..c429bbd21 100644 --- a/Tests/GRDBTests/RowFromDictionaryTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryTests.swift @@ -224,4 +224,23 @@ class RowFromDictionaryTests : RowTestCase { let debugVariants: Set = ["[a:0 b:\"foo\"]", "[b:\"foo\" a:0]"] XCTAssert(debugVariants.contains(row.debugDescription)) } + + func testCoalesce() throws { + let rows = [ + Row(["nickname": "Artie", "name": "Arthur"]), + Row(["nickname": nil, "name": "Jacob"]), + Row(["nickname": nil, "name": nil]), + ] + let values = rows.map { row in + [ + row.coalesce(["nickname", "name"]) as String?, + row.coalesce([Column("nickname"), Column("name")]) as String?, + ] + } + XCTAssertEqual(values, [ + ["Artie", "Artie"], + ["Jacob", "Jacob"], + [nil, nil], + ]) + } } diff --git a/Tests/GRDBTests/RowFromStatementTests.swift b/Tests/GRDBTests/RowFromStatementTests.swift index c42624a2b..62cc45529 100644 --- a/Tests/GRDBTests/RowFromStatementTests.swift +++ b/Tests/GRDBTests/RowFromStatementTests.swift @@ -380,4 +380,27 @@ class RowFromStatementTests : RowTestCase { XCTAssertTrue(rowFetched) } } + + func testCoalesce() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let values = try Array(Row + .fetchCursor(db, sql: """ + SELECT 'Artie' AS nickname, 'Arthur' AS name + UNION ALL SELECT NULL, 'Jacob' + UNION ALL SELECT NULL, NULL + """) + .map { row in + [ + row.coalesce(["nickname", "name"]) as String?, + row.coalesce([Column("nickname"), Column("name")]) as String?, + ] + }) + XCTAssertEqual(values, [ + ["Artie", "Artie"], + ["Jacob", "Jacob"], + [nil, nil], + ]) + } + } } diff --git a/Tests/GRDBTests/SimpleFunctionTests.swift b/Tests/GRDBTests/SimpleFunctionTests.swift index d9ccb1224..a0133f3f1 100644 --- a/Tests/GRDBTests/SimpleFunctionTests.swift +++ b/Tests/GRDBTests/SimpleFunctionTests.swift @@ -44,24 +44,4 @@ class SimpleFunctionTests: GRDBTestCase { } } } - - func testRowCoalesce() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let request = Player.all() - let rows = try Row.fetchAll(db, request) - var row = rows[0] - XCTAssertEqual(row.coalesce(["nickname", "name"]), "Artie") - XCTAssertEqual(row.coalesce([Column("nickname"), Column("name")]), "Artie") - row = rows[1] - XCTAssertEqual(row.coalesce(["nickname", "name"]), "Jacob") - XCTAssertEqual(row.coalesce([Column("nickname"), Column("name")]), "Jacob") - row = rows[2] - var result: String? = row.coalesce(["nickname", "name"]) - XCTAssertNil(result) - result = row.coalesce([Column("nickname"), Column("name")]) - XCTAssertNil(result) - } - } - } From ac3278a38b9ba0d451a77ee2a3c22faf29b8d24d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Oct 2024 12:42:00 +0200 Subject: [PATCH 08/15] Test top-level function coalesce like other top-level functions --- .../QueryInterfaceExpressionsTests.swift | 8 ++++ Tests/GRDBTests/SimpleFunctionTests.swift | 47 ------------------- 2 files changed, 8 insertions(+), 47 deletions(-) delete mode 100644 Tests/GRDBTests/SimpleFunctionTests.swift diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index a4248160f..896ecf4f1 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -1535,6 +1535,14 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT CAST(\"name\" AS BLOB) FROM \"readers\"") } + func testCoalesceExpression() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.select(coalesce([Col.name, Col.age]))), + "SELECT COALESCE(\"name\", \"age\") FROM \"readers\"") + } + func testLengthExpression() throws { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/GRDBTests/SimpleFunctionTests.swift b/Tests/GRDBTests/SimpleFunctionTests.swift deleted file mode 100644 index a0133f3f1..000000000 --- a/Tests/GRDBTests/SimpleFunctionTests.swift +++ /dev/null @@ -1,47 +0,0 @@ -import XCTest -import GRDB - -private struct Player: Codable, FetchableRecord, PersistableRecord { - var id: Int64 - var name: String? - var nickname: String? - var score: Int -} - -class SimpleFunctionTests: GRDBTestCase { - - override func setup(_ dbWriter: some DatabaseWriter) throws { - try dbWriter.write { db in - try db.create(table: "player") { t in - t.primaryKey("id", .integer) - t.column("name", .text) - t.column("nickname", .text) - t.column("score", .integer) - } - - try Player(id: 1, name: "Arthur", nickname: "Artie", score: 100).insert(db) - try Player(id: 2, name: "Jacob", nickname: nil, score: 200).insert(db) - try Player(id: 3, name: nil, nickname: nil, score: 200).insert(db) - } - } - - func testCoalesce() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.read { db in - do { - let request = Player.annotated(with: coalesce([Column("nickname"), Column("name")])) - try assertEqualSQL(db, request, """ - SELECT *, COALESCE("nickname", "name") \ - FROM "player" - """) - } - do { - let request = Player.annotated(with: coalesce([Column("nickname"), Column("name")]).forKey("foo")) - try assertEqualSQL(db, request, """ - SELECT *, COALESCE("nickname", "name") AS "foo" \ - FROM "player" - """) - } - } - } -} From 761b00f9bcaaab43a6e7a386f4239fc62aefe39e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Oct 2024 12:45:38 +0200 Subject: [PATCH 09/15] Test Row.coalesce with collections of size zero and one. --- Tests/GRDBTests/RowCopiedFromStatementTests.swift | 8 +++++--- Tests/GRDBTests/RowFromDictionaryLiteralTests.swift | 8 +++++--- Tests/GRDBTests/RowFromDictionaryTests.swift | 8 +++++--- Tests/GRDBTests/RowFromStatementTests.swift | 8 +++++--- 4 files changed, 20 insertions(+), 12 deletions(-) diff --git a/Tests/GRDBTests/RowCopiedFromStatementTests.swift b/Tests/GRDBTests/RowCopiedFromStatementTests.swift index 725618d64..e672d67d5 100644 --- a/Tests/GRDBTests/RowCopiedFromStatementTests.swift +++ b/Tests/GRDBTests/RowCopiedFromStatementTests.swift @@ -299,14 +299,16 @@ class RowCopiedFromStatementTests: RowTestCase { """) .map { row in [ + row.coalesce(Array()) as String?, + row.coalesce(["nickname"]) as String?, row.coalesce(["nickname", "name"]) as String?, row.coalesce([Column("nickname"), Column("name")]) as String?, ] } XCTAssertEqual(values, [ - ["Artie", "Artie"], - ["Jacob", "Jacob"], - [nil, nil], + [nil, "Artie", "Artie", "Artie"], + [nil, nil, "Jacob", "Jacob"], + [nil, nil, nil, nil], ]) } } diff --git a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift index aabc43231..2554e6e20 100644 --- a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift @@ -241,14 +241,16 @@ class RowFromDictionaryLiteralTests : RowTestCase { ] let values = rows.map { row in [ + row.coalesce(Array()) as String?, + row.coalesce(["nickname"]) as String?, row.coalesce(["nickname", "name"]) as String?, row.coalesce([Column("nickname"), Column("name")]) as String?, ] } XCTAssertEqual(values, [ - ["Artie", "Artie"], - ["Jacob", "Jacob"], - [nil, nil], + [nil, "Artie", "Artie", "Artie"], + [nil, nil, "Jacob", "Jacob"], + [nil, nil, nil, nil], ]) } } diff --git a/Tests/GRDBTests/RowFromDictionaryTests.swift b/Tests/GRDBTests/RowFromDictionaryTests.swift index c429bbd21..5625295e4 100644 --- a/Tests/GRDBTests/RowFromDictionaryTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryTests.swift @@ -233,14 +233,16 @@ class RowFromDictionaryTests : RowTestCase { ] let values = rows.map { row in [ + row.coalesce(Array()) as String?, + row.coalesce(["nickname"]) as String?, row.coalesce(["nickname", "name"]) as String?, row.coalesce([Column("nickname"), Column("name")]) as String?, ] } XCTAssertEqual(values, [ - ["Artie", "Artie"], - ["Jacob", "Jacob"], - [nil, nil], + [nil, "Artie", "Artie", "Artie"], + [nil, nil, "Jacob", "Jacob"], + [nil, nil, nil, nil], ]) } } diff --git a/Tests/GRDBTests/RowFromStatementTests.swift b/Tests/GRDBTests/RowFromStatementTests.swift index 62cc45529..85f17ff24 100644 --- a/Tests/GRDBTests/RowFromStatementTests.swift +++ b/Tests/GRDBTests/RowFromStatementTests.swift @@ -392,14 +392,16 @@ class RowFromStatementTests : RowTestCase { """) .map { row in [ + row.coalesce(Array()) as String?, + row.coalesce(["nickname"]) as String?, row.coalesce(["nickname", "name"]) as String?, row.coalesce([Column("nickname"), Column("name")]) as String?, ] }) XCTAssertEqual(values, [ - ["Artie", "Artie"], - ["Jacob", "Jacob"], - [nil, nil], + [nil, "Artie", "Artie", "Artie"], + [nil, nil, "Jacob", "Jacob"], + [nil, nil, nil, nil], ]) } } From a17d72e04cddbdfecc9e88238c1b0d126c869216 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Oct 2024 12:53:22 +0200 Subject: [PATCH 10/15] Make the top-level coalesce function work with collections of size zero and one. --- GRDB/QueryInterface/SQL/SQLFunctions.swift | 16 +++++++++++++++- .../QueryInterfaceExpressionsTests.swift | 8 ++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index dde4a4e16..8f3ccfea4 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -79,8 +79,22 @@ public func cast(_ expression: some SQLSpecificExpressible, as storageClass: Dat /// // COALESCE(value1, value2, ...) /// coalesce([Column("value1"), Column("value2"), ...]) /// ``` +/// +/// Unlike the SQL function, `coalesce` accepts any number of arguments. +/// When `values` is empty, the result is `NULL`. When `values` contains a +/// single value, the result is this value. `COALESCE` is used from +/// two values upwards. public func coalesce(_ values: some Collection) -> SQLExpression { - .function("COALESCE", values.map { $0.sqlExpression }) + // SQLite COALESCE wants at least two arguments. + // There is no reason to apply the same limitation. + guard let value = values.first else { + return .null + } + if values.count > 1 { + return .function("COALESCE", values.map { $0.sqlExpression }) + } else { + return value.sqlExpression + } } /// The `COUNT` SQL function. diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 896ecf4f1..f2a6d4b59 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -1538,6 +1538,14 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { func testCoalesceExpression() throws { let dbQueue = try makeDatabaseQueue() + XCTAssertEqual( + sql(dbQueue, tableRequest.select(coalesce([]))), + "SELECT NULL FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select(coalesce([Col.name]))), + "SELECT \"name\" FROM \"readers\"") + XCTAssertEqual( sql(dbQueue, tableRequest.select(coalesce([Col.name, Col.age]))), "SELECT COALESCE(\"name\", \"age\") FROM \"readers\"") From dd14710c866cf5ca313cbb5f9d7716c3a5c7a7a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 5 Oct 2024 12:06:04 +0200 Subject: [PATCH 11/15] Fix typo --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6dd540058..79589891c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -135,7 +135,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: Released September 29, 2024 -- **Fix** Update .spi.yml by [@finestructure](https://github.com/finestructure) in [#1643](https://github.com/groue/GRDB.swift/pull/1643) +- **Fix**: Update .spi.yml by [@finestructure](https://github.com/finestructure) in [#1643](https://github.com/groue/GRDB.swift/pull/1643) ## 7.0.0-beta From 8c5396898a715ce22dce1d69b4b3dc7bd3def204 Mon Sep 17 00:00:00 2001 From: Rob Amos Date: Sun, 6 Oct 2024 23:18:13 +1100 Subject: [PATCH 12/15] Add `DatabaseValueConvertible` tip --- GRDB/Documentation.docc/JSON.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/GRDB/Documentation.docc/JSON.md b/GRDB/Documentation.docc/JSON.md index ad4acad30..d0e02abec 100644 --- a/GRDB/Documentation.docc/JSON.md +++ b/GRDB/Documentation.docc/JSON.md @@ -98,6 +98,18 @@ extension Team: FetchableRecord, PersistableRecord { } ``` +> Tip: Conform your `Codable` property to `DatabaseValueConvertible` if you want to be able to filter on specific values of it: +> +> ```swift +> extension Address: DatabaseValueConvertible {} +> +> // SELECT * FROM player +> // WHERE "address" = '{"street": "...", "city": "...", "country": "..."}' +> let players = try Player +> .filter(JSONColumn("address") == Address(...)) +> .fetchAll(db) +> ``` + ## Manipulate JSON values at the database level [SQLite JSON functions and operators](https://www.sqlite.org/json1.html) are available starting iOS 16+, macOS 10.15+, tvOS 17+, and watchOS 9+. From a9fa2871aaf45b5aa5aa3df4427d883c37aa138f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Oct 2024 18:19:11 +0200 Subject: [PATCH 13/15] Document the requirements --- GRDB/Documentation.docc/JSON.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/GRDB/Documentation.docc/JSON.md b/GRDB/Documentation.docc/JSON.md index d0e02abec..5e3dcd6b8 100644 --- a/GRDB/Documentation.docc/JSON.md +++ b/GRDB/Documentation.docc/JSON.md @@ -101,14 +101,17 @@ extension Team: FetchableRecord, PersistableRecord { > Tip: Conform your `Codable` property to `DatabaseValueConvertible` if you want to be able to filter on specific values of it: > > ```swift +> struct Address: Codable { ... } > extension Address: DatabaseValueConvertible {} > > // SELECT * FROM player -> // WHERE "address" = '{"street": "...", "city": "...", "country": "..."}' +> // WHERE address = '{"street": "...", "city": "...", "country": "..."}' > let players = try Player > .filter(JSONColumn("address") == Address(...)) > .fetchAll(db) > ``` +> +> Take care that SQLite will compare strings, not JSON objects: white-space and key ordering matter. For this comparison to succeed, make sure that the database contains values that are formatted exactly like a serialized `Address`. ## Manipulate JSON values at the database level From 68d12916e641d3f03e8118f510dbf36cb25dfce7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Oct 2024 14:42:49 +0200 Subject: [PATCH 14/15] Fix Swiftlint warning --- GRDB/Fixits.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index 1092b1164..174a5ce7e 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -1,4 +1,5 @@ // Fixits for changes introduced by GRDB 7.0.0 +// swiftlint:disable all extension Configuration { @available(*, unavailable, message: "The default transaction kind is now automatically managed.") @@ -15,3 +16,5 @@ extension DatabasePool { @available(*, unavailable, message: "concurrentRead has been removed. Use `asyncConcurrentRead` instead.") public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { preconditionFailure() } } + +// swiftlint:enable all From 5b4a86b5f79b772e01c62d648d2c01787e73762a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Oct 2024 18:42:03 +0200 Subject: [PATCH 15/15] 7.0.0-beta.3 --- CHANGELOG.md | 12 ++++++++++-- Documentation/GRDB7MigrationGuide.md | 8 ++++---- GRDB.swift.podspec | 2 +- README.md | 2 +- Support/Info.plist | 2 +- 5 files changed, 17 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79589891c..878a36eef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 7.x Releases -- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) +- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.0.0-beta.3](#700-beta3) #### 6.x Releases @@ -131,6 +131,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## 7.0.0-beta.3 + +Released October 6, 2024 + +- **Fix**: use #if directives to conditionally @preconcurrency import the Dispatch module to enable building the package on linux by [@tayloraswift](https://github.com/tayloraswift) in [#1644](https://github.com/groue/GRDB.swift/pull/1644) +- **New**: Add coalesce free function and Row method by [@philmitchell](https://github.com/philmitchell) in [#1645](https://github.com/groue/GRDB.swift/pull/1645) +- **Documentation Update**: Add `DatabaseValueConvertible` tip for JSON columns by [@bok-](https://github.com/bok-) in [#1649](https://github.com/groue/GRDB.swift/pull/1649) + ## 7.0.0-beta.2 Released September 29, 2024 @@ -145,7 +153,7 @@ Released September 29, 2024 [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) describes in detail how to bump the GRDB version in your application. -The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.2/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency. +The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.3/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency. The [demo app](Documentation/DemoApps/) was rewritten from scratch in a brand new Xcode 16 project. diff --git a/Documentation/GRDB7MigrationGuide.md b/Documentation/GRDB7MigrationGuide.md index 81eb576f7..a13d442f0 100644 --- a/Documentation/GRDB7MigrationGuide.md +++ b/Documentation/GRDB7MigrationGuide.md @@ -228,7 +228,7 @@ Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non - The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/grdb.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior. [Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide -[Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.2/documentation/grdb/databasesharing -[Transaction Kinds]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.2/documentation/grdb/transactions#Transaction-Kinds -[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.2/documentation/grdb/swiftconcurrency -[Record]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.2/documentation/grdb/record +[Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.3/documentation/grdb/databasesharing +[Transaction Kinds]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.3/documentation/grdb/transactions#Transaction-Kinds +[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.3/documentation/grdb/swiftconcurrency +[Record]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.3/documentation/grdb/record diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index e5fb0391e..a56a6a97a 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '7.0.0-beta.2' + s.version = '7.0.0-beta.3' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/README.md b/README.md index ab9e29495..b4cf20881 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ CI Status

-**Latest release**: September 29, 2024 • [version 7.0.0-beta.2](https://github.com/groue/GRDB.swift/tree/v7.0.0-beta.2) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) +**Latest release**: October 6, 2024 • [version 7.0.0-beta.3](https://github.com/groue/GRDB.swift/tree/v7.0.0-beta.3) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) **Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ • SQLite 3.20.0+ • Swift 6+ / Xcode 16+ diff --git a/Support/Info.plist b/Support/Info.plist index e1632ae7f..0f9a7872c 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 7.0.0-beta.2 + 7.0.0-beta.3 CFBundleSignature ???? CFBundleVersion