From 3f96a965b9c92e0c883e9e8f6e6521aebf1121c2 Mon Sep 17 00:00:00 2001 From: Jhonny Bill Mena Date: Sun, 10 Sep 2023 22:59:07 -0400 Subject: [PATCH 01/24] ADD - databaseJSONDecoder and databaseJSONEncoder methods ADD - optional jsonEncoder parameter to DatabaseValueEncoder ADD - docs around new JSON customization methods --- GRDB/Core/DatabaseValueConvertible.swift | 47 +++++++++++++++++++ .../DatabaseValueConvertible+Decodable.swift | 6 +-- .../DatabaseValueConvertible+Encodable.swift | 29 ++++++++---- .../Extension/DatabaseValueConvertible.md | 10 +++- 4 files changed, 78 insertions(+), 14 deletions(-) diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 769e5b364..66becd1a2 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -59,6 +59,18 @@ public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding { /// /// - returns: A decoded value, or, if decoding is impossible, nil. static func fromMissingColumn() -> Self? + + /// Returns the `JSONDecoder` that decodes the value for a given column. + /// + /// This method is dedicated to ``DatabaseValueConvertible`` types that also conform + /// to the standard `Decodable` protocol. + static func databaseJSONDecoder() -> JSONDecoder + + /// Returns the `JSONEncoder` that encodes the value for a given column. + /// + /// This method is dedicated to ``DatabaseValueConvertible`` types that also conform + /// to the standard `Encodable` protocol. + static func databaseJSONEncoder() -> JSONEncoder } extension DatabaseValueConvertible { @@ -75,6 +87,41 @@ extension DatabaseValueConvertible { public static func fromMissingColumn() -> Self? { nil // failure. } + + /// Returns the `JSONDecoder` that decodes the value. + /// + /// The default implementation returns a `JSONDecoder` with the + /// following properties: + /// + /// - `dataDecodingStrategy`: `.base64` + /// - `dateDecodingStrategy`: `.millisecondsSince1970` + /// - `nonConformingFloatDecodingStrategy`: `.throw` + public static func databaseJSONDecoder() -> JSONDecoder { + let decoder = JSONDecoder() + decoder.dataDecodingStrategy = .base64 + decoder.dateDecodingStrategy = .millisecondsSince1970 + decoder.nonConformingFloatDecodingStrategy = .throw + return decoder + } + + /// Returns the `JSONEncoder` that encodes the value. + /// + /// The default implementation returns a `JSONEncoder` with the + /// following properties: + /// + /// - `dataEncodingStrategy`: `.base64` + /// - `dateEncodingStrategy`: `.millisecondsSince1970` + /// - `nonConformingFloatEncodingStrategy`: `.throw` + /// - `outputFormatting`: `.sortedKeys` + public static func databaseJSONEncoder() -> JSONEncoder { + let encoder = JSONEncoder() + encoder.dataEncodingStrategy = .base64 + encoder.dateEncodingStrategy = .millisecondsSince1970 + encoder.nonConformingFloatEncodingStrategy = .throw + // guarantee some stability in order to ease value comparison + encoder.outputFormatting = .sortedKeys + return encoder + } } // MARK: - Conversions diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift index e8ec70b8f..9e680f66b 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift @@ -179,11 +179,7 @@ extension DatabaseValueConvertible where Self: Decodable { guard let data = Data.fromDatabaseValue(databaseValue) else { return nil } - let decoder = JSONDecoder() - decoder.dataDecodingStrategy = .base64 - decoder.dateDecodingStrategy = .millisecondsSince1970 - decoder.nonConformingFloatDecodingStrategy = .throw - return try? decoder.decode(Self.self, from: data) + return try? databaseJSONDecoder().decode(Self.self, from: data) } catch { return nil } diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift index f9f7127d8..5e82390be 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift @@ -49,9 +49,14 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer { private class DatabaseValueEncoder: Encoder { let encode: (DatabaseValue) -> Void + let jsonEncoder: JSONEncoder? var requiresJSON = false - init(encode: @escaping (DatabaseValue) -> Void) { + init( + jsonEncoder: JSONEncoder? = nil, + encode: @escaping (DatabaseValue) -> Void + ) { + self.jsonEncoder = jsonEncoder self.encode = encode } @@ -115,12 +120,16 @@ private class DatabaseValueEncoder: Encoder { throw JSONRequiredError() } } catch is JSONRequiredError { - let encoder = JSONEncoder() - encoder.dataEncodingStrategy = .base64 - encoder.dateEncodingStrategy = .millisecondsSince1970 - encoder.nonConformingFloatEncodingStrategy = .throw - // guarantee some stability in order to ease value comparison - encoder.outputFormatting = .sortedKeys + let defaultEncoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.dataEncodingStrategy = .base64 + encoder.dateEncodingStrategy = .millisecondsSince1970 + encoder.nonConformingFloatEncodingStrategy = .throw + // guarantee some stability in order to ease value comparison + encoder.outputFormatting = .sortedKeys + return encoder + }() + let encoder = jsonEncoder ?? defaultEncoder let jsonData = try encoder.encode(value) // Store JSON String in the database for easier debugging and @@ -138,7 +147,11 @@ private class DatabaseValueEncoder: Encoder { extension DatabaseValueConvertible where Self: Encodable { public var databaseValue: DatabaseValue { var dbValue: DatabaseValue! = nil - try! DatabaseValueEncoder(encode: { dbValue = $0 }).encode(self) + try! DatabaseValueEncoder( + jsonEncoder: Self.databaseJSONEncoder(), + encode: { dbValue = $0 } + ) + .encode(self) return dbValue } } diff --git a/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md b/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md index 61a864c34..e282e0b04 100644 --- a/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md +++ b/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md @@ -74,7 +74,15 @@ extension Color: DatabaseValueConvertible { } By default, such codable value types are encoded and decoded with the standard [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder) and [JSONDecoder](https://developer.apple.com/documentation/foundation/jsondecoder). `Data` values are handled with the `.base64` strategy, `Date` with the `.millisecondsSince1970` strategy, and non conforming floats with the `.throw` strategy. -To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements. +To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements, +or implement these two methods: + +```swift +protocol DatabaseValueConvertible { + static func databaseJSONDecoder() -> JSONDecoder + static func databaseJSONEncoder() -> JSONEncoder +} +``` ### Adding support for the Tagged library From eec476b9ba6cfad529a6fb0592b4d1be7b339aa4 Mon Sep 17 00:00:00 2001 From: Jhonny Bill Mena Date: Sun, 10 Sep 2023 23:45:15 -0400 Subject: [PATCH 02/24] ADD - unit tests for custom JSON Encoder and Decoder in DatabaseValueConvertible --- ...tabaseValueConvertibleDecodableTests.swift | 53 +++++++++++++++++++ ...tabaseValueConvertibleEncodableTests.swift | 35 ++++++++++++ 2 files changed, 88 insertions(+) diff --git a/Tests/GRDBTests/DatabaseValueConvertibleDecodableTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleDecodableTests.swift index 53c98a282..50d495259 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleDecodableTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleDecodableTests.swift @@ -326,4 +326,57 @@ class DatabaseValueConvertibleDecodableTests: GRDBTestCase { XCTAssertEqual(value, .foo) } } + + func testDatabaseValueConvertibleImplementationDerivedFromDecodableWithCustomJsonDecoder() throws { + struct Value: Decodable, DatabaseValueConvertible { + let duration: Double + + var databaseValue: DatabaseValue { + preconditionFailure("not tested") + } + + public static func databaseJSONDecoder() -> JSONDecoder { + let decoder = JSONDecoder() + decoder.dataDecodingStrategy = .base64 + decoder.dateDecodingStrategy = .millisecondsSince1970 + decoder.nonConformingFloatDecodingStrategy = .convertFromString( + positiveInfinity: "+InF", + negativeInfinity: "-InF", + nan: "NaN" + ) + return decoder + } + } + + do { + // Success from DatabaseValue + let value = Value.fromDatabaseValue(#"{ "duration": "+InF" }"#.databaseValue)! + XCTAssertEqual(value.duration, Double.infinity) + + let value2 = Value.fromDatabaseValue(#"{ "duration": "-InF" }"#.databaseValue)! + XCTAssertEqual(value2.duration, -Double.infinity) + + let value3 = Value.fromDatabaseValue(#"{ "duration": "NaN" }"#.databaseValue)! + XCTAssertTrue(value3.duration.isNaN) + } + do { + // Success from database + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let value = try Value.fetchOne(db, sql: #"SELECT '{ "duration": "+InF" }'"#)! + XCTAssertEqual(value.duration, Double.infinity) + + let value2 = try Value.fetchOne(db, sql: #"SELECT '{ "duration": "-InF" }'"#)! + XCTAssertEqual(value2.duration, -Double.infinity) + + let value3 = try Value.fetchOne(db, sql: #"SELECT '{ "duration": "NaN" }'"#)! + XCTAssertTrue(value3.duration.isNaN) + } + } + do { + // Failure from DatabaseValue + let value = Value.fromDatabaseValue("infinity".databaseValue) + XCTAssertNil(value) + } + } } diff --git a/Tests/GRDBTests/DatabaseValueConvertibleEncodableTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleEncodableTests.swift index 66b0b7550..00f44620f 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleEncodableTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleEncodableTests.swift @@ -304,4 +304,39 @@ extension DatabaseValueConvertibleEncodableTests { let encodedUUID = UUID.fromDatabaseValue(dbValue)! XCTAssertEqual(encodedUUID, value.uuid) } + + func testDatabaseValueConvertibleImplementationDerivedFromEncodableWithCustomJsonEncoder() throws { + struct Value: Encodable, DatabaseValueConvertible { + let duration: Double + + static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? { + preconditionFailure("not tested") + } + + public static func databaseJSONEncoder() -> JSONEncoder { + let encoder = JSONEncoder() + encoder.dataEncodingStrategy = .base64 + encoder.dateEncodingStrategy = .millisecondsSince1970 + encoder.nonConformingFloatEncodingStrategy = .convertToString( + positiveInfinity: "+InF", + negativeInfinity: "-InF", + nan: "NaN" + ) + // guarantee some stability in order to ease value comparison + encoder.outputFormatting = .sortedKeys + return encoder + } + } + + do { + let dbValue = Value(duration: .infinity).databaseValue + XCTAssertEqual(dbValue.storage.value as! String, #"{"duration":"+InF"}"#) + + let dbValue2 = Value(duration: -Double.infinity).databaseValue + XCTAssertEqual(dbValue2.storage.value as! String, #"{"duration":"-InF"}"#) + + let dbValue3 = Value(duration: .nan).databaseValue + XCTAssertEqual(dbValue3.storage.value as! String, #"{"duration":"NaN"}"#) + } + } } From e560993b44f304edea4f34deac8f714fc197146c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 11 Sep 2023 06:25:17 +0000 Subject: [PATCH 03/24] Bump actions/checkout from 3 to 4 Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/CI.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 443234b51..6a9f3ec80 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -77,7 +77,7 @@ jobs: destination: "OS=16.0,name=iPhone 14" name: "iOS" steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: ${{ matrix.name }} run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test SPM: @@ -103,7 +103,7 @@ jobs: runsOn: macOS-12 name: "Xcode 14.0.1" steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: ${{ matrix.name }} run: make test_SPM test_install_SPM SQLCipher3: @@ -123,7 +123,7 @@ jobs: runsOn: macOS-12 name: "Xcode 14.0.1" steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: ${{ matrix.name }} run: make test_framework_SQLCipher3Encrypted SQLCipher4: @@ -143,7 +143,7 @@ jobs: runsOn: macOS-12 name: "Xcode 14.0.1" steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: ${{ matrix.name }} run: make test_framework_SQLCipher4Encrypted CustomSQLite: @@ -163,7 +163,7 @@ jobs: runsOn: macOS-12 name: "Xcode 14.0.1" steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: ${{ matrix.name }} run: make test_framework_GRDBCustomSQLiteOSX XCFramework: @@ -183,7 +183,7 @@ jobs: runsOn: macOS-12 name: "Xcode 14.0.1" steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: ${{ matrix.name }} run: make test_universal_xcframework \ No newline at end of file From 1e995b659d9b688eb11dbce4d91eabf9f6a1c9e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 16 Sep 2023 14:03:26 +0200 Subject: [PATCH 04/24] Hard-wrap documentation comments --- CONTRIBUTING.md | 2 +- GRDB/Core/DatabaseValueConvertible.swift | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8175ac90f..eab1679cb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -61,7 +61,7 @@ How you can Contribute - Get familiar with the [Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/). - Spaces, not tabs. - Whitespace-only lines are not trimmed. - - Documentation comments are hard-wrapped at column 80 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 80). + - Documentation comments are hard-wrapped at column 76 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 76). - No Swiftlint warning after a build. diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 66becd1a2..8c0ab4594 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -62,14 +62,14 @@ public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding { /// Returns the `JSONDecoder` that decodes the value for a given column. /// - /// This method is dedicated to ``DatabaseValueConvertible`` types that also conform - /// to the standard `Decodable` protocol. + /// This method is dedicated to ``DatabaseValueConvertible`` types that + /// also conform to the standard `Decodable` protocol. static func databaseJSONDecoder() -> JSONDecoder /// Returns the `JSONEncoder` that encodes the value for a given column. /// - /// This method is dedicated to ``DatabaseValueConvertible`` types that also conform - /// to the standard `Encodable` protocol. + /// This method is dedicated to ``DatabaseValueConvertible`` types that + /// also conform to the standard `Encodable` protocol. static func databaseJSONEncoder() -> JSONEncoder } From 9188251780ac9293027cd3f2a7ce0f000ef854a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 16 Sep 2023 14:03:38 +0200 Subject: [PATCH 05/24] Add missing import required by SPM --- GRDB/Core/DatabaseValueConvertible.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 8c0ab4594..2e086e44b 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -1,3 +1,5 @@ +import Foundation + // Standard collections `Array`, `Set`, and `Dictionary` do not conform to // `DatabaseValueConvertible`, on purpose. // From 746f65a9793ec3bce16b440e9a642205b6881823 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 16 Sep 2023 14:04:49 +0200 Subject: [PATCH 06/24] JSON encoder is always user-provided Now all created JSONEncoder or JSONDecoder are user-controlled. --- .../DatabaseValueConvertible+Encodable.swift | 21 ++++++------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift index 5e82390be..7735a8fb6 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift @@ -2,6 +2,7 @@ import Foundation private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer { let encode: (DatabaseValue) -> Void + let jsonEncoder: JSONEncoder var codingPath: [any CodingKey] { [] } @@ -42,18 +43,18 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer { // This allows us to encode Date as String, for example. encode(dbValueConvertible.databaseValue) } else { - try DatabaseValueEncoder(encode: encode).encode(value) + try DatabaseValueEncoder(jsonEncoder: jsonEncoder, encode: encode).encode(value) } } } private class DatabaseValueEncoder: Encoder { let encode: (DatabaseValue) -> Void - let jsonEncoder: JSONEncoder? + let jsonEncoder: JSONEncoder var requiresJSON = false init( - jsonEncoder: JSONEncoder? = nil, + jsonEncoder: JSONEncoder, encode: @escaping (DatabaseValue) -> Void ) { self.jsonEncoder = jsonEncoder @@ -109,7 +110,7 @@ private class DatabaseValueEncoder: Encoder { /// - precondition: May not be called after a value has been encoded through /// a previous `self.singleValueContainer()` call. func singleValueContainer() -> SingleValueEncodingContainer { - DatabaseValueEncodingContainer(encode: encode) + DatabaseValueEncodingContainer(encode: encode, jsonEncoder: jsonEncoder) } func encode(_ value: T) throws { @@ -120,17 +121,7 @@ private class DatabaseValueEncoder: Encoder { throw JSONRequiredError() } } catch is JSONRequiredError { - let defaultEncoder: JSONEncoder = { - let encoder = JSONEncoder() - encoder.dataEncodingStrategy = .base64 - encoder.dateEncodingStrategy = .millisecondsSince1970 - encoder.nonConformingFloatEncodingStrategy = .throw - // guarantee some stability in order to ease value comparison - encoder.outputFormatting = .sortedKeys - return encoder - }() - let encoder = jsonEncoder ?? defaultEncoder - let jsonData = try encoder.encode(value) + let jsonData = try jsonEncoder.encode(value) // Store JSON String in the database for easier debugging and // database inspection. Thanks to SQLite weak typing, we won't From 7f6ab592507901ce0c28112763bc4a70eaeadfd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 16 Sep 2023 14:10:17 +0200 Subject: [PATCH 07/24] Markdown files are soft-wrapped --- GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md b/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md index e282e0b04..804b64579 100644 --- a/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md +++ b/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md @@ -74,8 +74,7 @@ extension Color: DatabaseValueConvertible { } By default, such codable value types are encoded and decoded with the standard [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder) and [JSONDecoder](https://developer.apple.com/documentation/foundation/jsondecoder). `Data` values are handled with the `.base64` strategy, `Date` with the `.millisecondsSince1970` strategy, and non conforming floats with the `.throw` strategy. -To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements, -or implement these two methods: +To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements, or implement these two methods: ```swift protocol DatabaseValueConvertible { From 7944979d56c20853ebcb6d1c1991219d27f88997 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 16 Sep 2023 14:14:20 +0200 Subject: [PATCH 08/24] Add new methods to DocC --- .../Documentation.docc/Extension/DatabaseValueConvertible.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md b/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md index 804b64579..97a52239a 100644 --- a/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md +++ b/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md @@ -151,6 +151,11 @@ This extra conformance is not required: only aim at the low-level C interface if - ``databaseValue-1ob9k`` +### Configuring the JSON format for the standard Decodable protocol + +- ``databaseJSONDecoder()-7zou9`` +- ``databaseJSONEncoder()-37sff`` + ### Fetching Values from Raw SQL - ``fetchCursor(_:sql:arguments:adapter:)-6elcz`` From 76dbcfe700f08ebf83e0c82fba2cf0dfdfeb48ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 16 Sep 2023 14:14:30 +0200 Subject: [PATCH 09/24] Fix documentation wording --- GRDB/Core/DatabaseValueConvertible.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 2e086e44b..47f54c5af 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -62,13 +62,13 @@ public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding { /// - returns: A decoded value, or, if decoding is impossible, nil. static func fromMissingColumn() -> Self? - /// Returns the `JSONDecoder` that decodes the value for a given column. + /// Returns the `JSONDecoder` that decodes the value. /// /// This method is dedicated to ``DatabaseValueConvertible`` types that /// also conform to the standard `Decodable` protocol. static func databaseJSONDecoder() -> JSONDecoder - /// Returns the `JSONEncoder` that encodes the value for a given column. + /// Returns the `JSONEncoder` that encodes the value. /// /// This method is dedicated to ``DatabaseValueConvertible`` types that /// also conform to the standard `Encodable` protocol. From 6706de01032ea0088e900119366d3fe750c232ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 16 Sep 2023 14:39:58 +0200 Subject: [PATCH 10/24] Workaround for https://github.com/CocoaPods/CocoaPods/issues/12012 --- Tests/CocoaPods/GRDBiOS-framework/Podfile | 17 +++++++++++++++++ Tests/CocoaPods/GRDBiOS-static/Podfile | 17 +++++++++++++++++ Tests/CocoaPods/SQLCipher3/Podfile | 17 +++++++++++++++++ Tests/CocoaPods/SQLCipher4/Podfile | 17 +++++++++++++++++ 4 files changed, 68 insertions(+) diff --git a/Tests/CocoaPods/GRDBiOS-framework/Podfile b/Tests/CocoaPods/GRDBiOS-framework/Podfile index 4225f7023..8a4c9e93a 100644 --- a/Tests/CocoaPods/GRDBiOS-framework/Podfile +++ b/Tests/CocoaPods/GRDBiOS-framework/Podfile @@ -12,4 +12,21 @@ post_install do |installer| config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1" end end + + # TODO: remove when https://github.com/CocoaPods/CocoaPods/pull/12009 is merged. + # https://github.com/CocoaPods/CocoaPods/issues/12012#issuecomment-1655191516 + installer.aggregate_targets.each do |target| + target.xcconfigs.each do |variant, xcconfig| + xcconfig_path = target.client_root + target.xcconfig_relative_path(variant) + IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR")) + end + end + installer.pods_project.targets.each do |target| + target.build_configurations.each do |config| + if config.base_configuration_reference.is_a? Xcodeproj::Project::Object::PBXFileReference + xcconfig_path = config.base_configuration_reference.real_path + IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR")) + end + end + end end diff --git a/Tests/CocoaPods/GRDBiOS-static/Podfile b/Tests/CocoaPods/GRDBiOS-static/Podfile index 58476053c..94614c25b 100644 --- a/Tests/CocoaPods/GRDBiOS-static/Podfile +++ b/Tests/CocoaPods/GRDBiOS-static/Podfile @@ -11,4 +11,21 @@ post_install do |installer| config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1" end end + + # TODO: remove when https://github.com/CocoaPods/CocoaPods/pull/12009 is merged. + # https://github.com/CocoaPods/CocoaPods/issues/12012#issuecomment-1655191516 + installer.aggregate_targets.each do |target| + target.xcconfigs.each do |variant, xcconfig| + xcconfig_path = target.client_root + target.xcconfig_relative_path(variant) + IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR")) + end + end + installer.pods_project.targets.each do |target| + target.build_configurations.each do |config| + if config.base_configuration_reference.is_a? Xcodeproj::Project::Object::PBXFileReference + xcconfig_path = config.base_configuration_reference.real_path + IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR")) + end + end + end end diff --git a/Tests/CocoaPods/SQLCipher3/Podfile b/Tests/CocoaPods/SQLCipher3/Podfile index 6d99439cf..fbe38136b 100644 --- a/Tests/CocoaPods/SQLCipher3/Podfile +++ b/Tests/CocoaPods/SQLCipher3/Podfile @@ -23,4 +23,21 @@ post_install do |installer| config.build_settings['GCC_OPTIMIZATION_LEVEL'] = '3' end end + + # TODO: remove when https://github.com/CocoaPods/CocoaPods/pull/12009 is merged. + # https://github.com/CocoaPods/CocoaPods/issues/12012#issuecomment-1655191516 + installer.aggregate_targets.each do |target| + target.xcconfigs.each do |variant, xcconfig| + xcconfig_path = target.client_root + target.xcconfig_relative_path(variant) + IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR")) + end + end + installer.pods_project.targets.each do |target| + target.build_configurations.each do |config| + if config.base_configuration_reference.is_a? Xcodeproj::Project::Object::PBXFileReference + xcconfig_path = config.base_configuration_reference.real_path + IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR")) + end + end + end end diff --git a/Tests/CocoaPods/SQLCipher4/Podfile b/Tests/CocoaPods/SQLCipher4/Podfile index 008d26d86..031d49b72 100644 --- a/Tests/CocoaPods/SQLCipher4/Podfile +++ b/Tests/CocoaPods/SQLCipher4/Podfile @@ -23,4 +23,21 @@ post_install do |installer| config.build_settings['GCC_OPTIMIZATION_LEVEL'] = '3' end end + + # TODO: remove when https://github.com/CocoaPods/CocoaPods/pull/12009 is merged. + # https://github.com/CocoaPods/CocoaPods/issues/12012#issuecomment-1655191516 + installer.aggregate_targets.each do |target| + target.xcconfigs.each do |variant, xcconfig| + xcconfig_path = target.client_root + target.xcconfig_relative_path(variant) + IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR")) + end + end + installer.pods_project.targets.each do |target| + target.build_configurations.each do |config| + if config.base_configuration_reference.is_a? Xcodeproj::Project::Object::PBXFileReference + xcconfig_path = config.base_configuration_reference.real_path + IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR")) + end + end + end end From 4abcbdf452f039876878ab8dc48edcbc74945b1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 16 Sep 2023 17:53:50 +0200 Subject: [PATCH 11/24] CHANGELOG --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 313cc3c94..97eaa1f72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,6 +116,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## Next Release + +- **New**: [#1429](https://github.com/groue/GRDB.swift/pull/1429) by [@JhonnyBillM](https://github.com/JhonnyBillM): Allow `DatabaseValueConvertible` types to customize their database JSON format + ## 6.18.0 Released September 1, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.17.0...v6.18.0) From b896923fd496013221b2e7da7f51a7ee3d8b2a34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Oct 2023 12:27:34 +0200 Subject: [PATCH 12/24] TODO GRDB7: remove painful optionals due to IGNORE --- GRDB/Record/MutablePersistableRecord+Insert.swift | 4 ++++ GRDB/Record/MutablePersistableRecord+Save.swift | 4 ++++ GRDB/Record/MutablePersistableRecord+Update.swift | 9 +++++++++ GRDB/Record/PersistableRecord+Insert.swift | 2 ++ GRDB/Record/PersistableRecord+Save.swift | 2 ++ 5 files changed, 21 insertions(+) diff --git a/GRDB/Record/MutablePersistableRecord+Insert.swift b/GRDB/Record/MutablePersistableRecord+Insert.swift index 6097d12f8..4b2b1e1d0 100644 --- a/GRDB/Record/MutablePersistableRecord+Insert.swift +++ b/GRDB/Record/MutablePersistableRecord+Insert.swift @@ -91,6 +91,7 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER + // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` statement, and returns a new record built /// from the inserted row. /// @@ -122,6 +123,7 @@ extension MutablePersistableRecord { return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self) } + // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` statement, and returns a new record built /// from the inserted row. /// @@ -264,6 +266,7 @@ extension MutablePersistableRecord { return success.returned } #else + // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` statement, and returns a new record built /// from the inserted row. /// @@ -296,6 +299,7 @@ extension MutablePersistableRecord { return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self) } + // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` statement, and returns a new record built /// from the inserted row. /// diff --git a/GRDB/Record/MutablePersistableRecord+Save.swift b/GRDB/Record/MutablePersistableRecord+Save.swift index 15faebc66..a9776cc82 100644 --- a/GRDB/Record/MutablePersistableRecord+Save.swift +++ b/GRDB/Record/MutablePersistableRecord+Save.swift @@ -87,6 +87,7 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER + // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and /// returns a new record built from the saved row. /// @@ -121,6 +122,7 @@ extension MutablePersistableRecord { return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self) } + // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and /// returns a new record built from the saved row. /// @@ -209,6 +211,7 @@ extension MutablePersistableRecord { return success.returned } #else + // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and /// returns a new record built from the saved row. /// @@ -244,6 +247,7 @@ extension MutablePersistableRecord { return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self) } + // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and /// returns a new record built from the saved row. /// diff --git a/GRDB/Record/MutablePersistableRecord+Update.swift b/GRDB/Record/MutablePersistableRecord+Update.swift index f6ee3c39f..691d77d8d 100644 --- a/GRDB/Record/MutablePersistableRecord+Update.swift +++ b/GRDB/Record/MutablePersistableRecord+Update.swift @@ -218,6 +218,7 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER + // TODO: GRDB7 make it unable to return an optional /// Executes an `UPDATE RETURNING` statement on all columns, and returns a /// new record built from the updated row. /// @@ -241,6 +242,7 @@ extension MutablePersistableRecord { try updateAndFetch(db, onConflict: conflictResolution, as: Self.self) } + // TODO: GRDB7 make it unable to return an optional /// Executes an `UPDATE RETURNING` statement on all columns, and returns a /// new record built from the updated row. /// @@ -267,6 +269,7 @@ extension MutablePersistableRecord { } } + // TODO: GRDB7 make it unable to return an optional /// Modifies the record according to the provided `modify` closure, and /// executes an `UPDATE RETURNING` statement that updates the modified /// columns, if and only if the record was modified. The method returns a @@ -294,6 +297,7 @@ extension MutablePersistableRecord { try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify) } + // TODO: GRDB7 make it unable to return an optional /// Modifies the record according to the provided `modify` closure, and /// executes an `UPDATE RETURNING` statement that updates the modified /// columns, if and only if the record was modified. The method returns a @@ -478,6 +482,7 @@ extension MutablePersistableRecord { fetch: fetch) } + // TODO: GRDB7 make it unable to return an optional /// Modifies the record according to the provided `modify` closure, and /// executes an `UPDATE RETURNING` statement that updates the modified /// columns, if and only if the record was modified. The method returns a @@ -514,6 +519,7 @@ extension MutablePersistableRecord { fetch: fetch) } #else + // TODO: GRDB7 make it unable to return an optional /// Executes an `UPDATE RETURNING` statement on all columns, and returns a /// new record built from the updated row. /// @@ -565,6 +571,7 @@ extension MutablePersistableRecord { } } + // TODO: GRDB7 make it unable to return an optional /// Modifies the record according to the provided `modify` closure, and /// executes an `UPDATE RETURNING` statement that updates the modified /// columns, if and only if the record was modified. The method returns a @@ -593,6 +600,7 @@ extension MutablePersistableRecord { try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify) } + // TODO: GRDB7 make it unable to return an optional /// Modifies the record according to the provided `modify` closure, and /// executes an `UPDATE RETURNING` statement that updates the modified /// columns, if and only if the record was modified. The method returns a @@ -781,6 +789,7 @@ extension MutablePersistableRecord { fetch: fetch) } + // TODO: GRDB7 make it unable to return an optional /// Modifies the record according to the provided `modify` closure, and /// executes an `UPDATE RETURNING` statement that updates the modified /// columns, if and only if the record was modified. The method returns a diff --git a/GRDB/Record/PersistableRecord+Insert.swift b/GRDB/Record/PersistableRecord+Insert.swift index 232c217d9..b44f3f432 100644 --- a/GRDB/Record/PersistableRecord+Insert.swift +++ b/GRDB/Record/PersistableRecord+Insert.swift @@ -56,6 +56,7 @@ extension PersistableRecord { extension PersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER + // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` statement, and returns a new record built /// from the inserted row. /// @@ -198,6 +199,7 @@ extension PersistableRecord { return success.returned } #else + // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` statement, and returns a new record built /// from the inserted row. /// diff --git a/GRDB/Record/PersistableRecord+Save.swift b/GRDB/Record/PersistableRecord+Save.swift index 4f713cdfb..9ba55346b 100644 --- a/GRDB/Record/PersistableRecord+Save.swift +++ b/GRDB/Record/PersistableRecord+Save.swift @@ -39,6 +39,7 @@ extension PersistableRecord { extension PersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER + // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and /// returns a new record built from the saved row. /// @@ -127,6 +128,7 @@ extension PersistableRecord { return success.returned } #else + // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and /// returns a new record built from the saved row. /// From 8cc52983b73738d29395df5fd8c184fadf1a0b8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Oct 2023 12:03:44 +0200 Subject: [PATCH 13/24] Introduce SQLFunctionFlags --- GRDB/Core/DatabaseFunction.swift | 28 +- .../Association/AssociationAggregate.swift | 10 +- GRDB/QueryInterface/SQL/SQLExpression.swift | 344 +++++++++++------- GRDB/QueryInterface/SQL/SQLFunctions.swift | 10 +- 4 files changed, 248 insertions(+), 144 deletions(-) diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index db3af3ef8..e74b22b73 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -30,9 +30,22 @@ public final class DatabaseFunction: Hashable { /// The name of the SQL function public var name: String { identity.name } private let identity: Identity - let pure: Bool + let isPure: Bool private let kind: Kind - private var eTextRep: CInt { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) } + private var eTextRep: CInt { (SQLITE_UTF8 | (isPure ? SQLITE_DETERMINISTIC : 0)) } + + var functionFlags: SQLFunctionFlags { + var flags = SQLFunctionFlags(isPure: isPure) + + switch kind { + case .function: + break + case .aggregate: + flags.isAggregate = true + } + + return flags + } /// Creates an SQL function. /// @@ -76,7 +89,7 @@ public final class DatabaseFunction: Hashable { function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?) { self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1) - self.pure = pure + self.isPure = pure self.kind = .function{ (argc, argv) in let arguments = (0.. SQLExpression { - switch kind { - case .aggregate: - return .function(name, arguments.map(\.sqlExpression)) - case .function: - return .aggregate(name, arguments.map(\.sqlExpression)) - } + .function(name, arguments.map(\.sqlExpression), flags: functionFlags) } /// Calls sqlite3_create_function_v2 diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 08b8af6f8..cb6ecbcc4 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -127,7 +127,7 @@ extension AssociationToMany { /// } /// ``` public func average(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression])) + let aggregate = makeAggregate(.function("AVG", [expression.sqlExpression])) if let column = expression as? any ColumnExpression { let name = key.singularizedName return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") @@ -174,7 +174,7 @@ extension AssociationToMany { /// } /// ``` public func max(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression])) + let aggregate = makeAggregate(.function("MAX", [expression.sqlExpression])) if let column = expression as? any ColumnExpression { let name = key.singularizedName return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") @@ -221,7 +221,7 @@ extension AssociationToMany { /// } /// ``` public func min(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression])) + let aggregate = makeAggregate(.function("MIN", [expression.sqlExpression])) if let column = expression as? any ColumnExpression { let name = key.singularizedName return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") @@ -271,7 +271,7 @@ extension AssociationToMany { /// } /// ``` public func sum(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression])) + let aggregate = makeAggregate(.function("SUM", [expression.sqlExpression])) if let column = expression as? any ColumnExpression { let name = key.singularizedName return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum") @@ -321,7 +321,7 @@ extension AssociationToMany { /// } /// ``` public func total(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.aggregate("TOTAL", [expression.sqlExpression])) + let aggregate = makeAggregate(.function("TOTAL", [expression.sqlExpression])) if let column = expression as? any ColumnExpression { let name = key.singularizedName // Yes we use the `Sum` suffix instead of `Total`. Both `total(_:)` diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index b781ccf4d..46660ef72 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -146,7 +146,7 @@ public struct SQLExpression { /// /// (, ...) /// (DISTINCT ) - case function(String, aggregate: Bool, distinct: Bool, arguments: [SQLExpression]) + case function(String, flags: SQLFunctionFlags, arguments: [SQLExpression]) /// An expression that checks for zero or positive values. /// @@ -178,6 +178,90 @@ public struct SQLExpression { /// - For views, it is true iff any column is not null. /// - For CTEs, it is not implemented yet. case qualifiedExists(TableAlias, isNegated: Bool) + + /// Returns a qualified expression + func qualified(with alias: TableAlias) -> Impl { + switch self { + case .databaseValue, + .qualifiedColumn, + .qualifiedFastPrimaryKey, + .qualifiedExists, + .subquery, + .exists: + return self + + case let .column(name): + return .qualifiedColumn(name, alias) + + case let .rowValue(expressions): + return .rowValue(expressions.map { $0.qualified(with: alias) }) + + case let .literal(sqlLiteral): + return .literal(sqlLiteral.qualified(with: alias)) + + case let .between( + expression: expression, + lowerBound: lowerBound, + upperBound: upperBound, + isNegated: isNegated): + + return .between( + expression: expression.qualified(with: alias), + lowerBound: lowerBound.qualified(with: alias), + upperBound: upperBound.qualified(with: alias), + isNegated: isNegated) + + case let .binary(op, lhs, rhs): + return .binary(op, lhs.qualified(with: alias), rhs.qualified(with: alias)) + + case let .escapableBinary(op, lhs, rhs, escape): + return .escapableBinary( + op, + lhs.qualified(with: alias), + rhs.qualified(with: alias), + escape: escape?.qualified(with: alias)) + + case let .associativeBinary(op, expressions): + return .associativeBinary(op, expressions.map { $0.qualified(with: alias) }) + + case let .in(expression, collection, isNegated: isNegated): + return .in( + expression.qualified(with: alias), + collection.qualified(with: alias), + isNegated: isNegated + ) + + case let .unary(op, expression): + return .unary(op, expression.qualified(with: alias)) + + case let .compare(op, lhs, rhs): + return .compare(op, lhs.qualified(with: alias), rhs.qualified(with: alias)) + + case let .tableMatch(a, expression): + return .tableMatch(a, expression.qualified(with: alias)) + + case let .not(expression): + return .not(expression.qualified(with: alias)) + + case let .collated(expression, collationName): + return .collated(expression.qualified(with: alias), collationName) + + case .countAll: + return .countAll + + case let .function(name, flags: flags, arguments: arguments): + return .function( + name, + flags: flags, + arguments: arguments.map { $0.qualified(with: alias) }) + + case let .isEmpty(expression, isNegated: isNegated): + return .isEmpty(expression.qualified(with: alias), isNegated: isNegated) + + case .fastPrimaryKey: + return .qualifiedFastPrimaryKey(alias) + } + } } /// `BooleanTest` supports truthiness tests. @@ -763,41 +847,31 @@ extension SQLExpression { /// /// COUNT() static func count(_ expression: SQLExpression) -> Self { - aggregate("COUNT", [expression]) + function("COUNT", [expression]) } /// The `COUNT(DISTINCT)` function. /// /// COUNT(DISTINCT ) static func countDistinct(_ expression: SQLExpression) -> Self { - distinctAggregate("COUNT", expression) + function("COUNT", [expression], flags: .init(isAggregate: true, isDistinct: true)) } /// A function call. /// /// (, ...) - /// - /// - warning: for aggregate functions, call one of: - /// - `SQLExpression.aggregate(_:_:)`, - /// - `SQLExpression.distinctAggregate(_:_:)`, - /// - `SQLExpression.countDistinct(_:)` - /// - `SQLExpression.countAll`. static func function(_ name: String, _ arguments: [SQLExpression]) -> Self { - self.init(impl: .function(name, aggregate: false, distinct: false, arguments: arguments)) + .init(impl: .function( + name, + flags: .defaultFlags(for: name, argumentCount: arguments.count), + arguments: arguments)) } - /// An aggregate function call. + /// A function call with explicit flags. /// - /// (, ...) - static func aggregate(_ name: String, _ arguments: [SQLExpression]) -> Self { - self.init(impl: .function(name, aggregate: true, distinct: false, arguments: arguments)) - } - - /// A distinct aggregate function call. - /// - /// (DISTINCT ) - static func distinctAggregate(_ name: String, _ argument: SQLExpression) -> Self { - self.init(impl: .function(name, aggregate: true, distinct: true, arguments: [argument])) + /// (, ...) + static func function(_ name: String, _ arguments: [SQLExpression], flags: SQLFunctionFlags) -> Self { + .init(impl: .function(name, flags: flags, arguments: arguments)) } /// An expression that checks for zero or positive values. @@ -843,6 +917,17 @@ extension SQLExpression { } } +// MARK: - Deriving Expressions + +extension SQLExpression { + /// Returns a qualified expression + func qualified(with alias: TableAlias) -> Self { + .init(impl: impl.qualified(with: alias)) + } +} + +// MARK: - Expressions Information + extension SQLExpression { /// The expression as a quoted SQL literal (not public in order to avoid abuses) /// @@ -906,7 +991,7 @@ extension SQLExpression { case let .collated(expression, _): return try expression.column(db, for: alias, acceptsBijection: acceptsBijection) - case let .function(name, aggregate: false, distinct: false, arguments: arguments): + case let .function(name, flags: flags, arguments: arguments) where !flags.isAggregate: guard acceptsBijection else { return nil } @@ -1101,11 +1186,11 @@ extension SQLExpression { case .countAll: return "COUNT(*)" - case let .function(name, aggregate: aggregate, distinct: distinct, arguments: arguments): - assert(!distinct || aggregate, "distinct requires aggregate") - assert(!distinct || arguments.count == 1, "distinct requires a single argument") + case let .function(name, flags: flags, arguments: arguments): + assert(!flags.isDistinct || flags.isAggregate, "distinct requires aggregate") + assert(!flags.isDistinct || arguments.count == 1, "distinct requires a single argument") return try name - + (distinct ? "(DISTINCT " : "(") + + (flags.isDistinct ? "(DISTINCT " : "(") + arguments.map { try $0.sql(context) }.joined(separator: ", ") + ")" @@ -1516,17 +1601,6 @@ extension SQLExpression { } } - private static let knownPureFunctions = [ - "ABS", "CHAR", "COALESCE", "GLOB", "HEX", "IFNULL", - "IIF", "INSTR", "LENGTH", "LIKE", "LIKELIHOOD", - "LIKELY", "LOAD_EXTENSION", "LOWER", "LTRIM", - "NULLIF", "PRINTF", "QUOTE", "REPLACE", "ROUND", - "RTRIM", "SOUNDEX", "SQLITE_COMPILEOPTION_GET", - "SQLITE_COMPILEOPTION_USED", "SQLITE_SOURCE_ID", - "SQLITE_VERSION", "SUBSTR", "TRIM", "TRIM", - "TYPEOF", "UNICODE", "UNLIKELY", "UPPER", "ZEROBLOB", - ] - /// Returns true if the expression has a unique value when SQLite runs /// a request. /// @@ -1567,13 +1641,8 @@ extension SQLExpression { let .collated(expression, _): return expression.isConstantInRequest - case let .function(name, aggregate: false, distinct: false, arguments: arguments): - let name = name.uppercased() - guard ((name == "MAX" || name == "MIN") && arguments.count > 1) - || Self.knownPureFunctions.contains(name) - else { - return false // Don't know - assume not constant - } + case let .function(_, flags: flags, arguments: arguments) + where flags.isPure && !flags.isAggregate: return arguments.allSatisfy(\.isConstantInRequest) @@ -1582,84 +1651,6 @@ extension SQLExpression { } } - /// Returns a qualified expression - func qualified(with alias: TableAlias) -> SQLExpression { - switch impl { - case .databaseValue, - .qualifiedColumn, - .qualifiedFastPrimaryKey, - .qualifiedExists, - .subquery, - .exists: - return self - - case let .column(name): - return .qualifiedColumn(name, alias) - - case let .rowValue(expressions): - assert(!expressions.isEmpty) - return .rowValue(expressions.map { $0.qualified(with: alias) })! - - case let .literal(sqlLiteral): - return .literal(sqlLiteral.qualified(with: alias)) - - case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: isNegated): - return .between( - expression: expression.qualified(with: alias), - lowerBound: lowerBound.qualified(with: alias), - upperBound: upperBound.qualified(with: alias), - isNegated: isNegated) - - case let .binary(op, lhs, rhs): - return .binary(op, lhs.qualified(with: alias), rhs.qualified(with: alias)) - - case let .escapableBinary(op, lhs, rhs, escape): - return .escapableBinary( - op, - lhs.qualified(with: alias), - rhs.qualified(with: alias), - escape: escape?.qualified(with: alias)) - - case let .associativeBinary(op, expressions): - return .associativeBinary(op, expressions.map { $0.qualified(with: alias) }) - - case let .in(expression, collection, isNegated: isNegated): - return .in( - expression.qualified(with: alias), - collection.qualified(with: alias), - isNegated: isNegated - ) - - case let .unary(op, expression): - return .unary(op, expression.qualified(with: alias)) - - case let .compare(op, lhs, rhs): - return .compare(op, lhs.qualified(with: alias), rhs.qualified(with: alias)) - - case let .tableMatch(a, expression): - return .tableMatch(a, expression.qualified(with: alias)) - - case let .not(expression): - return .not(expression.qualified(with: alias)) - - case let .collated(expression, collationName): - return .collated(expression.qualified(with: alias), collationName) - - case .countAll: - return .countAll - - case let .function(name, aggregate: aggregate, distinct: distinct, arguments: arguments): - return SQLExpression(impl: .function(name, aggregate: aggregate, distinct: distinct, - arguments: arguments.map { $0.qualified(with: alias) })) - - case let .isEmpty(expression, isNegated: isNegated): - return .isEmpty(expression.qualified(with: alias), isNegated: isNegated) - - case .fastPrimaryKey: - return .qualifiedFastPrimaryKey(alias) - } - } - /// Returns true if the expression is an aggregate. /// /// When in doubt, returns false. @@ -1709,8 +1700,10 @@ extension SQLExpression { return false - case .countAll, - .function(_, aggregate: true, distinct: _, arguments: _): + case .countAll: + return true + + case let .function(_, flags: flags, arguments: _) where flags.isAggregate: return true default: @@ -1719,6 +1712,109 @@ extension SQLExpression { } } +// MARK: - Function Flags + +/// Information about a function +struct SQLFunctionFlags { + /// A boolean value indicating if a function is known to be pure. + /// + /// A false value does not provide any information. + var isPure = false + + /// A boolean value indicating if a function is known to be + /// an aggregate. + /// + /// A false value does not provide any information. + var isAggregate = false + + /// A boolean value indicating if the function should have `DISTINCT` + /// in its SQL generation (as in `COUNT(DISTINCT ...)`). + var isDistinct = false +} + +extension SQLFunctionFlags { + // TODO: add missing pure functions: + // https://www.sqlite.org/lang_aggfunc.html + // https://www.sqlite.org/lang_datefunc.html + // https://www.sqlite.org/lang_mathfunc.html + private static let knownPureFunctions: Set = [ + "ABS", + "CHAR", + "COALESCE", + "GLOB", + "HEX", + "IFNULL", + "IIF", + "INSTR", + "JSON", + "JSON_ARRAY", + "JSON_GROUP_ARRAY", + "JSON_GROUP_OBJECT", + "JSON_INSERT", + "JSON_OBJECT", + "JSON_PATCH", + "JSON_REMOVE", + "JSON_REPLACE", + "JSON_SET", + "JSON_QUOTE", + "LENGTH", + "LIKE", + "LIKELIHOOD", + "LIKELY", + "LOAD_EXTENSION", + "LOWER", + "LTRIM", + "NULLIF", + "PRINTF", + "QUOTE", + "REPLACE", + "ROUND", + "RTRIM", + "SOUNDEX", + "SQLITE_COMPILEOPTION_GET", + "SQLITE_COMPILEOPTION_USED", + "SQLITE_SOURCE_ID", + "SQLITE_VERSION", + "SUBSTR", + "TRIM", + "TYPEOF", + "UNICODE", + "UNLIKELY", + "UPPER", + "ZEROBLOB", + ] + + private static let knownAggregateFunctions: Set = [ + "AVG", + "COUNT", + "GROUP_CONCAT", + "JSON_GROUP_ARRAY", + "JSON_GROUP_OBJECT", + "MAX", // when single argument + "MIN", // when single argument + "SUM", + "TOTAL", + ] + + /// Infers flags from the function name and number of arguments. + static func defaultFlags(for functionName: String, argumentCount: Int) -> Self { + var flags = SQLFunctionFlags() + + let name = functionName.uppercased() + + flags.isPure = Self.knownPureFunctions.contains(name) + + if (name == "MAX" || name == "MIN") && argumentCount > 1 { + flags.isPure = true + } else { + flags.isAggregate = Self.knownAggregateFunctions.contains(name.uppercased()) + } + + return flags + } +} + + // MARK: - SQLExpressible /// A type that can be used as an SQL expression. diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 9d1796a2d..a1eb3c0f2 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -19,7 +19,7 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression { /// average(Column("length")) /// ``` public func average(_ value: some SQLSpecificExpressible) -> SQLExpression { - .aggregate("AVG", [value.sqlExpression]) + .function("AVG", [value.sqlExpression]) } /// The `COUNT` SQL function. @@ -81,7 +81,7 @@ public func length(_ value: some SQLSpecificExpressible) -> SQLExpression { /// max(Column("score")) /// ``` public func max(_ value: some SQLSpecificExpressible) -> SQLExpression { - .aggregate("MAX", [value.sqlExpression]) + .function("MAX", [value.sqlExpression]) } /// The `MIN` SQL function. @@ -93,7 +93,7 @@ public func max(_ value: some SQLSpecificExpressible) -> SQLExpression { /// min(Column("score")) /// ``` public func min(_ value: some SQLSpecificExpressible) -> SQLExpression { - .aggregate("MIN", [value.sqlExpression]) + .function("MIN", [value.sqlExpression]) } /// The `SUM` SQL function. @@ -109,7 +109,7 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression { /// /// Related SQLite documentation: . public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression { - .aggregate("SUM", [value.sqlExpression]) + .function("SUM", [value.sqlExpression]) } /// The `TOTAL` SQL function. @@ -125,7 +125,7 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression { /// /// Related SQLite documentation: . public func total(_ value: some SQLSpecificExpressible) -> SQLExpression { - .aggregate("TOTAL", [value.sqlExpression]) + .function("TOTAL", [value.sqlExpression]) } // MARK: - String functions From 718102f743f5f68277836e3861281dd52986dfb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 4 Sep 2023 20:11:12 +0200 Subject: [PATCH 14/24] Create indexes on expressions --- CHANGELOG.md | 1 + GRDB/Documentation.docc/DatabaseSchema.md | 1 + .../SQLGeneration/SQLIndexGenerator.swift | 34 +++++---- .../SQLGeneration/SQLTableGenerator.swift | 4 +- .../Schema/ColumnDefinition.swift | 2 +- .../Schema/Database+SchemaDefinition.swift | 75 +++++++++++++++---- .../Schema/IndexDefinition.swift | 2 +- Tests/GRDBTests/TableDefinitionTests.swift | 11 ++- 8 files changed, 93 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 97eaa1f72..474cae004 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -119,6 +119,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release - **New**: [#1429](https://github.com/groue/GRDB.swift/pull/1429) by [@JhonnyBillM](https://github.com/JhonnyBillM): Allow `DatabaseValueConvertible` types to customize their database JSON format +- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method. ## 6.18.0 diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index ce908d8ce..5e466a204 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -385,6 +385,7 @@ extension Team: TableRecord { - ``Database/create(indexOn:columns:options:condition:)`` - ``Database/create(index:on:columns:options:condition:)`` +- ``Database/create(index:on:expressions:options:condition:)`` - ``Database/drop(indexOn:columns:)`` - ``Database/drop(index:)`` - ``IndexOptions`` diff --git a/GRDB/QueryInterface/SQLGeneration/SQLIndexGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLIndexGenerator.swift index 35d3662ff..81e63a3de 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLIndexGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLIndexGenerator.swift @@ -1,31 +1,33 @@ struct SQLIndexGenerator { let name: String let table: String - let columns: [String] + let expressions: [SQLExpression] let options: IndexOptions let condition: SQLExpression? func sql(_ db: Database) throws -> String { - var chunks: [String] = [] - chunks.append("CREATE") + var sql: SQL = "CREATE" + if options.contains(.unique) { - chunks.append("UNIQUE") + sql += " UNIQUE" } - chunks.append("INDEX") + + sql += " INDEX" + if options.contains(.ifNotExists) { - chunks.append("IF NOT EXISTS") + sql += " IF NOT EXISTS" } - chunks.append(name.quotedDatabaseIdentifier) - chunks.append("ON") - chunks.append(""" - \(table.quotedDatabaseIdentifier)(\ - \(columns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\ - ) - """) + + sql += " \(identifier: name) ON \(identifier: table)(" + sql += expressions.map { SQL($0) }.joined(separator: ", ") + sql += ")" + if let condition { - try chunks.append("WHERE \(condition.quotedSQL(db))") + sql += " WHERE \(condition)" } - return chunks.joined(separator: " ") + + let context = SQLGenerationContext(db, argumentsSink: .literalValues) + return try sql.sql(context) } } @@ -33,7 +35,7 @@ extension SQLIndexGenerator { init(index: IndexDefinition) { name = index.name table = index.table - columns = index.columns + expressions = index.expressions options = index.options condition = index.condition } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLTableGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLTableGenerator.swift index 69cd9de15..740b74dcc 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLTableGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLTableGenerator.swift @@ -406,14 +406,14 @@ extension SQLTableGenerator { indexGenerator = SQLIndexGenerator( name: Database.defaultIndexName(on: originTable, columns: columnNames), table: originTable, - columns: columnNames, + expressions: columnNames.map { .column($0) }, options: indexOptions, condition: nil) case .unique: indexGenerator = SQLIndexGenerator( name: Database.defaultIndexName(on: originTable, columns: columnNames), table: originTable, - columns: columnNames, + expressions: columnNames.map { .column($0) }, options: indexOptions.union([.unique]), condition: nil) } diff --git a/GRDB/QueryInterface/Schema/ColumnDefinition.swift b/GRDB/QueryInterface/Schema/ColumnDefinition.swift index 9ca39370d..08b611945 100644 --- a/GRDB/QueryInterface/Schema/ColumnDefinition.swift +++ b/GRDB/QueryInterface/Schema/ColumnDefinition.swift @@ -559,7 +559,7 @@ public final class ColumnDefinition { return IndexDefinition( name: "\(table)_on_\(name)", table: table, - columns: [name], + expressions: [.column(name)], options: options, condition: nil) } diff --git a/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift b/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift index b8f14ccf0..eb62d7e88 100644 --- a/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift +++ b/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift @@ -433,7 +433,7 @@ extension Database { try execute(sql: "DROP VIEW \(name.quotedDatabaseIdentifier)") } - /// Creates an index. + /// Creates an index on the specified table and columns. /// /// For example: /// @@ -443,12 +443,8 @@ extension Database { /// ``` /// /// SQLite can also index expressions () - /// and use specific collations. To create such an index, use a raw SQL - /// query: - /// - /// ```swift - /// try db.execute(sql: "CREATE INDEX ...") - /// ``` + /// and use specific collations. To create such an index, use + /// ``create(index:on:expressions:options:condition:)``. /// /// Related SQLite documentation: /// @@ -481,7 +477,7 @@ extension Database { try create(index: name, on: table, columns: columns, options: options, condition: condition) } - /// Creates an index. + /// Creates an index on the specified table and columns. /// /// For example: /// @@ -526,7 +522,7 @@ extension Database { let index = IndexDefinition( name: name, table: table, - columns: columns, + expressions: columns.map { .column($0) }, options: options, condition: condition?.sqlExpression) let generator = SQLIndexGenerator(index: index) @@ -534,7 +530,58 @@ extension Database { try execute(sql: sql) } - /// Creates an index on the specified table and columns. + /// Creates an index on the specified table and expressions. + /// + /// This method can generally create indexes on expressions (see + /// ): + /// + /// ```swift + /// // CREATE INDEX txy ON t(x+y) + /// try db.create( + /// index: "txy", + /// on: "t", + /// expressions: [Column("x") + Column("y")]) + /// ``` + /// + /// In particular, you can specify the collation on indexed + /// columns (see ): + /// + /// ```swift + /// // CREATE INDEX index_player_name ON player(name COLLATE NOCASE) + /// try db.create( + /// index: "index_player_name", + /// on: "player", + /// expressions: [Column("name").collating(.nocase)]) + /// ``` + /// + /// - parameters: + /// - name: The index name. + /// - table: The name of the indexed table. + /// - expressions: The indexed expressions. + /// - options: Index creation options. + /// - condition: If not nil, creates a partial index + /// (see ). + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public func create( + index name: String, + on table: String, + expressions: [any SQLExpressible], + options: IndexOptions = [], + condition: (any SQLExpressible)? = nil) + throws + { + let index = IndexDefinition( + name: name, + table: table, + expressions: expressions.map { $0.sqlExpression }, + options: options, + condition: condition?.sqlExpression) + let generator = SQLIndexGenerator(index: index) + let sql = try generator.sql(self) + try execute(sql: sql) + } + + /// Creates an index with a default name on the specified table and columns. /// /// The created index is named after the table and the column name(s): /// @@ -554,12 +601,8 @@ extension Database { /// ``create(index:on:columns:options:condition:)`` instead. /// /// SQLite can also index expressions () - /// and use specific collations. To create such an index, use a raw SQL - /// query: - /// - /// ```swift - /// try db.execute(sql: "CREATE INDEX ...") - /// ``` + /// and use specific collations. To create such an index, use + /// ``create(index:on:expressions:options:condition:)``. /// /// Related SQLite documentation: /// diff --git a/GRDB/QueryInterface/Schema/IndexDefinition.swift b/GRDB/QueryInterface/Schema/IndexDefinition.swift index 5ac47c766..616d8d886 100644 --- a/GRDB/QueryInterface/Schema/IndexDefinition.swift +++ b/GRDB/QueryInterface/Schema/IndexDefinition.swift @@ -1,7 +1,7 @@ struct IndexDefinition { let name: String let table: String - let columns: [String] + let expressions: [SQLExpression] let options: IndexOptions let condition: SQLExpression? } diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index cad002a0b..0092b26d7 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -961,8 +961,14 @@ class TableDefinitionTests: GRDBTestCase { try db.create(index: "test_on_a_b_2", on: "test", columns: ["a", "b"], options: [.unique, .ifNotExists]) assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b_2\" ON \"test\"(\"a\", \"b\")") + try db.create(index: "test_on_a_plus_b", on: "test", expressions: [Column("a") + Column("b")], options: [.unique, .ifNotExists]) + assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_plus_b\" ON \"test\"(\"a\" + \"b\")") + + try db.create(index: "test_on_a_nocase", on: "test", expressions: [Column("a").collating(.nocase)], options: [.unique, .ifNotExists]) + assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_nocase\" ON \"test\"(\"a\" COLLATE NOCASE)") + // Sanity check - XCTAssertEqual(try Set(db.indexes(on: "test").map(\.name)), ["test_on_a", "test_on_a_b", "test_on_a_b_2"]) + XCTAssertEqual(try Set(db.indexes(on: "test").map(\.name)), ["test_on_a", "test_on_a_b", "test_on_a_b_2", "test_on_a_nocase"]) } } @@ -1001,6 +1007,9 @@ class TableDefinitionTests: GRDBTestCase { try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], options: [.unique, .ifNotExists], condition: Column("a") == 1) assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\") WHERE \"a\" = 1") + try db.create(index: "test_on_a_plus_b", on: "test", expressions: [Column("a") + Column("b")], options: [.unique, .ifNotExists], condition: Column("a") == 1) + assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_plus_b\" ON \"test\"(\"a\" + \"b\") WHERE \"a\" = 1") + // Sanity check XCTAssertEqual(try Set(db.indexes(on: "test").map(\.name)), ["test_on_a_b"]) } From 97e6f88b31754154dca44a3ebc0d0e74b591c678 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Oct 2023 09:37:14 +0200 Subject: [PATCH 15/24] Add new .jsonText column type --- GRDB/Core/Database.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 86ef1b8fa..532054b08 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1826,6 +1826,14 @@ extension Database { /// The `TEXT` column type. public static let text = ColumnType(rawValue: "TEXT") + /// The `TEXT` column type, suitable for JSON columns. + /// + /// SQLite JSON functions and operators are + /// [documented](https://www.sqlite.org/json1.html#interface_overview) + /// to throw errors if any of their arguments are binary blobs. + /// That's the reason why it is recommended to store JSON as text. + public static let jsonText = ColumnType(rawValue: "TEXT") + /// The `INTEGER` column type. public static let integer = ColumnType(rawValue: "INTEGER") From ed01d40ba9bebec62edd3896197a9f5d586e3a40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Oct 2023 12:19:44 +0200 Subject: [PATCH 16/24] JSON functions --- GRDB.xcodeproj/project.pbxproj | 12 + GRDB/JSON/SQLJSONFunctions.swift | 777 ++++++++++++++++++++ GRDB/QueryInterface/SQL/SQLExpression.swift | 189 ++++- GRDBCustom.xcodeproj/project.pbxproj | 12 + 4 files changed, 986 insertions(+), 4 deletions(-) create mode 100644 GRDB/JSON/SQLJSONFunctions.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 78de977bb..5bc34fa75 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -13,6 +13,7 @@ 56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; }; 560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; }; 560233C92724338800529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C82724338800529DF3 /* SharedValueObservationTests.swift */; }; + 5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */; }; 560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; }; 560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; }; 5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; }; @@ -418,6 +419,7 @@ 56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; 560233C32724234F00529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = ""; }; 560233C82724338800529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = ""; }; + 5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONFunctions.swift; sourceTree = ""; }; 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = ""; }; 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; @@ -842,6 +844,14 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 5603CEB52AC862EC00CF097D /* JSON */ = { + isa = PBXGroup; + children = ( + 5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */, + ); + path = JSON; + sourceTree = ""; + }; 5605F1471C672E4000235C62 /* Support */ = { isa = PBXGroup; children = ( @@ -1644,6 +1654,7 @@ 566DDE0C288D763C0000DCFB /* Fixits.swift */, 56A2386F1B9C75030082EB20 /* Core */, 5698AC291D9E5A480056AF8C /* FTS */, + 5603CEB52AC862EC00CF097D /* JSON */, 56A238911B9C750B0082EB20 /* Migration */, 56300B6D1C53F592005A543B /* QueryInterface */, 56A2389F1B9C753B0082EB20 /* Record */, @@ -2184,6 +2195,7 @@ 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, 56E9FADA221053DD00C703A8 /* SQL.swift in Sources */, + 5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */, 56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */, 563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */, C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */, diff --git a/GRDB/JSON/SQLJSONFunctions.swift b/GRDB/JSON/SQLJSONFunctions.swift new file mode 100644 index 000000000..0f172876f --- /dev/null +++ b/GRDB/JSON/SQLJSONFunctions.swift @@ -0,0 +1,777 @@ +#if GRDBCUSTOMSQLITE || GRDBCIPHER +extension Database { + /// Validates and minifies a JSON string, with the `JSON` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON(' { "a": [ "test" ] } ') → '{"a":["test"]}' + /// Database.json(#" { "a": [ "test" ] } "#) + /// ``` + /// + /// Related SQLite documentation: + public static func json(_ value: some SQLExpressible) -> SQLExpression { + .function("JSON", [value.sqlExpression]) + } + + /// Creates a JSON array with the `JSON_ARRAY` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_ARRAY(1, 2, 3, 4) → '[1,2,3,4]' + /// Database.jsonArray(1...4) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonArray(_ values: C) -> SQLExpression + where C: Collection, C.Element: SQLExpressible + { + .function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression)) + } + + /// Creates a JSON array with the `JSON_ARRAY` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_ARRAY(1, 2, '3', 4) → '[1,2,"3",4]' + /// Database.jsonArray([1, 2, "3", 4]) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonArray(_ values: C) -> SQLExpression + where C: Collection, C.Element == any SQLExpressible + { + .function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression)) + } + + /// The number of elements in a JSON array, as returned by the + /// `JSON_ARRAY_LENGTH` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_ARRAY_LENGTH('[1,2,3,4]') → 4 + /// Database.jsonArrayLength("[1,2,3,4]") + /// ``` + /// + /// Related SQLite documentation: + public static func jsonArrayLength(_ value: some SQLExpressible) -> SQLExpression { + .function("JSON_ARRAY_LENGTH", [value.sqlExpression]) + } + + /// The number of elements in a JSON array, as returned by the + /// `JSON_ARRAY_LENGTH` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_ARRAY_LENGTH('{"one":[1,2,3]}', '$.one') → 3 + /// Database.jsonArrayLength(#"{"one":[1,2,3]}"#, atPath: "$.one") + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON array. + /// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonArrayLength( + _ value: some SQLExpressible, + atPath path: some SQLExpressible) + -> SQLExpression + { + .function("JSON_ARRAY_LENGTH", [value.sqlExpression, path.sqlExpression]) + } + + /// The `JSON_ERROR_POSITION` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_ERROR_POSITION(info) + /// Database.jsonErrorPosition(Column("info")) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonErrorPosition(_ value: some SQLExpressible) -> SQLExpression { + .function("JSON_ERROR_POSITION", [value.sqlExpression]) + } + + /// The `JSON_EXTRACT` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_EXTRACT('{"a":123}', '$.a') → 123 + /// Database.jsonExtract(#"{"a":123}"#, atPath: "$.a") + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression { + .function("JSON_EXTRACT", [value.sqlExpression, path.sqlExpression]) + } + + /// The `JSON_EXTRACT` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_EXTRACT('{"a":2,"c":[4,5]}','$.c','$.a') → '[[4,5],2]' + /// Database.jsonExtract(#"{"a":2,"c":[4,5]}"#, atPaths: ["$.c", "$.a"]) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonExtract(_ value: some SQLExpressible, atPaths paths: C) + -> SQLExpression + where C: Collection, C.Element: SQLExpressible + { + .function("JSON_EXTRACT", [value.sqlExpression] + paths.map(\.sqlExpression)) + } + + /// The `JSON_INSERT` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_INSERT('[1,2,3,4]','$[#]',99) → '[1,2,3,4,99]' + /// Database.jsonInsert("[1,2,3,4]", ["$[#]": value: 99]) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - assignments: A collection of key/value pairs, where keys are + /// [JSON paths](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonInsert( + _ value: some SQLExpressible, + _ assignments: C) + -> SQLExpression + where C: Collection, + C.Element == (key: String, value: any SQLExpressible) + { + .function("JSON_INSERT", [value.sqlExpression] + assignments.flatMap { + [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] + }) + } + + /// The `JSON_REPLACE` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_REPLACE('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}' + /// Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": 99]) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - assignments: A collection of key/value pairs, where keys are + /// [JSON paths](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonReplace( + _ value: some SQLExpressible, + _ assignments: C) + -> SQLExpression + where C: Collection, + C.Element == (key: String, value: any SQLExpressible) + { + .function("JSON_REPLACE", [value.sqlExpression] + assignments.flatMap { + [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] + }) + } + + /// The `JSON_SET` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_SET('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}' + /// Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": 99]]) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - assignments: A collection of key/value pairs, where keys are + /// [JSON paths](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonSet( + _ value: some SQLExpressible, + _ assignments: C) + -> SQLExpression + where C: Collection, + C.Element == (key: String, value: any SQLExpressible) + { + .function("JSON_SET", [value.sqlExpression] + assignments.flatMap { + [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] + }) + } + + /// Creates a JSON object with the `JSON_OBJECT` SQL function. Pass + /// key/value pairs with a Swift collection such as a `Dictionary`. + /// + /// For example: + /// + /// ```swift + /// // JSON_OBJECT('c', '{"e":5}') → '{"c":"{\"e\":5}"}' + /// Database.jsonObject([ + /// "c": #"{"e":5}"#, + /// ]) + /// + /// // JSON_OBJECT('c', JSON_OBJECT('e', 5)) → '{"c":{"e":5}}' + /// Database.jsonObject([ + /// "c": Database.jsonObject(["e": 5])), + /// ]) + /// + /// // JSON_OBJECT('c', JSON('{"e":5}')) → '{"c":{"e":5}}' + /// Database.jsonObject([ + /// "c": Database.json(#"{"e":5}"#), + /// ]) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonObject(_ elements: C) + -> SQLExpression + where C: Collection, + C.Element == (key: String, value: any SQLExpressible) + { + .function("JSON_OBJECT", elements.flatMap { + [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] + }) + } + + /// The `JSON_PATCH` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_PATCH('{"a":1,"b":2}','{"c":3,"d":4}') → '{"a":1,"b":2,"c":3,"d":4}' + /// Database.jsonPatch(#"{"a":1,"b":2}"#, #"{"c":3,"d":4}"#) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonPatch( + _ value: some SQLExpressible, + with patch: some SQLExpressible) + -> SQLExpression + { + .function("JSON_PATCH", [value.sqlExpression, patch.sqlExpression]) + } + + /// The `JSON_REMOVE` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_REMOVE('[0,1,2,3,4]', '$[2]') → '[0,1,3,4]' + /// Database.jsonRemove("[0,1,2,3,4]", atPath: "$[2]") + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression { + .function("JSON_REMOVE", [value.sqlExpression, path.sqlExpression]) + } + + /// The `JSON_REMOVE` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_REMOVE('[0,1,2,3,4]', '$[2]','$[0]') → '[1,3,4]' + /// Database.jsonRemove("[0,1,2,3,4]", atPaths: ["$[2]", "$[0]"]) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonRemove(_ value: some SQLExpressible, atPaths paths: C) + -> SQLExpression + where C: Collection, C.Element: SQLExpressible + { + .function("JSON_REMOVE", [value.sqlExpression] + paths.map(\.sqlExpression)) + } + + /// The `JSON_TYPE` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}') → 'object' + /// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonType(_ value: some SQLExpressible) -> SQLExpression { + .function("JSON_TYPE", [value.sqlExpression]) + } + + /// The `JSON_TYPE` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}', '$.a') → 'object' + /// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#, atPath: "$.a") + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonType(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression { + .function("JSON_TYPE", [value.sqlExpression, path.sqlExpression]) + } + + /// The `JSON_VALID` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_VALID('{"x":35') → 0 + /// Database.jsonIsValid(#"{"x":35"#) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression { + .function("JSON_VALID", [value.sqlExpression]) + } + + /// The `JSON_QUOTE` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_QUOTE('[1]') → '"[1]"' + /// Database.jsonQuote("[1]") + /// + /// // JSON_QUOTE(JSON('[1]')) → '[1]' + /// Database.jsonQuote(Database.json("[1]")) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonQuote(_ value: some SQLExpressible) -> SQLExpression { + .function("JSON_QUOTE", [value.sqlExpression.jsonBuilderExpression]) + } + + /// The `JSON_GROUP_ARRAY` SQL function. + /// + /// Related SQLite documentation: + public static func jsonGroupArray(_ value: some SQLExpressible) -> SQLExpression { + .function("JSON_GROUP_ARRAY", [value.sqlExpression.jsonBuilderExpression]) + } + + /// The `JSON_GROUP_OBJECT` SQL function. + /// + /// Related SQLite documentation: + public static func jsonGroupObject(key: some SQLExpressible, value: some SQLExpressible) -> SQLExpression { + .function("JSON_GROUP_OBJECT", [key.sqlExpression, value.sqlExpression.jsonBuilderExpression]) + } +} +#else +@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+ +extension Database { + /// Validates and minifies a JSON string, with the `JSON` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON(' { "a": [ "test" ] } ') → '{"a":["test"]}' + /// Database.json(#" { "a": [ "test" ] } "#) + /// ``` + /// + /// Related SQLite documentation: + public static func json(_ value: some SQLExpressible) -> SQLExpression { + .function("JSON", [value.sqlExpression]) + } + + /// Creates a JSON array with the `JSON_ARRAY` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_ARRAY(1, 2, 3, 4) → '[1,2,3,4]' + /// Database.jsonArray(1...4) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonArray(_ values: C) -> SQLExpression + where C: Collection, C.Element: SQLExpressible + { + .function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression)) + } + + /// Creates a JSON array with the `JSON_ARRAY` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_ARRAY(1, 2, '3', 4) → '[1,2,"3",4]' + /// Database.jsonArray([1, 2, "3", 4]) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonArray(_ values: C) -> SQLExpression + where C: Collection, C.Element == any SQLExpressible + { + .function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression)) + } + + /// The number of elements in a JSON array, as returned by the + /// `JSON_ARRAY_LENGTH` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_ARRAY_LENGTH('[1,2,3,4]') → 4 + /// Database.jsonArrayLength("[1,2,3,4]") + /// ``` + /// + /// Related SQLite documentation: + public static func jsonArrayLength(_ value: some SQLExpressible) -> SQLExpression { + .function("JSON_ARRAY_LENGTH", [value.sqlExpression]) + } + + /// The number of elements in a JSON array, as returned by the + /// `JSON_ARRAY_LENGTH` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_ARRAY_LENGTH('{"one":[1,2,3]}', '$.one') → 3 + /// Database.jsonArrayLength(#"{"one":[1,2,3]}"#, atPath: "$.one") + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON array. + /// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonArrayLength( + _ value: some SQLExpressible, + atPath path: some SQLExpressible) + -> SQLExpression + { + .function("JSON_ARRAY_LENGTH", [value.sqlExpression, path.sqlExpression]) + } + + /// The `JSON_ERROR_POSITION` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_ERROR_POSITION(info) + /// Database.jsonErrorPosition(Column("info")) + /// ``` + /// + /// Related SQLite documentation: + @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) + public static func jsonErrorPosition(_ value: some SQLExpressible) -> SQLExpression { + .function("JSON_ERROR_POSITION", [value.sqlExpression]) + } + + /// The `JSON_EXTRACT` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_EXTRACT('{"a":123}', '$.a') → 123 + /// Database.jsonExtract(#"{"a":123}"#, atPath: "$.a") + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression { + .function("JSON_EXTRACT", [value.sqlExpression, path.sqlExpression]) + } + + /// The `JSON_EXTRACT` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_EXTRACT('{"a":2,"c":[4,5]}','$.c','$.a') → '[[4,5],2]' + /// Database.jsonExtract(#"{"a":2,"c":[4,5]}"#, atPaths: ["$.c", "$.a"]) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonExtract(_ value: some SQLExpressible, atPaths paths: C) + -> SQLExpression + where C: Collection, C.Element: SQLExpressible + { + .function("JSON_EXTRACT", [value.sqlExpression] + paths.map(\.sqlExpression)) + } + + /// The `JSON_INSERT` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_INSERT('[1,2,3,4]','$[#]',99) → '[1,2,3,4,99]' + /// Database.jsonInsert("[1,2,3,4]", ["$[#]": value: 99]) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - assignments: A collection of key/value pairs, where keys are + /// [JSON paths](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonInsert( + _ value: some SQLExpressible, + _ assignments: C) + -> SQLExpression + where C: Collection, + C.Element == (key: String, value: any SQLExpressible) + { + .function("JSON_INSERT", [value.sqlExpression] + assignments.flatMap { + [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] + }) + } + + /// The `JSON_REPLACE` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_REPLACE('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}' + /// Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": 99]) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - assignments: A collection of key/value pairs, where keys are + /// [JSON paths](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonReplace( + _ value: some SQLExpressible, + _ assignments: C) + -> SQLExpression + where C: Collection, + C.Element == (key: String, value: any SQLExpressible) + { + .function("JSON_REPLACE", [value.sqlExpression] + assignments.flatMap { + [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] + }) + } + + /// The `JSON_SET` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_SET('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}' + /// Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": 99]]) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - assignments: A collection of key/value pairs, where keys are + /// [JSON paths](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonSet( + _ value: some SQLExpressible, + _ assignments: C) + -> SQLExpression + where C: Collection, + C.Element == (key: String, value: any SQLExpressible) + { + .function("JSON_SET", [value.sqlExpression] + assignments.flatMap { + [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] + }) + } + + /// Creates a JSON object with the `JSON_OBJECT` SQL function. Pass + /// key/value pairs with a Swift collection such as a `Dictionary`. + /// + /// For example: + /// + /// ```swift + /// // JSON_OBJECT('c', '{"e":5}') → '{"c":"{\"e\":5}"}' + /// Database.jsonObject([ + /// "c": #"{"e":5}"#, + /// ]) + /// + /// // JSON_OBJECT('c', JSON_OBJECT('e', 5)) → '{"c":{"e":5}}' + /// Database.jsonObject([ + /// "c": Database.jsonObject(["e": 5])), + /// ]) + /// + /// // JSON_OBJECT('c', JSON('{"e":5}')) → '{"c":{"e":5}}' + /// Database.jsonObject([ + /// "c": Database.json(#"{"e":5}"#), + /// ]) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonObject(_ elements: C) + -> SQLExpression + where C: Collection, + C.Element == (key: String, value: any SQLExpressible) + { + .function("JSON_OBJECT", elements.flatMap { + [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] + }) + } + + /// The `JSON_PATCH` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_PATCH('{"a":1,"b":2}','{"c":3,"d":4}') → '{"a":1,"b":2,"c":3,"d":4}' + /// Database.jsonPatch(#"{"a":1,"b":2}"#, #"{"c":3,"d":4}"#) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonPatch( + _ value: some SQLExpressible, + with patch: some SQLExpressible) + -> SQLExpression + { + .function("JSON_PATCH", [value.sqlExpression, patch.sqlExpression]) + } + + /// The `JSON_REMOVE` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_REMOVE('[0,1,2,3,4]', '$[2]') → '[0,1,3,4]' + /// Database.jsonRemove("[0,1,2,3,4]", atPath: "$[2]") + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression { + .function("JSON_REMOVE", [value.sqlExpression, path.sqlExpression]) + } + + /// The `JSON_REMOVE` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_REMOVE('[0,1,2,3,4]', '$[2]','$[0]') → '[1,3,4]' + /// Database.jsonRemove("[0,1,2,3,4]", atPaths: ["$[2]", "$[0]"]) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonRemove(_ value: some SQLExpressible, atPaths paths: C) + -> SQLExpression + where C: Collection, C.Element: SQLExpressible + { + .function("JSON_REMOVE", [value.sqlExpression] + paths.map(\.sqlExpression)) + } + + /// The `JSON_TYPE` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}') → 'object' + /// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonType(_ value: some SQLExpressible) -> SQLExpression { + .function("JSON_TYPE", [value.sqlExpression]) + } + + /// The `JSON_TYPE` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}', '$.a') → 'object' + /// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#, atPath: "$.a") + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameters: + /// - value: A JSON value. + /// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). + public static func jsonType(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression { + .function("JSON_TYPE", [value.sqlExpression, path.sqlExpression]) + } + + /// The `JSON_VALID` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_VALID('{"x":35') → 0 + /// Database.jsonIsValid(#"{"x":35"#) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression { + .function("JSON_VALID", [value.sqlExpression]) + } + + /// Returns a valid JSON string with the `JSON_QUOTE` SQL function. + /// + /// For example: + /// + /// ```swift + /// // JSON_QUOTE('[1]') → '"[1]"' + /// Database.jsonQuote("[1]") + /// + /// // JSON_QUOTE(JSON('[1]')) → '[1]' + /// Database.jsonQuote(Database.json("[1]")) + /// ``` + /// + /// Related SQLite documentation: + public static func jsonQuote(_ value: some SQLExpressible) -> SQLExpression { + .function("JSON_QUOTE", [value.sqlExpression.jsonBuilderExpression]) + } + + /// The `JSON_GROUP_ARRAY` SQL function. + /// + /// Related SQLite documentation: + public static func jsonGroupArray(_ value: some SQLExpressible) -> SQLExpression { + .function("JSON_GROUP_ARRAY", [value.sqlExpression.jsonBuilderExpression]) + } + + /// The `JSON_GROUP_OBJECT` SQL function. + /// + /// Related SQLite documentation: + public static func jsonGroupObject(key: some SQLExpressible, value: some SQLExpressible) -> SQLExpression { + .function("JSON_GROUP_OBJECT", [key.sqlExpression, value.sqlExpression.jsonBuilderExpression]) + } +} +#endif diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 46660ef72..6545b6aad 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -37,6 +37,25 @@ public struct SQLExpression { private var impl: Impl + /// The preferred interpretation of the expression in JSON + /// building contexts (see `jsonBuilderExpression`). + /// + /// ```swift + /// // Considering: + /// // JSON_ARRAY('[1, 2, 3]') → '["[1, 2, 3]"]' + /// // JSON_ARRAY(JSON('[1, 2, 3]')) → [[1,2,3]] + /// + /// // Compare an expression with preferredJSONInterpretation = .unspecified: + /// // JSON_ARRAY("info") + /// Database.jsonArray([Column("info")]) + /// + /// // ...with an expression with preferredJSONInterpretation = .jsonValue: + /// // JSON_ARRAY(JSON("info")) + /// Database.jsonArray([Column("info").jsonValue]) + /// Database.jsonArray([JSONColumn("info")]) + /// ``` + var preferredJSONInterpretation = JSONInterpretation.deferredToSQLite + /// The private implementation of the public `SQLExpression`. private enum Impl { /// A column. @@ -428,11 +447,22 @@ public struct SQLExpression { /// The SQL operator let sql: String - /// Creates a binary operator + /// A boolean value indicating if the operator is known to return a + /// JSON value. /// - /// BinaryOperator("-") - init(_ sql: String) { + /// A false value does not provide any information. + let isJSONValue: Bool + + /// Creates a binary operator. + /// + /// For example: + /// + /// ``` + /// BinaryOperator("-") + /// ``` + init(_ sql: String, isJSONValue: Bool = false) { self.sql = sql + self.isJSONValue = isJSONValue } /// The `<` binary operator @@ -461,6 +491,14 @@ public struct SQLExpression { /// The `>>` bitwise right shift operator static let rightShift = BinaryOperator(">>") + + // Not guarded by availability checks, but only available for SQLite 3.38+ + /// The `->` SQL operator + static let jsonExtractJSON = BinaryOperator("->", isJSONValue: true) + + // Not guarded by availability checks, but only available for SQLite 3.38+ + /// The `->>` SQL operator + static let jsonExtractSQL = BinaryOperator("->>") } /// `EscapableBinaryOperator` is an SQLite binary operator that accepts an @@ -528,6 +566,36 @@ public struct SQLExpression { /// The `~` unary operator static let bitwiseNot = UnaryOperator("~") } + + /// Describes the interpretation of an expression in a JSON + /// building context. + enum JSONInterpretation { + /// JSON interpretation is deferred to SQLite: + /// + /// ```swift + /// // JSON_ARRAY('[1, 2, 3]') → '["[1, 2, 3]"]' + /// Database.jsonArray(["[1, 2, 3]"]) + /// + /// // JSON_ARRAY(JSON('[1, 2, 3]')) → '[[1, 2, 3]]' + /// Database.jsonArray([Database.json("[1, 2, 3]")]) + /// + /// // JSON_ARRAY("info") + /// Database.jsonArray([Column("info")]) + /// ``` + case deferredToSQLite + + /// Expression is interpreted as a JSON value: + /// + /// ```swift + /// // JSON_ARRAY(JSON('[1, 2, 3]')) → '[[1, 2, 3]]' + /// Database.jsonArray(["[1, 2, 3]"].jsonValue) + /// + /// // JSON_ARRAY(JSON("info")) + /// Database.jsonArray([Column("info").jsonValue]) + /// Database.jsonArray([JSONColumn("info")]) + /// ``` + case jsonValue + } } // MARK: - Creating Expressions @@ -922,7 +990,11 @@ extension SQLExpression { extension SQLExpression { /// Returns a qualified expression func qualified(with alias: TableAlias) -> Self { - .init(impl: impl.qualified(with: alias)) + .init(impl: impl.qualified(with: alias), preferredJSONInterpretation: preferredJSONInterpretation) + } + + func withPreferredJSONInterpretation(_ interpretation: JSONInterpretation) -> Self { + .init(impl: impl, preferredJSONInterpretation: interpretation) } } @@ -1730,6 +1802,12 @@ struct SQLFunctionFlags { /// A boolean value indicating if the function should have `DISTINCT` /// in its SQL generation (as in `COUNT(DISTINCT ...)`). var isDistinct = false + + /// A boolean value indicating if a function is known to return a + /// JSON value. + /// + /// A false value does not provide any information. + var isJSONValue = false } extension SQLFunctionFlags { @@ -1796,6 +1874,20 @@ extension SQLFunctionFlags { "TOTAL", ] + private static let knownFunctionsReturningJSONValue: Set = [ + "JSON", + "JSON_ARRAY", + "JSON_GROUP_ARRAY", + "JSON_GROUP_OBJECT", + "JSON_INSERT", + "JSON_OBJECT", + "JSON_PATCH", + "JSON_REMOVE", + "JSON_REPLACE", + "JSON_SET", + "JSON_QUOTE", + ] + /// Infers flags from the function name and number of arguments. static func defaultFlags(for functionName: String, argumentCount: Int) -> Self { var flags = SQLFunctionFlags() @@ -1810,10 +1902,99 @@ extension SQLFunctionFlags { flags.isAggregate = Self.knownAggregateFunctions.contains(name.uppercased()) } + if name == "JSON_EXTRACT" && argumentCount > 2 { + flags.isJSONValue = true + } else { + flags.isJSONValue = Self.knownFunctionsReturningJSONValue.contains(name) + } + return flags } } +// MARK: - JSON + +extension SQLExpression { + /// A boolean value indicating if the expression is known to be a + /// JSON value. + /// + /// A false value does not provide any information. + /// + /// For examples: + /// + /// ```swift + /// // isJSONValue is true: + /// // + /// // NULL + /// // JSON('[1, 2, 3]') + /// // info -> 'address' + /// DatabaseValue.null + /// Database.json("[1, 2, 3]") + /// JSONColumn("info").jsonString(forKey: "address") + /// + /// // isJSONValue is false + /// // + /// // '[1, 2, 3]' + /// // info + /// // info ->> 'address' + /// [1, 2, 3].databaseValue + /// JSONColumn("info") + /// JSONColumn("info")["address"] + /// ``` + var isJSONValue: Bool { + switch impl { + case .databaseValue(.null): + return true + + case let .binary(op, _, _): + return op.isJSONValue + + case let .collated(expression, _): + return expression.isJSONValue + + case let .function(_, flags: flags, arguments: _): + return flags.isJSONValue + + default: + return false + } + } + +#if GRDBCUSTOMSQLITE || GRDBCIPHER + /// Returns an expression suitable in JSON building contexts. + var jsonBuilderExpression: SQLExpression { + switch preferredJSONInterpretation { + case .deferredToSQLite: + return self + + case .jsonValue: + if isJSONValue { + return self + } else { + // Needs explicit call to JSON() + return .function("JSON", [self]) + } + } + } +#else + @available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+ + /// Returns an expression suitable in JSON building contexts. + var jsonBuilderExpression: SQLExpression { + switch preferredJSONInterpretation { + case .deferredToSQLite: + return self + + case .jsonValue: + if isJSONValue { + return self + } else { + // Needs explicit call to JSON() + return .function("JSON", [self]) + } + } + } +#endif +} // MARK: - SQLExpressible diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index b7a5602da..50bb3720d 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -13,6 +13,7 @@ 56012B82257404A400B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B80257404A300B4925B /* CommonTableExpression.swift */; }; 560233CF2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */; }; 560233D127243A9200529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233D027243A9100529DF3 /* SharedValueObservation.swift */; }; + 5603CEC42AC862F800CF097D /* SQLJSONFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEBF2AC862F800CF097D /* SQLJSONFunctions.swift */; }; 56043296228F00A9009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */; }; 560432A6228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */; }; 5604484E25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */; }; @@ -434,6 +435,7 @@ 56012B80257404A300B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = ""; }; 560233D027243A9100529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = ""; }; + 5603CEBF2AC862F800CF097D /* SQLJSONFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONFunctions.swift; sourceTree = ""; }; 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = ""; }; 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; @@ -855,6 +857,14 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 5603CEBE2AC862F800CF097D /* JSON */ = { + isa = PBXGroup; + children = ( + 5603CEBF2AC862F800CF097D /* SQLJSONFunctions.swift */, + ); + path = JSON; + sourceTree = ""; + }; 5605F1471C672E4000235C62 /* Support */ = { isa = PBXGroup; children = ( @@ -1647,6 +1657,7 @@ 566DDE11288D76400000DCFB /* Fixits.swift */, 56A2386F1B9C75030082EB20 /* Core */, 5698AC291D9E5A480056AF8C /* FTS */, + 5603CEBE2AC862F800CF097D /* JSON */, 56A238911B9C750B0082EB20 /* Migration */, 5656A8252295BD56001FF3FF /* QueryInterface */, 56A2389F1B9C753B0082EB20 /* Record */, @@ -2015,6 +2026,7 @@ 5656A88F2295BD56001FF3FF /* Column.swift in Sources */, 564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */, 5656A8612295BD56001FF3FF /* TableRecord+Association.swift in Sources */, + 5603CEC42AC862F800CF097D /* SQLJSONFunctions.swift in Sources */, F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, 563CBBE42A595141008905CE /* SQLIndexGenerator.swift in Sources */, 5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */, From 546e8aa77cbfe9d5f14c76fe23e05fa86f0c7d1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Oct 2023 20:26:31 +0200 Subject: [PATCH 17/24] JSONColumn and SQLJSONExpressible --- GRDB.xcodeproj/project.pbxproj | 8 + GRDB/JSON/JSONColumn.swift | 16 + GRDB/JSON/SQLJSONExpressible.swift | 332 ++++++++++++++++++ .../SQLGeneration/SQLGenerationContext.swift | 9 + GRDBCustom.xcodeproj/project.pbxproj | 8 + 5 files changed, 373 insertions(+) create mode 100644 GRDB/JSON/JSONColumn.swift create mode 100644 GRDB/JSON/SQLJSONExpressible.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 5bc34fa75..dc093125a 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -14,6 +14,8 @@ 560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; }; 560233C92724338800529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C82724338800529DF3 /* SharedValueObservationTests.swift */; }; 5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */; }; + 5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */; }; + 5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB82AC862EC00CF097D /* JSONColumn.swift */; }; 560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; }; 560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; }; 5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; }; @@ -420,6 +422,8 @@ 560233C32724234F00529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = ""; }; 560233C82724338800529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = ""; }; 5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONFunctions.swift; sourceTree = ""; }; + 5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONExpressible.swift; sourceTree = ""; }; + 5603CEB82AC862EC00CF097D /* JSONColumn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumn.swift; sourceTree = ""; }; 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = ""; }; 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; @@ -847,6 +851,8 @@ 5603CEB52AC862EC00CF097D /* JSON */ = { isa = PBXGroup; children = ( + 5603CEB82AC862EC00CF097D /* JSONColumn.swift */, + 5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */, 5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */, ); path = JSON; @@ -2164,6 +2170,7 @@ 5659F4881EA8D94E004A4992 /* Utils.swift in Sources */, 566BE71E2342542F00A8254B /* LockedBox.swift in Sources */, 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, + 5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */, 56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */, 5611620825757583007AAF99 /* JoinAssociation.swift in Sources */, 5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, @@ -2192,6 +2199,7 @@ 56D110BF28AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */, 566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */, 5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */, 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, 56E9FADA221053DD00C703A8 /* SQL.swift in Sources */, diff --git a/GRDB/JSON/JSONColumn.swift b/GRDB/JSON/JSONColumn.swift new file mode 100644 index 000000000..97faef0a4 --- /dev/null +++ b/GRDB/JSON/JSONColumn.swift @@ -0,0 +1,16 @@ +public struct JSONColumn: ColumnExpression, SQLJSONExpressible { + public var name: String + + /// Creates a `JSONColumn` given its name. + /// + /// The name should be unqualified, such as `"score"`. Qualified name such + /// as `"player.score"` are unsupported. + public init(_ name: String) { + self.name = name + } + + /// Creates a `JSONColumn` given a `CodingKey`. + public init(_ codingKey: some CodingKey) { + self.name = codingKey.stringValue + } +} diff --git a/GRDB/JSON/SQLJSONExpressible.swift b/GRDB/JSON/SQLJSONExpressible.swift new file mode 100644 index 000000000..be395be29 --- /dev/null +++ b/GRDB/JSON/SQLJSONExpressible.swift @@ -0,0 +1,332 @@ +public protocol SQLJSONExpressible: SQLSpecificExpressible { } + +extension ColumnExpression where Self: SQLJSONExpressible { + /// Returns an SQL column that is interpreted as a JSON value. + public var sqlExpression: SQLExpression { + .column(name).withPreferredJSONInterpretation(.jsonValue) + } +} + +// This type only grants access to `SQLJSONExpressible` apis. The fact that +// it is a JSON value is embedded in its +// `sqlExpression.preferredJSONInterpretation`. +/// A type-erased ``SQLJSONExpressible``. +public struct AnySQLJSONExpressible: SQLJSONExpressible { + /// An SQL expression that is interpreted as a JSON value. + public let sqlExpression: SQLExpression + + public init(_ base: some SQLJSONExpressible) { + self.init(sqlExpression: base.sqlExpression) + } + + /// - Precondition: `sqlExpression` is a JSON value + init(sqlExpression: SQLExpression) { + assert(sqlExpression.preferredJSONInterpretation == .jsonValue) + self.sqlExpression = sqlExpression + } +} + +extension SQLSpecificExpressible { + /// Returns an expression that is interpreted as a JSON value. + /// + /// For example: + /// + /// ```swift + /// let info = Column("info").asJSON + /// + /// // SELECT info ->> 'firstName' FROM player + /// // → 'Arthur' + /// let firstName = try Player + /// .select(info["firstName"], as: String.self) + /// .fetchOne(db) + /// ``` + /// + /// For more information, see ``SQLJSONExpressible``. + public var asJSON: AnySQLJSONExpressible { + AnySQLJSONExpressible(sqlExpression: sqlExpression.withPreferredJSONInterpretation(.jsonValue)) + } +} + +#if GRDBCUSTOMSQLITE || GRDBCIPHER +extension SQLJSONExpressible { + /// The `->>` SQL operator. + /// + /// For example: + /// + /// ```swift + /// let info = JSONColumn("info") + /// + /// // SELECT info ->> 'firstName' FROM player + /// // → 'Arthur' + /// let firstName = try Player + /// .select(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) + /// .fetchOne(db) + /// ``` + /// + /// Related SQL documentation: + /// + /// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments), + /// or an JSON object field label, or an array index. + public subscript(_ path: some SQLExpressible) -> SQLExpression { + .binary(.jsonExtractSQL, sqlExpression, path.sqlExpression) + } + + /// The `JSON_EXTRACT` SQL function. + /// + /// For example: + /// + /// ```swift + /// let info = JSONColumn("info") + /// + /// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player + /// // → 'Arthur' + /// let firstName = try Player + /// .select(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) + /// .fetchOne(db) + /// ``` + /// + /// Related SQL documentation: + /// + /// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). + public func jsonExtract(atPath path: some SQLExpressible) -> SQLExpression { + Database.jsonExtract(self, atPath: path) + } + + /// The `JSON_EXTRACT` SQL function. + /// + /// For example: + /// + /// ```swift + /// 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) + /// .fetchOne(db) + /// ``` + /// + /// Related SQL documentation: + /// + /// - parameter paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments). + public func jsonExtract(atPaths paths: C) -> SQLExpression + where C: Collection, C.Element: SQLExpressible + { + Database.jsonExtract(self, atPaths: paths) + } + + /// Returns a valid JSON string with the `->` SQL operator. + /// + /// For example: + /// + /// ```swift + /// let info = JSONColumn("info") + /// + /// // SELECT info -> 'firstName' FROM player + /// // → '"Arthur"' + /// let name = try Player + /// .select(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) + /// .fetchOne(db) + /// ``` + /// + /// Related SQL documentation: + /// + /// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments), + /// or an JSON object field label, or an array index. + public func jsonRepresentation(atPath path: some SQLExpressible) -> SQLExpression { + .binary(.jsonExtractJSON, sqlExpression, path.sqlExpression) + } +} +#else +@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+ +extension SQLJSONExpressible { + /// The `->>` SQL operator. + /// + /// For example: + /// + /// ```swift + /// let info = JSONColumn("info") + /// + /// // SELECT info ->> 'firstName' FROM player + /// // → 'Arthur' + /// let firstName = try Player + /// .select(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) + /// .fetchOne(db) + /// ``` + /// + /// Related SQL documentation: + /// + /// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments), + /// or an JSON object field label, or an array index. + public subscript(_ path: some SQLExpressible) -> SQLExpression { + .binary(.jsonExtractSQL, sqlExpression, path.sqlExpression) + } + + /// The `JSON_EXTRACT` SQL function. + /// + /// For example: + /// + /// ```swift + /// let info = JSONColumn("info") + /// + /// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player + /// // → 'Arthur' + /// let firstName = try Player + /// .select(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) + /// .fetchOne(db) + /// ``` + /// + /// Related SQL documentation: + /// + /// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). + public func jsonExtract(atPath path: some SQLExpressible) -> SQLExpression { + Database.jsonExtract(self, atPath: path) + } + + /// The `JSON_EXTRACT` SQL function. + /// + /// For example: + /// + /// ```swift + /// 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) + /// .fetchOne(db) + /// ``` + /// + /// Related SQL documentation: + /// + /// - parameter paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments). + public func jsonExtract(atPaths paths: C) -> SQLExpression + where C: Collection, C.Element: SQLExpressible + { + Database.jsonExtract(self, atPaths: paths) + } + + /// Returns a valid JSON string with the `->` SQL operator. + /// + /// For example: + /// + /// ```swift + /// let info = JSONColumn("info") + /// + /// // SELECT info -> 'firstName' FROM player + /// // → '"Arthur"' + /// let name = try Player + /// .select(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) + /// .fetchOne(db) + /// ``` + /// + /// Related SQL documentation: + /// + /// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments), + /// or an JSON object field label, or an array index. + public func jsonRepresentation(atPath path: some SQLExpressible) -> SQLExpression { + .binary(.jsonExtractJSON, sqlExpression, path.sqlExpression) + } +} + +// TODO: Enable when those apis are ready. +// @available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+ +// extension ColumnExpression where Self: SQLJSONExpressible { +// /// Updates a columns with the `JSON_PATCH` SQL function. +// /// +// /// For example: +// /// +// /// ```swift +// /// // UPDATE player SET address = JSON_PATCH(address, '{"country": "FR"}') +// /// try Player.updateAll(db, [ +// /// JSONColumn("address").jsonPatch(#"{"country": "FR"}"#) +// /// ]) +// /// ``` +// /// +// /// Related SQLite documentation: +// public func jsonPatch( +// with patch: some SQLExpressible) +// -> ColumnAssignment +// { +// .init(columnName: name, value: Database.jsonPatch(self, with: patch)) +// } +// +// /// Updates a columns with the `JSON_REMOVE` SQL function. +// /// +// /// For example: +// /// +// /// ```swift +// /// // UPDATE player SET address = JSON_REMOVE(address, '$.country') +// /// try Player.updateAll(db, [ +// /// JSONColumn("address").jsonRemove(atPath: "$.country") +// /// ]) +// /// ``` +// /// +// /// Related SQLite documentation: +// /// +// /// - Parameters: +// /// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). +// public func jsonRemove(atPath path: some SQLExpressible) -> ColumnAssignment { +// .init(columnName: name, value: Database.jsonRemove(self, atPath: path)) +// } +// +// /// Updates a columns with the `JSON_REMOVE` SQL function. +// /// +// /// For example: +// /// +// /// ```swift +// /// // UPDATE player SET address = JSON_REMOVE(address, '$.country', '$.city') +// /// try Player.updateAll(db, [ +// /// JSONColumn("address").jsonRemove(atPatsh: ["$.country", "$.city"]) +// /// ]) +// /// ``` +// /// +// /// Related SQLite documentation: +// /// +// /// - Parameters: +// /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments). +// public func jsonRemove(atPaths paths: C) +// -> ColumnAssignment +// where C: Collection, C.Element: SQLExpressible +// { +// .init(columnName: name, value: Database.jsonRemove(self, atPaths: paths)) +// } +// +// } +#endif diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index cc865de97..d364a6bbb 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -431,6 +431,15 @@ public class TableAlias { expression.sqlExpression.qualified(with: self) } + public subscript(_ expression: some SQLJSONExpressible & + SQLSpecificExpressible & + SQLSelectable & + SQLOrderingTerm) + -> AnySQLJSONExpressible + { + AnySQLJSONExpressible(sqlExpression: expression.sqlExpression.qualified(with: self)) + } + /// Returns an SQL ordering term that refers to the aliased table. /// /// For example, let's sort books by author name first, and then by title: diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 50bb3720d..55b5a9ade 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -14,6 +14,8 @@ 560233CF2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */; }; 560233D127243A9200529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233D027243A9100529DF3 /* SharedValueObservation.swift */; }; 5603CEC42AC862F800CF097D /* SQLJSONFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEBF2AC862F800CF097D /* SQLJSONFunctions.swift */; }; + 5603CEC52AC862F800CF097D /* SQLJSONExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEC02AC862F800CF097D /* SQLJSONExpressible.swift */; }; + 5603CEC62AC862F800CF097D /* JSONColumn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEC12AC862F800CF097D /* JSONColumn.swift */; }; 56043296228F00A9009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */; }; 560432A6228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */; }; 5604484E25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */; }; @@ -436,6 +438,8 @@ 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = ""; }; 560233D027243A9100529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = ""; }; 5603CEBF2AC862F800CF097D /* SQLJSONFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONFunctions.swift; sourceTree = ""; }; + 5603CEC02AC862F800CF097D /* SQLJSONExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONExpressible.swift; sourceTree = ""; }; + 5603CEC12AC862F800CF097D /* JSONColumn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumn.swift; sourceTree = ""; }; 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = ""; }; 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; @@ -860,6 +864,8 @@ 5603CEBE2AC862F800CF097D /* JSON */ = { isa = PBXGroup; children = ( + 5603CEC12AC862F800CF097D /* JSONColumn.swift */, + 5603CEC02AC862F800CF097D /* SQLJSONExpressible.swift */, 5603CEBF2AC862F800CF097D /* SQLJSONFunctions.swift */, ); path = JSON; @@ -1995,6 +2001,7 @@ F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */, 56F89DFA2A57EAB9002FE2AA /* ColumnDefinition.swift in Sources */, 56F89E1C2A585E0D002FE2AA /* SQLTableGenerator.swift in Sources */, + 5603CEC52AC862F800CF097D /* SQLJSONExpressible.swift in Sources */, 560233D127243A9200529DF3 /* SharedValueObservation.swift in Sources */, 5656A8592295BD56001FF3FF /* SQLGenerationContext.swift in Sources */, 5690C3421D23E82A00E59934 /* Data.swift in Sources */, @@ -2023,6 +2030,7 @@ 5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 5656A85B2295BD56001FF3FF /* TableDefinition.swift in Sources */, 5656A8552295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */, + 5603CEC62AC862F800CF097D /* JSONColumn.swift in Sources */, 5656A88F2295BD56001FF3FF /* Column.swift in Sources */, 564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */, 5656A8612295BD56001FF3FF /* TableRecord+Association.swift in Sources */, From 5a42d78e06f1a865a46f4419d7a393947099b2f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Oct 2023 20:31:12 +0200 Subject: [PATCH 18/24] Data decoding and encoding strategies Users must be able to store JSON data as text in the database. --- GRDB.xcodeproj/project.pbxproj | 8 + .../Request/RequestProtocols.swift | 6 +- GRDB/Record/EncodableRecord+Encodable.swift | 4 +- GRDB/Record/EncodableRecord.swift | 68 ++++ GRDB/Record/FetchableRecord+Decodable.swift | 117 ++++++- GRDB/Record/FetchableRecord.swift | 64 ++++ GRDBCustom.xcodeproj/project.pbxproj | 8 + README.md | 28 +- .../GRDBTests.xcodeproj/project.pbxproj | 14 +- .../GRDBTests.xcodeproj/project.pbxproj | 14 +- .../DatabaseDataDecodingStrategyTests.swift | 139 ++++++++ .../DatabaseDataEncodingStrategyTests.swift | 309 ++++++++++++++++++ 12 files changed, 759 insertions(+), 20 deletions(-) create mode 100644 Tests/GRDBTests/DatabaseDataDecodingStrategyTests.swift create mode 100644 Tests/GRDBTests/DatabaseDataEncodingStrategyTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index dc093125a..d12f4459c 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -57,6 +57,8 @@ 561CFA7823735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; }; 561CFA982376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; }; 561CFA9C2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */; }; + 561F38EF2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; }; + 561F38F42AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; }; 562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; }; 562205F21E420E47005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */; }; 562205F31E420E47005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; }; @@ -464,6 +466,8 @@ 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = ""; }; 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = ""; }; 561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = ""; }; + 561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = ""; }; + 561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = ""; }; @@ -937,6 +941,7 @@ isa = PBXGroup; children = ( D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */, + 561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */, 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */, 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */, 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */, @@ -1294,6 +1299,7 @@ 5674A7251F30A8EF0095F066 /* FetchableRecord */ = { isa = PBXGroup; children = ( + 561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */, 5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */, 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */, 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */, @@ -1947,6 +1953,7 @@ 56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */, 563B06CA2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */, 56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */, + 561F38F42AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */, 56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */, 5616B4FB28B5F5220052017E /* SingletonRecordTest.swift in Sources */, 56419C5724A51998004967E1 /* Inverted.swift in Sources */, @@ -1957,6 +1964,7 @@ 56057C552291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */, 56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */, 56419C5124A51998004967E1 /* Finished.swift in Sources */, + 561F38EF2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */, 56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 564D4F7E261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift in Sources */, 56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */, diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index e253baec8..9e64e7d25 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -442,7 +442,11 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { // make it impractical to define `filter(id:)`, `fetchOne(_:key:)`, // `deleteAll(_:ids:)` etc. if let recordType = RowDecoder.self as? any EncodableRecord.Type { - if Sequence.Element.self == Date.self || Sequence.Element.self == Optional.self { + if Sequence.Element.self == Data.self || Sequence.Element.self == Optional.self { + let strategy = recordType.databaseDataEncodingStrategy + let keys = keys.compactMap { ($0 as! Data?).flatMap(strategy.encode)?.databaseValue } + return filter(rawKeys: keys) + } else if Sequence.Element.self == Date.self || Sequence.Element.self == Optional.self { let strategy = recordType.databaseDateEncodingStrategy let keys = keys.compactMap { ($0 as! Date?).flatMap(strategy.encode)?.databaseValue } return filter(rawKeys: keys) diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index 0782dc6b3..c7816c672 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -128,7 +128,9 @@ private class RecordEncoder: Encoder { } fileprivate func encode(_ value: T, forKey key: any CodingKey) throws where T: Encodable { - if let date = value as? Date { + if let data = value as? Data { + persist(Record.databaseDataEncodingStrategy.encode(data), forKey: key) + } else if let date = value as? Date { persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key) } else if let uuid = value as? UUID { persist(Record.databaseUUIDEncodingStrategy.encode(uuid), forKey: key) diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 6818fbd28..30bf4bb48 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -20,11 +20,13 @@ import Foundation // For JSONEncoder /// ### Configuring Persistence for the Standard Encodable Protocol /// /// - ``databaseColumnEncodingStrategy-5sx4v`` +/// - ``databaseDataEncodingStrategy-9y0c7`` /// - ``databaseDateEncodingStrategy-2gtc1`` /// - ``databaseEncodingUserInfo-8upii`` /// - ``databaseJSONEncoder(for:)-6x62c`` /// - ``databaseUUIDEncodingStrategy-2t96q`` /// - ``DatabaseColumnEncodingStrategy`` +/// - ``DatabaseDataEncodingStrategy`` /// - ``DatabaseDateEncodingStrategy`` /// - ``DatabaseUUIDEncodingStrategy`` /// @@ -115,6 +117,24 @@ public protocol EncodableRecord { /// ``encode(to:)-1mrt`` implementation. static func databaseJSONEncoder(for column: String) -> JSONEncoder + /// The strategy for encoding `Data` columns. + /// + /// This property is dedicated to ``EncodableRecord`` types that also + /// conform to the standard `Encodable` protocol and use the default + /// ``encode(to:)-1mrt`` implementation. + /// + /// For example: + /// + /// ```swift + /// struct Player: EncodableRecord, Encodable { + /// static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text + /// + /// // Encoded as SQL text. Data must contain valid UTF8 bytes. + /// var jsonData: Data + /// } + /// ``` + static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { get } + /// The strategy for encoding `Date` columns. /// /// This property is dedicated to ``EncodableRecord`` types that also @@ -199,6 +219,12 @@ extension EncodableRecord { return encoder } + /// Returns the default strategy for encoding `Data` columns: + /// ``DatabaseDataEncodingStrategy/deferredToData``. + public static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { + .deferredToData + } + /// Returns the default strategy for encoding `Date` columns: /// ``DatabaseDateEncodingStrategy/deferredToDate``. public static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { @@ -423,6 +449,48 @@ extension Row { } } +// MARK: - DatabaseDataEncodingStrategy + +/// `DatabaseDataEncodingStrategy` specifies how `EncodableRecord` types that +/// also adopt the standard `Encodable` protocol encode their `Data` properties +/// in the default +/// implementation. +/// +/// For example: +/// +/// ```swift +/// struct Player: EncodableRecord, Encodable { +/// static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text +/// +/// // Encoded as SQL text. Data must contain valid UTF8 bytes. +/// var jsonData: Data +/// } +/// ``` +public enum DatabaseDataEncodingStrategy { + /// Encodes `Data` columns as SQL blob. + case deferredToData + + /// Encodes `Data` columns as SQL text. Data must contain valid UTF8 bytes. + case text + + /// Encodes `Data` column as the result of the user-provided function. + case custom((Data) -> (any DatabaseValueConvertible)?) + + func encode(_ data: Data) -> DatabaseValue { + switch self { + case .deferredToData: + return data.databaseValue + case .text: + guard let string = String(data: data, encoding: .utf8) else { + fatalError("Invalid UTF8 data") + } + return string.databaseValue + case .custom(let format): + return format(data)?.databaseValue ?? .null + } + } +} + // MARK: - DatabaseDateEncodingStrategy /// `DatabaseDateEncodingStrategy` specifies how `EncodableRecord` types that diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 1d42f5c02..e1d7db715 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -51,6 +51,7 @@ extension FetchableRecord where Self: Decodable { /// The behavior of the decoder depends on the decoded type. See: /// /// - ``FetchableRecord/databaseColumnDecodingStrategy-6uefz`` +/// - ``FetchableRecord/databaseDataDecodingStrategy-71bh1`` /// - ``FetchableRecord/databaseDateDecodingStrategy-78y03`` /// - ``FetchableRecord/databaseDecodingUserInfo-77jim`` /// - ``FetchableRecord/databaseJSONDecoder(for:)-7lmxd`` @@ -258,7 +259,11 @@ private struct _RowDecoder: Decoder { { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. - if type == Date.self { + if type == Data.self { + return try R.databaseDataDecodingStrategy.decodeIfPresent( + fromRow: row, + atUncheckedIndex: index) as! T? + } else if type == Date.self { return try R.databaseDateDecodingStrategy.decodeIfPresent( fromRow: row, atUncheckedIndex: index) as! T? @@ -303,7 +308,9 @@ private struct _RowDecoder: Decoder { { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. - if type == Date.self { + if type == Data.self { + return try R.databaseDataDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T + } else if type == Date.self { return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T } else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type { return try type.fastDecode(fromRow: row, atUncheckedIndex: index) as! T @@ -546,9 +553,10 @@ extension ColumnDecoder: SingleValueDecodingContainer { func decode(_ type: String.Type) throws -> String { try row.decode(atIndex: columnIndex) } func decode(_ type: T.Type) throws -> T where T: Decodable { - // Prefer DatabaseValueConvertible decoding over Decodable. - // This allows decoding Date from String, or DatabaseValue from NULL. - if type == Date.self { + // TODO: not tested + if type == Data.self { + return try R.databaseDataDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T + } else if type == Date.self { return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T } else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type { return try type.fastDecode(fromRow: row, atUncheckedIndex: columnIndex) as! T @@ -566,6 +574,105 @@ private let iso8601Formatter: ISO8601DateFormatter = { return formatter }() +extension DatabaseDataDecodingStrategy { + fileprivate func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Data? { + if let sqliteStatement = row.sqliteStatement { + return try decodeIfPresent( + fromStatement: sqliteStatement, + atUncheckedIndex: CInt(index), + context: RowDecodingContext(row: row, key: .columnIndex(index))) + } else { + return try decodeIfPresent( + fromDatabaseValue: row[index], + context: RowDecodingContext(row: row, key: .columnIndex(index))) + } + } + + fileprivate func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Data { + if let sqliteStatement = row.sqliteStatement { + return try decode( + fromStatement: sqliteStatement, + atUncheckedIndex: CInt(index), + context: RowDecodingContext(row: row, key: .columnIndex(index))) + } else { + return try decode( + fromDatabaseValue: row[index], + context: RowDecodingContext(row: row, key: .columnIndex(index))) + } + } + + /// - precondition: value is not NULL + fileprivate func decode( + fromStatement sqliteStatement: SQLiteStatement, + atUncheckedIndex index: CInt, + context: @autoclosure () -> RowDecodingContext) + throws -> Data + { + assert(sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL, "unexpected NULL value") + switch self { + case .deferredToData: + return Data(sqliteStatement: sqliteStatement, index: index) + case .custom(let format): + let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) + guard let data = format(dbValue) else { + throw RowDecodingError.valueMismatch( + Data.self, + context: context(), + databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) + } + return data + } + } + + fileprivate func decodeIfPresent( + fromStatement sqliteStatement: SQLiteStatement, + atUncheckedIndex index: CInt, + context: @autoclosure () -> RowDecodingContext) + throws -> Data? + { + if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { + return nil + } + return try decode(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context()) + } + + fileprivate func decode( + fromDatabaseValue dbValue: DatabaseValue, + context: @autoclosure () -> RowDecodingContext) + throws -> Data + { + if let data = dataFromDatabaseValue(dbValue) { + return data + } else { + throw RowDecodingError.valueMismatch(Data.self, context: context(), databaseValue: dbValue) + } + } + + fileprivate func decodeIfPresent( + fromDatabaseValue dbValue: DatabaseValue, + context: @autoclosure () -> RowDecodingContext) + throws -> Data? + { + if dbValue.isNull { + return nil + } else if let data = dataFromDatabaseValue(dbValue) { + return data + } else { + throw RowDecodingError.valueMismatch(Data.self, context: context(), databaseValue: dbValue) + } + } + + // Returns nil if decoding fails + private func dataFromDatabaseValue(_ dbValue: DatabaseValue) -> Data? { + switch self { + case .deferredToData: + return Data.fromDatabaseValue(dbValue) + case .custom(let format): + return format(dbValue) + } + } +} + extension DatabaseDateDecodingStrategy { fileprivate func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Date? { if let sqliteStatement = row.sqliteStatement { diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 31616d672..b91cef517 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -89,10 +89,12 @@ import Foundation /// ### Configuring Row Decoding for the Standard Decodable Protocol /// /// - ``databaseColumnDecodingStrategy-6uefz`` +/// - ``databaseDataDecodingStrategy-71bh1`` /// - ``databaseDateDecodingStrategy-78y03`` /// - ``databaseDecodingUserInfo-77jim`` /// - ``databaseJSONDecoder(for:)-7lmxd`` /// - ``DatabaseColumnDecodingStrategy`` +/// - ``DatabaseDataDecodingStrategy`` /// - ``DatabaseDateDecodingStrategy`` /// /// ### Supporting Types @@ -153,6 +155,29 @@ public protocol FetchableRecord { /// ``init(row:)-4ptlh`` implementation. static func databaseJSONDecoder(for column: String) -> JSONDecoder + /// The strategy for decoding `Data` columns. + /// + /// This property is dedicated to ``FetchableRecord`` types that also + /// conform to the standard `Decodable` protocol and use the default + /// ``init(row:)-4ptlh`` implementation. + /// + /// For example: + /// + /// ```swift + /// struct Player: FetchableRecord, Decodable { + /// static let databaseDataDecodingStrategy = DatabaseDataDecodingStrategy.custom { dbValue + /// guard let base64Data = Data.fromDatabaseValue(dbValue) else { + /// return nil + /// } + /// return Data(base64Encoded: base64Data) + /// } + /// + /// // Decoded from both database base64 strings and blobs + /// var myData: Data + /// } + /// ``` + static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { get } + /// The strategy for decoding `Date` columns. /// /// This property is dedicated to ``FetchableRecord`` types that also @@ -216,6 +241,12 @@ extension FetchableRecord { return decoder } + /// The default strategy for decoding `Data` columns is + /// ``DatabaseDataDecodingStrategy/deferredToData``. + public static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { + .deferredToData + } + /// The default strategy for decoding `Date` columns is /// ``DatabaseDateDecodingStrategy/deferredToDate``. public static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { @@ -823,6 +854,39 @@ public final class RecordCursor: DatabaseCursor { } } +// MARK: - DatabaseDataDecodingStrategy + +/// `DatabaseDataDecodingStrategy` specifies how `FetchableRecord` types that +/// also adopt the standard `Decodable` protocol decode their +/// `Data` properties. +/// +/// For example: +/// +/// ```swift +/// struct Player: FetchableRecord, Decodable { +/// static let databaseDataDecodingStrategy = DatabaseDataDecodingStrategy.custom { dbValue +/// guard let base64Data = Data.fromDatabaseValue(dbValue) else { +/// return nil +/// } +/// return Data(base64Encoded: base64Data) +/// } +/// +/// // Decoded from both database base64 strings and blobs +/// var myData: Data +/// } +/// ``` +public enum DatabaseDataDecodingStrategy { + /// Decodes `Data` columns from SQL blobs and UTF8 text. + case deferredToData + + /// Decodes `Data` columns according to the user-provided function. + /// + /// If the database value does not contain a suitable value, the function + /// must return nil (GRDB will interpret this nil result as a conversion + /// error, and react accordingly). + case custom((DatabaseValue) -> Data?) +} + // MARK: - DatabaseDateDecodingStrategy /// `DatabaseDateDecodingStrategy` specifies how `FetchableRecord` types that diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 55b5a9ade..9e28d7dac 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -36,6 +36,8 @@ 561CFA7D2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */; }; 561CFAA12376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */; }; 561CFAA42376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; }; + 561F38F22AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F02AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; }; + 561F38F62AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F52AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; }; 562205FA1E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; }; 562205FB1E420E49005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */; }; 562205FC1E420E49005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; }; @@ -476,6 +478,8 @@ 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = ""; }; 561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = ""; }; 561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = ""; }; + 561F38F02AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = ""; }; + 561F38F52AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = ""; }; 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; @@ -949,6 +953,7 @@ 560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = { isa = PBXGroup; children = ( + 561F38F02AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift */, 5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */, 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */, 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */, @@ -1312,6 +1317,7 @@ 5674A7251F30A8EF0095F066 /* FetchableRecord */ = { isa = PBXGroup; children = ( + 561F38F52AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */, 5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */, 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */, 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */, @@ -2103,6 +2109,7 @@ F3BA81301CFB3064003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, 5653EB7A20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */, + 561F38F22AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */, 563C67B824628C0C00E94EDC /* DatabasePoolTests.swift in Sources */, F3BA80FB1CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, F3BA80EE1CFB3017003DC1BA /* RowAdapterTests.swift in Sources */, @@ -2230,6 +2237,7 @@ 5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 563B533B267E2FA4009549B5 /* TableTests.swift in Sources */, 5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 561F38F62AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */, 564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */, F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */, 5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */, diff --git a/README.md b/README.md index c31d94741..53447ca80 100644 --- a/README.md +++ b/README.md @@ -2571,7 +2571,7 @@ For more information about Codable records, see: - [JSON Columns] - [Column Names Coding Strategies] -- [Date and UUID Coding Strategies] +- [Data, Date, and UUID Coding Strategies] - [The userInfo Dictionary] - [Tip: Derive Columns from Coding Keys](#tip-derive-columns-from-coding-keys) @@ -2646,9 +2646,9 @@ protocol EncodableRecord { See [DatabaseColumnDecodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasecolumndecodingstrategy) and [DatabaseColumnEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasecolumnencodingstrategy/) to learn about all available strategies. -### Date and UUID Coding Strategies +### Data, Date, and UUID Coding Strategies -By default, [Codable Records] encode and decode their Date and UUID properties as described in the general [Date and DateComponents](#date-and-datecomponents) and [UUID](#uuid) chapters. +By default, [Codable Records] encode and decode their Data properties as blobs, and Date and UUID properties as described in the general [Date and DateComponents](#date-and-datecomponents) and [UUID](#uuid) chapters. To sum up: dates encode themselves in the "YYYY-MM-DD HH:MM:SS.SSS" format, in the UTC time zone, and decode a variety of date formats and timestamps. UUIDs encode themselves as 16-bytes data blobs, and decode both 16-bytes data blobs and strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F". @@ -2656,27 +2656,29 @@ Those behaviors can be overridden: ```swift protocol FetchableRecord { + static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { get } static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get } } protocol EncodableRecord { + static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { get } static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get } static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get } } ``` -See [DatabaseDateDecodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedatedecodingstrategy/), [DatabaseDateEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedateencodingstrategy/), and [DatabaseUUIDEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseuuidencodingstrategy/) to learn about all available strategies. +See [DatabaseDataDecodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedatadecodingstrategy/), [DatabaseDateDecodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedatedecodingstrategy/), [DatabaseDataEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedataencodingstrategy/), [DatabaseDateEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedateencodingstrategy/), and [DatabaseUUIDEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseuuidencodingstrategy/) to learn about all available strategies. There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase). -Customized date and uuid handling apply: +Customized coding strategies apply: - When encoding and decoding database rows to and from records (fetching and persistence methods). - In requests by single-column primary key: `fetchOne(_:id:)`, `filter(id:)`, `deleteAll(_:keys:)`, etc. -*They do not apply* in other requests based on date or uuid values. +*They do not apply* in other requests based on data, date, or uuid values. -So make sure that dates and uuids are properly encoded in your requests. For example: +So make sure that those are properly encoded in your requests. For example: ```swift struct Player: Codable, FetchableRecord, PersistableRecord, Identifiable { @@ -3449,11 +3451,11 @@ This is the list of record methods, along with their required protocols. The [Re | **[Codable Records]** | | | | `Type.databaseDecodingUserInfo` | [FetchableRecord] | [*](#the-userinfo-dictionary) | | `Type.databaseJSONDecoder(for:)` | [FetchableRecord] | [*](#json-columns) | -| `Type.databaseDateDecodingStrategy` | [FetchableRecord] | [*](#date-and-uuid-coding-strategies) | +| `Type.databaseDateDecodingStrategy` | [FetchableRecord] | [*](#data-date-and-uuid-coding-strategies) | | `Type.databaseEncodingUserInfo` | [EncodableRecord] | [*](#the-userinfo-dictionary) | | `Type.databaseJSONEncoder(for:)` | [EncodableRecord] | [*](#json-columns) | -| `Type.databaseDateEncodingStrategy` | [EncodableRecord] | [*](#date-and-uuid-coding-strategies) | -| `Type.databaseUUIDEncodingStrategy` | [EncodableRecord] | [*](#date-and-uuid-coding-strategies) | +| `Type.databaseDateEncodingStrategy` | [EncodableRecord] | [*](#data-date-and-uuid-coding-strategies) | +| `Type.databaseUUIDEncodingStrategy` | [EncodableRecord] | [*](#data-date-and-uuid-coding-strategies) | | **Define [Associations]** | | | | `Type.belongsTo(...)` | [TableRecord] | [*](Documentation/AssociationsBasics.md) | | `Type.hasMany(...)` | [TableRecord] | [*](Documentation/AssociationsBasics.md) | @@ -6213,6 +6215,10 @@ This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/document This chapter was removed. See the references of [DatabaseReader](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasereader) and [DatabaseWriter](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasewriter). +#### Date and UUID Coding Strategies + +This chapter has been renamed [Data, Date, and UUID Coding Strategies]. + #### Dealing with External Connections This chapter has been superseded by the [Sharing a Database] guide. @@ -6308,7 +6314,7 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [Common Table Expressions]: Documentation/CommonTableExpressions.md [Conflict Resolution]: #conflict-resolution [Column Names Coding Strategies]: #column-names-coding-strategies -[Date and UUID Coding Strategies]: #date-and-uuid-coding-strategies +[Data, Date, and UUID Coding Strategies]: #data-date-and-uuid-coding-strategies [Fetching from Requests]: #fetching-from-requests [Embedding SQL in Query Interface Requests]: #embedding-sql-in-query-interface-requests [Full-Text Search]: Documentation/FullTextSearch.md diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index bc0906d61..21d46891b 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -3,10 +3,14 @@ archiveVersion = 1; classes = { }; - objectVersion = 51; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ + 561F38F92AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; }; + 561F38FA2AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; }; + 561F38FB2AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F82AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; }; + 561F38FC2AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F82AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; }; 56419D6724A54062004967E1 /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419C9C24A54053004967E1 /* DatabasePoolTests.swift */; }; 56419D6824A54062004967E1 /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419C9C24A54053004967E1 /* DatabasePoolTests.swift */; }; 56419D6924A54062004967E1 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419C9D24A54053004967E1 /* ResultCodeTests.swift */; }; @@ -459,6 +463,8 @@ /* Begin PBXFileReference section */ 04298D834C818285823558AB /* Pods-GRDBTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.release.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.release.xcconfig"; sourceTree = ""; }; 47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = ""; }; + 561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = ""; }; + 561F38F82AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = ""; }; 56419C9C24A54053004967E1 /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = ""; }; 56419C9D24A54053004967E1 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = ""; }; 56419C9E24A54053004967E1 /* DatabaseQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTests.swift; sourceTree = ""; }; @@ -827,6 +833,8 @@ 56419CE824A54059004967E1 /* DatabaseCollationTests.swift */, 56419D1124A5405C004967E1 /* DatabaseConfigurationTests.swift */, 56419CA424A54054004967E1 /* DatabaseCursorTests.swift */, + 561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */, + 561F38F82AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift */, 56419CCE24A54057004967E1 /* DatabaseDateDecodingStrategyTests.swift */, 56419CE424A54058004967E1 /* DatabaseDateEncodingStrategyTests.swift */, 56419CAF24A54054004967E1 /* DatabaseErrorTests.swift */, @@ -1226,6 +1234,7 @@ 56419DF324A54062004967E1 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 56419E6724A54062004967E1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 56419E4D24A54062004967E1 /* FoundationNSDecimalNumberTests.swift in Sources */, + 561F38F92AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */, 56419E6B24A54062004967E1 /* ValueObservationFetchTests.swift in Sources */, 56419D8524A54062004967E1 /* FTS4RecordTests.swift in Sources */, 5641A1B224A540D6004967E1 /* Next.swift in Sources */, @@ -1383,6 +1392,7 @@ 56419EA924A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56419E7F24A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */, 56419EF124A54063004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */, + 561F38FB2AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */, 56419EA324A54063004967E1 /* TableRecordDeleteTests.swift in Sources */, 56419EFB24A54063004967E1 /* FoundationDateComponentsTests.swift in Sources */, 56419E3D24A54062004967E1 /* FTS3TableBuilderTests.swift in Sources */, @@ -1452,6 +1462,7 @@ 56419DF424A54062004967E1 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 56419E6824A54062004967E1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 56419E4E24A54062004967E1 /* FoundationNSDecimalNumberTests.swift in Sources */, + 561F38FA2AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */, 56419E6C24A54062004967E1 /* ValueObservationFetchTests.swift in Sources */, 56419D8624A54062004967E1 /* FTS4RecordTests.swift in Sources */, 5641A1B324A540D6004967E1 /* Next.swift in Sources */, @@ -1609,6 +1620,7 @@ 56419EAA24A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56419E8024A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */, 56419EF224A54063004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */, + 561F38FC2AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */, 56419EA424A54063004967E1 /* TableRecordDeleteTests.swift in Sources */, 56419EFC24A54063004967E1 /* FoundationDateComponentsTests.swift in Sources */, 56419E3E24A54062004967E1 /* FTS3TableBuilderTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 46926ec6d..90f12e2d0 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -3,10 +3,14 @@ archiveVersion = 1; classes = { }; - objectVersion = 51; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ + 561F38FF2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38FD2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; }; + 561F39002AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38FD2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; }; + 561F39012AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38FE2AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; }; + 561F39022AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38FE2AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; }; 56419FC824A540A1004967E1 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFD24A54093004967E1 /* FetchRequestTests.swift */; }; 56419FC924A540A1004967E1 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFD24A54093004967E1 /* FetchRequestTests.swift */; }; 56419FCA24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */; }; @@ -475,6 +479,8 @@ /* Begin PBXFileReference section */ 04298D834C818285823558AB /* Pods-GRDBTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.release.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.release.xcconfig"; sourceTree = ""; }; 47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = ""; }; + 561F38FD2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = ""; }; + 561F38FE2AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = ""; }; 56419EFD24A54093004967E1 /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = ""; }; 56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = ""; }; @@ -856,6 +862,8 @@ 568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */, 56419F7024A5409A004967E1 /* DatabaseConfigurationTests.swift */, 56419F2324A54095004967E1 /* DatabaseCursorTests.swift */, + 561F38FE2AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift */, + 561F38FD2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift */, 56419FBE24A540A0004967E1 /* DatabaseDateDecodingStrategyTests.swift */, 56419F2824A54095004967E1 /* DatabaseDateEncodingStrategyTests.swift */, 56419F5824A54098004967E1 /* DatabaseErrorTests.swift */, @@ -1355,6 +1363,7 @@ 5641A0F424A540A1004967E1 /* ColumnInfoTests.swift in Sources */, 5641A07A24A540A1004967E1 /* QueryInterfacePromiseTests.swift in Sources */, 5641A0E824A540A1004967E1 /* AssociationParallelSQLTests.swift in Sources */, + 561F39012AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */, 56419FE024A540A1004967E1 /* AssociationChainSQLTests.swift in Sources */, 5641A03E24A540A1004967E1 /* InflectionsTests.swift in Sources */, 5641A06224A540A1004967E1 /* DropWhileCursorTests.swift in Sources */, @@ -1398,6 +1407,7 @@ 56419FE624A540A1004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 5641A04424A540A1004967E1 /* FTS3TokenizerTests.swift in Sources */, 5641A14024A540A2004967E1 /* RecordPrimaryKeyRowIDTests.swift in Sources */, + 561F38FF2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */, 5641A08A24A540A1004967E1 /* EncryptionTests.swift in Sources */, 5641A11E24A540A1004967E1 /* IndexInfoTests.swift in Sources */, 56419FEC24A540A1004967E1 /* FTS4TableBuilderTests.swift in Sources */, @@ -1588,6 +1598,7 @@ 5641A0F524A540A1004967E1 /* ColumnInfoTests.swift in Sources */, 5641A07B24A540A1004967E1 /* QueryInterfacePromiseTests.swift in Sources */, 5641A0E924A540A1004967E1 /* AssociationParallelSQLTests.swift in Sources */, + 561F39022AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */, 56419FE124A540A1004967E1 /* AssociationChainSQLTests.swift in Sources */, 5641A03F24A540A1004967E1 /* InflectionsTests.swift in Sources */, 5641A06324A540A1004967E1 /* DropWhileCursorTests.swift in Sources */, @@ -1631,6 +1642,7 @@ 56419FE724A540A1004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 5641A04524A540A1004967E1 /* FTS3TokenizerTests.swift in Sources */, 5641A14124A540A2004967E1 /* RecordPrimaryKeyRowIDTests.swift in Sources */, + 561F39002AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */, 5641A08B24A540A1004967E1 /* EncryptionTests.swift in Sources */, 5641A11F24A540A1004967E1 /* IndexInfoTests.swift in Sources */, 56419FED24A540A1004967E1 /* FTS4TableBuilderTests.swift in Sources */, diff --git a/Tests/GRDBTests/DatabaseDataDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDataDecodingStrategyTests.swift new file mode 100644 index 000000000..8ff1da13b --- /dev/null +++ b/Tests/GRDBTests/DatabaseDataDecodingStrategyTests.swift @@ -0,0 +1,139 @@ +import Foundation +import XCTest +@testable import GRDB // TODO: remove @testable when RowDecodingError is public + +private protocol StrategyProvider { + static var strategy: DatabaseDataDecodingStrategy { get } +} + +private enum StrategyDeferredToData: StrategyProvider { + static let strategy: DatabaseDataDecodingStrategy = .deferredToData +} + +private enum StrategyCustom: StrategyProvider { + static let strategy: DatabaseDataDecodingStrategy = .custom { dbValue in + if dbValue == "invalid".databaseValue { + return nil + } + return "foo".data(using: .utf8)! + } +} + +private struct RecordWithData: FetchableRecord, Decodable { + static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { Strategy.strategy } + var data: Data +} + +private struct RecordWithOptionalData: FetchableRecord, Decodable { + static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { Strategy.strategy } + var data: Data? +} + +class DatabaseDataDecodingStrategyTests: GRDBTestCase { + /// test the conversion from a database value to a data extracted from a record + private func test( + _ db: Database, + record: T.Type, + data: (T) -> Data?, + databaseValue: (any DatabaseValueConvertible)?, + with test: (Data?) -> Void) throws + { + let request = SQLRequest(sql: "SELECT ? AS data", arguments: [databaseValue]) + do { + // test decoding straight from SQLite + let record = try T.fetchOne(db, request)! + test(data(record)) + } + do { + // test decoding from copied row + let record = try T(row: Row.fetchOne(db, request)!) + test(data(record)) + } + } + + /// test the conversion from a database value to a data with a given strategy + private func test( + _ db: Database, + strategy: Strategy.Type, + databaseValue: some DatabaseValueConvertible, + _ test: (Data) -> Void) + throws + { + try self.test(db, record: RecordWithData.self, data: { $0.data }, databaseValue: databaseValue, with: { test($0!) }) + try self.test(db, record: RecordWithOptionalData.self, data: { $0.data }, databaseValue: databaseValue, with: { test($0!) }) + } + + private func testNullDecoding(_ db: Database, strategy: Strategy.Type) throws { + try self.test(db, record: RecordWithOptionalData.self, data: { $0.data }, databaseValue: nil) { data in + XCTAssertNil(data) + } + } +} + +// MARK: - deferredToData + +extension DatabaseDataDecodingStrategyTests { + func testDeferredToData() throws { + try makeDatabaseQueue().read { db in + // Null + try testNullDecoding(db, strategy: StrategyDeferredToData.self) + + // Empty string + try test(db, strategy: StrategyDeferredToData.self, databaseValue: "") { data in + XCTAssertEqual(data, Data()) + } + + // String + try test(db, strategy: StrategyDeferredToData.self, databaseValue: "foo") { data in + XCTAssertEqual(data, "foo".data(using: .utf8)) + } + + // Empty blob + try test(db, strategy: StrategyDeferredToData.self, databaseValue: Data()) { data in + XCTAssertEqual(data, Data()) + } + + // Blob + try test(db, strategy: StrategyDeferredToData.self, databaseValue: "foo".data(using: .utf8)) { data in + XCTAssertEqual(data, "foo".data(using: .utf8)) + } + } + } +} + +// MARK: - custom((DatabaseValue) -> Data? + +extension DatabaseDataDecodingStrategyTests { + func testCustom() throws { + try makeDatabaseQueue().read { db in + // Null + try testNullDecoding(db, strategy: StrategyCustom.self) + + // Data + try test(db, strategy: StrategyCustom.self, databaseValue: "valid") { data in + XCTAssertEqual(data, "foo".data(using: .utf8)!) + } + + // error + do { + try test(db, strategy: StrategyCustom.self, databaseValue: "invalid") { data in + XCTFail("Unexpected Data") + } + } catch let error as RowDecodingError { + switch error { + case .valueMismatch: + XCTAssertEqual(error.description, """ + could not decode Data from database value "invalid" - \ + column: "data", \ + column index: 0, \ + row: [data:"invalid"], \ + sql: `SELECT ? AS data`, \ + arguments: ["invalid"] + """) + default: + XCTFail("Unexpected Error") + } + } + } + } +} diff --git a/Tests/GRDBTests/DatabaseDataEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDataEncodingStrategyTests.swift new file mode 100644 index 000000000..6fdf7d875 --- /dev/null +++ b/Tests/GRDBTests/DatabaseDataEncodingStrategyTests.swift @@ -0,0 +1,309 @@ +import XCTest +import Foundation +@testable import GRDB + +private protocol StrategyProvider { + static var strategy: DatabaseDataEncodingStrategy { get } +} + +private enum StrategyDeferredToData: StrategyProvider { + static let strategy: DatabaseDataEncodingStrategy = .deferredToData +} + +private enum StrategyTextUTF8: StrategyProvider { + static let strategy: DatabaseDataEncodingStrategy = .text +} + +private enum StrategyCustom: StrategyProvider { + static let strategy: DatabaseDataEncodingStrategy = .custom { _ in "custom" } +} + +private struct RecordWithData: EncodableRecord, Encodable { + static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { Strategy.strategy } + var data: Data +} + +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) +extension RecordWithData: Identifiable { + var id: Data { data } +} + +private struct RecordWithOptionalData: EncodableRecord, Encodable { + static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { Strategy.strategy } + var data: Data? +} + +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) +extension RecordWithOptionalData: Identifiable { + var id: Data? { data } +} + +class DatabaseDataEncodingStrategyTests: GRDBTestCase { + let testedDatas = [ + "foo".data(using: .utf8)!, + Data(), + ] + + private func test( + record: T, + expectedStorage: DatabaseValue.Storage) + throws + { + var container = PersistenceContainer() + try record.encode(to: &container) + if let dbValue = container["data"]?.databaseValue { + XCTAssertEqual(dbValue.storage, expectedStorage) + } else { + XCTAssertEqual(.null, expectedStorage) + } + } + + private func test( + strategy: Strategy.Type, + encodesData data: Data, + as value: some DatabaseValueConvertible) + throws + { + try test(record: RecordWithData(data: data), expectedStorage: value.databaseValue.storage) + try test(record: RecordWithOptionalData(data: data), expectedStorage: value.databaseValue.storage) + } + + private func testNullEncoding(strategy: Strategy.Type) throws { + try test(record: RecordWithOptionalData(data: nil), expectedStorage: .null) + } +} + +// MARK: - deferredToData + +extension DatabaseDataEncodingStrategyTests { + func testDeferredToData() throws { + try testNullEncoding(strategy: StrategyDeferredToData.self) + + for (data, value) in zip(testedDatas, [ + "foo".data(using: .utf8)!, + Data(), + ]) { try test(strategy: StrategyDeferredToData.self, encodesData: data, as: value) } + } +} + +// MARK: - text(UTF8) + +extension DatabaseDataEncodingStrategyTests { + func testTextUTF8() throws { + try testNullEncoding(strategy: StrategyTextUTF8.self) + + for (data, value) in zip(testedDatas, [ + "foo", + "", + ]) { try test(strategy: StrategyTextUTF8.self, encodesData: data, as: value) } + } +} + +// MARK: - custom((Data) -> DatabaseValueConvertible?) + +extension DatabaseDataEncodingStrategyTests { + func testCustom() throws { + try testNullEncoding(strategy: StrategyCustom.self) + + for (data, value) in zip(testedDatas, [ + "custom", + "custom", + ]) { try test(strategy: StrategyCustom.self, encodesData: data, as: value) } + } +} + +// MARK: - Filter + +extension DatabaseDataEncodingStrategyTests { + func testFilterKey() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "t") { $0.primaryKey("id", .blob) } + + do { + let request = Table>("t").filter(key: testedDatas[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = x'666f6f' + """) + } + + do { + let request = Table>("t").filter(keys: testedDatas) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN (x'666f6f', x'') + """) + } + + do { + let request = Table>("t").filter(key: testedDatas[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = 'foo' + """) + } + + do { + let request = Table>("t").filter(keys: testedDatas) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN ('foo', '') + """) + } + } + } + + func testFilterID() throws { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { + throw XCTSkip("Identifiable not available") + } + + try makeDatabaseQueue().write { db in + try db.create(table: "t") { $0.primaryKey("id", .blob) } + + do { + let request = Table>("t").filter(id: testedDatas[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = x'666f6f' + """) + } + + do { + let request = Table>("t").filter(ids: testedDatas) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN (x'666f6f', x'') + """) + } + + do { + let request = Table>("t").filter(id: testedDatas[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = 'foo' + """) + } + + do { + let request = Table>("t").filter(ids: testedDatas) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN ('foo', '') + """) + } + + do { + let request = Table>("t").filter(id: nil) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE 0 + """) + } + + do { + let request = Table>("t").filter(id: testedDatas[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = x'666f6f' + """) + } + + do { + let request = Table>("t").filter(ids: testedDatas) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN (x'666f6f', x'') + """) + } + + do { + let request = Table>("t").filter(id: nil) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE 0 + """) + } + + do { + let request = Table>("t").filter(id: testedDatas[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = 'foo' + """) + } + + do { + let request = Table>("t").filter(ids: testedDatas) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN ('foo', '') + """) + } + } + } + + func testDeleteID() throws { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { + throw XCTSkip("Identifiable not available") + } + + try makeDatabaseQueue().write { db in + try db.create(table: "t") { $0.primaryKey("id", .blob) } + + do { + try Table>("t").deleteOne(db, id: testedDatas[0]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" = x'666f6f' + """) + } + + do { + try Table>("t").deleteAll(db, ids: testedDatas) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" IN (x'666f6f', x'') + """) + } + + do { + try Table>("t").deleteOne(db, id: testedDatas[0]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" = 'foo' + """) + } + + do { + try Table>("t").deleteAll(db, ids: testedDatas) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" IN ('foo', '') + """) + } + + do { + sqlQueries.removeAll() + try Table>("t").deleteOne(db, id: nil) + XCTAssertNil(lastSQLQuery) // Database not hit + } + + do { + try Table>("t").deleteOne(db, id: testedDatas[0]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" = x'666f6f' + """) + } + + do { + try Table>("t").deleteAll(db, ids: testedDatas) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" IN (x'666f6f', x'') + """) + } + + do { + sqlQueries.removeAll() + try Table>("t").deleteOne(db, id: nil) + XCTAssertNil(lastSQLQuery) // Database not hit + } + + do { + try Table>("t").deleteOne(db, id: testedDatas[0]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" = 'foo' + """) + } + + do { + try Table>("t").deleteAll(db, ids: testedDatas) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" IN ('foo', '') + """) + } + } + } +} From 9faea276d8d7cc197e3bea8a66ba60b793b8eefa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Oct 2023 20:32:08 +0200 Subject: [PATCH 19/24] JSON tests --- GRDB.xcodeproj/project.pbxproj | 20 +- GRDBCustom.xcodeproj/project.pbxproj | 20 +- .../GRDBTests.xcodeproj/project.pbxproj | 12 + .../GRDBTests.xcodeproj/project.pbxproj | 12 + Tests/GRDBTests/GRDBTestCase.swift | 15 +- Tests/GRDBTests/JSONColumnTests.swift | 94 ++ Tests/GRDBTests/JSONExpressionsTests.swift | 1294 +++++++++++++++++ 7 files changed, 1462 insertions(+), 5 deletions(-) create mode 100644 Tests/GRDBTests/JSONColumnTests.swift create mode 100644 Tests/GRDBTests/JSONExpressionsTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index d12f4459c..5f6ae7ecd 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -16,6 +16,7 @@ 5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */; }; 5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */; }; 5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB82AC862EC00CF097D /* JSONColumn.swift */; }; + 5603CED42AC8642F00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */; }; 560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; }; 560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; }; 5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; }; @@ -57,6 +58,7 @@ 561CFA7823735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; }; 561CFA982376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; }; 561CFA9C2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */; }; + 561F38D82AC88A550051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */; }; 561F38EF2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; }; 561F38F42AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; }; 562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; }; @@ -426,6 +428,7 @@ 5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONFunctions.swift; sourceTree = ""; }; 5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONExpressible.swift; sourceTree = ""; }; 5603CEB82AC862EC00CF097D /* JSONColumn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumn.swift; sourceTree = ""; }; + 5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = ""; }; 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = ""; }; 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; @@ -466,6 +469,7 @@ 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = ""; }; 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = ""; }; 561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = ""; }; + 561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = ""; }; 561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = ""; }; 561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; @@ -862,6 +866,15 @@ path = JSON; sourceTree = ""; }; + 5603CEC82AC8630300CF097D /* JSON */ = { + isa = PBXGroup; + children = ( + 561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */, + 5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */, + ); + name = JSON; + sourceTree = ""; + }; 5605F1471C672E4000235C62 /* Support */ = { isa = PBXGroup; children = ( @@ -969,12 +982,13 @@ 56176C581EACC2D8000F3F2B /* GRDBTests */ = { isa = PBXGroup; children = ( + 56677C14241D14450050755D /* FailureTestCase.swift */, + 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, 562EA81E1F17B26F00FA528C /* Compilation */, 56A238111B9C74A90082EB20 /* Core */, - 56677C14241D14450050755D /* FailureTestCase.swift */, 5698AC3E1DA2BEBB0056AF8C /* FTS */, 56176CA01EACEE2A000F3F2B /* GRDBCipher */, - 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, + 5603CEC82AC8630300CF097D /* JSON */, 56A238231B9C74A90082EB20 /* Migrations */, 569978D31B539038005EBEED /* Private */, 56300B5C1C53C38F005A543B /* QueryInterface */, @@ -1862,6 +1876,7 @@ 56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */, 560714E3227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */, 56D496841D813147008276D7 /* SelectStatementTests.swift in Sources */, + 561F38D82AC88A550051EEE9 /* JSONColumnTests.swift in Sources */, 56D496B11D8133BC008276D7 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, 56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */, @@ -1876,6 +1891,7 @@ 56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */, 5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 56D496801D813131008276D7 /* StatementColumnConvertibleFetchTests.swift in Sources */, + 5603CED42AC8642F00CF097D /* JSONExpressionsTests.swift in Sources */, 563B0705218627F800B38F35 /* ValueObservationRowTests.swift in Sources */, 56D4966E1D81309E008276D7 /* RecordPrimaryKeyMultipleTests.swift in Sources */, 56D496891D81316E008276D7 /* DatabaseValueConvertibleFetchTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 9e28d7dac..2b2be7313 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -16,6 +16,7 @@ 5603CEC42AC862F800CF097D /* SQLJSONFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEBF2AC862F800CF097D /* SQLJSONFunctions.swift */; }; 5603CEC52AC862F800CF097D /* SQLJSONExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEC02AC862F800CF097D /* SQLJSONExpressible.swift */; }; 5603CEC62AC862F800CF097D /* JSONColumn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEC12AC862F800CF097D /* JSONColumn.swift */; }; + 5603CED52AC8643800CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CECC2AC8633B00CF097D /* JSONExpressionsTests.swift */; }; 56043296228F00A9009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */; }; 560432A6228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */; }; 5604484E25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */; }; @@ -36,6 +37,7 @@ 561CFA7D2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */; }; 561CFAA12376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */; }; 561CFAA42376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; }; + 561F38DB2AC8914D0051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DA2AC8914D0051EEE9 /* JSONColumnTests.swift */; }; 561F38F22AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F02AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; }; 561F38F62AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F52AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; }; 562205FA1E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; }; @@ -442,6 +444,7 @@ 5603CEBF2AC862F800CF097D /* SQLJSONFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONFunctions.swift; sourceTree = ""; }; 5603CEC02AC862F800CF097D /* SQLJSONExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONExpressible.swift; sourceTree = ""; }; 5603CEC12AC862F800CF097D /* JSONColumn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumn.swift; sourceTree = ""; }; + 5603CECC2AC8633B00CF097D /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = ""; }; 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = ""; }; 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; @@ -478,6 +481,7 @@ 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = ""; }; 561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = ""; }; 561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = ""; }; + 561F38DA2AC8914D0051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = ""; }; 561F38F02AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = ""; }; 561F38F52AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = ""; }; 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = ""; }; @@ -875,6 +879,15 @@ path = JSON; sourceTree = ""; }; + 5603CECB2AC8632A00CF097D /* JSON */ = { + isa = PBXGroup; + children = ( + 561F38DA2AC8914D0051EEE9 /* JSONColumnTests.swift */, + 5603CECC2AC8633B00CF097D /* JSONExpressionsTests.swift */, + ); + name = JSON; + sourceTree = ""; + }; 5605F1471C672E4000235C62 /* Support */ = { isa = PBXGroup; children = ( @@ -988,12 +1001,13 @@ 56176C581EACC2D8000F3F2B /* GRDBTests */ = { isa = PBXGroup; children = ( + 567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */, + 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, 562EA81E1F17B26F00FA528C /* Compilation */, 56A238111B9C74A90082EB20 /* Core */, - 567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */, 5698AC3E1DA2BEBB0056AF8C /* FTS */, 56176CA01EACEE2A000F3F2B /* GRDBCipher */, - 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, + 5603CECB2AC8632A00CF097D /* JSON */, 56A238231B9C74A90082EB20 /* Migrations */, 569978D31B539038005EBEED /* Private */, 56300B5C1C53C38F005A543B /* QueryInterface */, @@ -2068,6 +2082,7 @@ F3BA80CC1CFB2FD8003DC1BA /* DatabaseQueueTests.swift in Sources */, F3BA81101CFB3057003DC1BA /* Row+FoundationTests.swift in Sources */, F3BA812C1CFB3064003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, + 561F38DB2AC8914D0051EEE9 /* JSONColumnTests.swift in Sources */, 5698AC991DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, 5653EB6C20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, @@ -2281,6 +2296,7 @@ F3BA812D1CFB3064003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 5698AC831DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, F3BA811B1CFB305F003DC1BA /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, + 5603CED52AC8643800CF097D /* JSONExpressionsTests.swift in Sources */, F3BA811A1CFB305F003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */, F3BA81111CFB3057003DC1BA /* StatementArguments+FoundationTests.swift in Sources */, F3BA81371CFB3064003DC1BA /* RecordInitializersTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 21d46891b..25b79c854 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -7,6 +7,10 @@ objects = { /* Begin PBXBuildFile section */ + 5603CECF2AC8636E00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CECE2AC8636E00CF097D /* JSONExpressionsTests.swift */; }; + 5603CED02AC8636E00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CECE2AC8636E00CF097D /* JSONExpressionsTests.swift */; }; + 561F38DD2AC891710051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DC2AC891710051EEE9 /* JSONColumnTests.swift */; }; + 561F38DE2AC891710051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DC2AC891710051EEE9 /* JSONColumnTests.swift */; }; 561F38F92AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; }; 561F38FA2AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; }; 561F38FB2AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F82AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; }; @@ -463,6 +467,8 @@ /* Begin PBXFileReference section */ 04298D834C818285823558AB /* Pods-GRDBTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.release.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.release.xcconfig"; sourceTree = ""; }; 47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = ""; }; + 5603CECE2AC8636E00CF097D /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = ""; }; + 561F38DC2AC891710051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = ""; }; 561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = ""; }; 561F38F82AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = ""; }; 56419C9C24A54053004967E1 /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = ""; }; @@ -919,6 +925,8 @@ 56419CDE24A54058004967E1 /* IndexInfoTests.swift */, 56419CF024A54059004967E1 /* InflectionsTests.swift */, 56419D0024A5405A004967E1 /* JoinSupportTests.swift */, + 561F38DC2AC891710051EEE9 /* JSONColumnTests.swift */, + 5603CECE2AC8636E00CF097D /* JSONExpressionsTests.swift */, 56419CDC24A54058004967E1 /* MapCursorTests.swift */, 56419D0224A5405A004967E1 /* MutablePersistableRecordChangesTests.swift */, 56419D2F24A5405E004967E1 /* MutablePersistableRecordEncodableTests.swift */, @@ -1266,6 +1274,7 @@ 56419ED924A54063004967E1 /* AssociationHasOneSQLTests.swift in Sources */, 56419EAB24A54063004967E1 /* DatabaseValueTests.swift in Sources */, 56419D7724A54062004967E1 /* DatabaseCursorTests.swift in Sources */, + 5603CECF2AC8636E00CF097D /* JSONExpressionsTests.swift in Sources */, 56419E1524A54062004967E1 /* AssociationChainRowScopesTests.swift in Sources */, 56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */, 56419EC724A54063004967E1 /* RecordPrimaryKeyMultipleTests.swift in Sources */, @@ -1276,6 +1285,7 @@ 56419DA524A54062004967E1 /* QueryInterfacePromiseTests.swift in Sources */, 56419EE324A54063004967E1 /* Row+FoundationTests.swift in Sources */, 56419E7124A54062004967E1 /* DatabaseTests.swift in Sources */, + 561F38DD2AC891710051EEE9 /* JSONColumnTests.swift in Sources */, 56419E9524A54063004967E1 /* PrefixWhileCursorTests.swift in Sources */, 56419E2F24A54062004967E1 /* JoinSupportTests.swift in Sources */, 56419E0524A54062004967E1 /* AssociationParallelSQLTests.swift in Sources */, @@ -1494,6 +1504,7 @@ 56419EDA24A54063004967E1 /* AssociationHasOneSQLTests.swift in Sources */, 56419EAC24A54063004967E1 /* DatabaseValueTests.swift in Sources */, 56419D7824A54062004967E1 /* DatabaseCursorTests.swift in Sources */, + 5603CED02AC8636E00CF097D /* JSONExpressionsTests.swift in Sources */, 56419E1624A54062004967E1 /* AssociationChainRowScopesTests.swift in Sources */, 56F61DF1283D484700AF9884 /* getThreadsCount.c in Sources */, 56419EC824A54063004967E1 /* RecordPrimaryKeyMultipleTests.swift in Sources */, @@ -1504,6 +1515,7 @@ 56419DA624A54062004967E1 /* QueryInterfacePromiseTests.swift in Sources */, 56419EE424A54063004967E1 /* Row+FoundationTests.swift in Sources */, 56419E7224A54062004967E1 /* DatabaseTests.swift in Sources */, + 561F38DE2AC891710051EEE9 /* JSONColumnTests.swift in Sources */, 56419E9624A54063004967E1 /* PrefixWhileCursorTests.swift in Sources */, 56419E3024A54062004967E1 /* JoinSupportTests.swift in Sources */, 56419E0624A54062004967E1 /* AssociationParallelSQLTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 90f12e2d0..1a667d385 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -7,6 +7,10 @@ objects = { /* Begin PBXBuildFile section */ + 561F38E12AC891890051EEE9 /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DF2AC891890051EEE9 /* JSONExpressionsTests.swift */; }; + 561F38E22AC891890051EEE9 /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DF2AC891890051EEE9 /* JSONExpressionsTests.swift */; }; + 561F38E32AC891890051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38E02AC891890051EEE9 /* JSONColumnTests.swift */; }; + 561F38E42AC891890051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38E02AC891890051EEE9 /* JSONColumnTests.swift */; }; 561F38FF2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38FD2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; }; 561F39002AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38FD2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; }; 561F39012AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38FE2AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; }; @@ -479,6 +483,8 @@ /* Begin PBXFileReference section */ 04298D834C818285823558AB /* Pods-GRDBTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.release.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.release.xcconfig"; sourceTree = ""; }; 47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = ""; }; + 561F38DF2AC891890051EEE9 /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = ""; }; + 561F38E02AC891890051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = ""; }; 561F38FD2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = ""; }; 561F38FE2AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = ""; }; 56419EFD24A54093004967E1 /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; @@ -950,6 +956,8 @@ 56419FA824A5409E004967E1 /* IndexInfoTests.swift */, 56419F3824A54096004967E1 /* InflectionsTests.swift */, 56419F6D24A5409A004967E1 /* JoinSupportTests.swift */, + 561F38E02AC891890051EEE9 /* JSONColumnTests.swift */, + 561F38DF2AC891890051EEE9 /* JSONExpressionsTests.swift */, 56419F7B24A5409B004967E1 /* MapCursorTests.swift */, 56419F4524A54097004967E1 /* MutablePersistableRecordChangesTests.swift */, 56419F0224A54093004967E1 /* MutablePersistableRecordEncodableTests.swift */, @@ -1353,6 +1361,7 @@ 5641A08224A540A1004967E1 /* AssociationAggregateTests.swift in Sources */, 5641A12424A540A1004967E1 /* DatabaseTraceTests.swift in Sources */, 56419FE224A540A1004967E1 /* AssociationBelongsToRowScopeTests.swift in Sources */, + 561F38E12AC891890051EEE9 /* JSONExpressionsTests.swift in Sources */, 5641A07624A540A1004967E1 /* CompilationProtocolTests.swift in Sources */, 5641A14624A540A2004967E1 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5641A03C24A540A1004967E1 /* AssociationBelongsToSQLTests.swift in Sources */, @@ -1442,6 +1451,7 @@ 5641A05624A540A1004967E1 /* AssociationPrefetchingSQLTests.swift in Sources */, 5641A12224A540A1004967E1 /* FTS5PatternTests.swift in Sources */, 5641A0F624A540A1004967E1 /* FTS5WrapperTokenizerTests.swift in Sources */, + 561F38E32AC891890051EEE9 /* JSONColumnTests.swift in Sources */, 5641A15C24A540A2004967E1 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 5641A03024A540A1004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 5641A00224A540A1004967E1 /* PersistableRecordTests.swift in Sources */, @@ -1588,6 +1598,7 @@ 5641A08324A540A1004967E1 /* AssociationAggregateTests.swift in Sources */, 5641A12524A540A1004967E1 /* DatabaseTraceTests.swift in Sources */, 56419FE324A540A1004967E1 /* AssociationBelongsToRowScopeTests.swift in Sources */, + 561F38E22AC891890051EEE9 /* JSONExpressionsTests.swift in Sources */, 5641A07724A540A1004967E1 /* CompilationProtocolTests.swift in Sources */, 5641A14724A540A2004967E1 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5641A03D24A540A1004967E1 /* AssociationBelongsToSQLTests.swift in Sources */, @@ -1677,6 +1688,7 @@ 5641A05724A540A1004967E1 /* AssociationPrefetchingSQLTests.swift in Sources */, 5641A12324A540A1004967E1 /* FTS5PatternTests.swift in Sources */, 5641A0F724A540A1004967E1 /* FTS5WrapperTokenizerTests.swift in Sources */, + 561F38E42AC891890051EEE9 /* JSONColumnTests.swift in Sources */, 5641A15D24A540A2004967E1 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 5641A03124A540A1004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 5641A00324A540A1004967E1 /* PersistableRecordTests.swift in Sources */, diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 7192b9320..9028d491f 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -159,6 +159,19 @@ class GRDBTestCase: XCTestCase { assertEqualSQL(lastSQLQuery!, sql, file: file, line: line) } + // Compare SQL strings. + func assertEqualSQL( + _ db: Database, + _ expression: some SQLExpressible, + _ sql: String, + file: StaticString = #file, + line: UInt = #line) + throws + { + let request: SQLRequest = "SELECT \(expression)" + try assertEqualSQL(db, request, "SELECT \(sql)", file: file, line: line) + } + // Compare SQL strings (ignoring leading and trailing white space and semicolons. func assertEqualSQL( _ databaseReader: some DatabaseReader, @@ -172,7 +185,7 @@ class GRDBTestCase: XCTestCase { try assertEqualSQL(db, request, sql, file: file, line: line) } } - + func sql( _ databaseReader: some DatabaseReader, _ request: some FetchRequest) diff --git a/Tests/GRDBTests/JSONColumnTests.swift b/Tests/GRDBTests/JSONColumnTests.swift new file mode 100644 index 000000000..1a78c9c96 --- /dev/null +++ b/Tests/GRDBTests/JSONColumnTests.swift @@ -0,0 +1,94 @@ +import XCTest +import GRDB + +final class JSONColumnTests: GRDBTestCase { + func test_JSONColumn_derived_from_CodingKey() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + struct Player: Codable, TableRecord, FetchableRecord, PersistableRecord { + var id: Int64 + var info: Data + + enum CodingKeys: String, CodingKey { + case id + case info = "info_json" + } + + enum Columns { + static let id = Column(CodingKeys.id) + static let info = JSONColumn(CodingKeys.info) + } + + static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.info] + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("info_json", .jsonText) + } + + try assertEqualSQL(db, Player.all(), """ + SELECT "id", "info_json" FROM "player" + """) + } + } + + func test_extraction() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("info", .jsonText) + } + + let player = Table("player") + let info = JSONColumn("info") + + try assertEqualSQL(db, player.select(info["score"]), """ + SELECT "info" ->> 'score' FROM "player" + """) + + try assertEqualSQL(db, player.select(info["$.score"]), """ + SELECT "info" ->> '$.score' FROM "player" + """) + + try assertEqualSQL(db, player.select(info.jsonExtract(atPath: "$.score")), """ + SELECT JSON_EXTRACT("info", '$.score') FROM "player" + """) + + try assertEqualSQL(db, player.select(info.jsonExtract(atPaths: ["$.score", "$.bonus"])), """ + SELECT JSON_EXTRACT("info", '$.score', '$.bonus') FROM "player" + """) + + try assertEqualSQL(db, player.select(info.jsonRepresentation(atPath: "score")), """ + SELECT "info" -> 'score' FROM "player" + """) + + try assertEqualSQL(db, player.select(info.jsonRepresentation(atPath: "$.score")), """ + SELECT "info" -> '$.score' FROM "player" + """) + } + } +} diff --git a/Tests/GRDBTests/JSONExpressionsTests.swift b/Tests/GRDBTests/JSONExpressionsTests.swift new file mode 100644 index 000000000..46daefbc6 --- /dev/null +++ b/Tests/GRDBTests/JSONExpressionsTests.swift @@ -0,0 +1,1294 @@ +import XCTest +import GRDB + +final class JSONExpressionsTests: GRDBTestCase { + func test_Database_json() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.json(#" { "a": [ "test" ] } "#), """ + JSON(' { "a": [ "test" ] } ') + """) + + try assertEqualSQL(db, player.select(Database.json(nameColumn)), """ + SELECT JSON("name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.json(infoColumn)), """ + SELECT JSON("info") FROM "player" + """) + } + } + + func test_asJSON() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, player.select([ + #"[1, 2, 3]"#.databaseValue.asJSON, + DatabaseValue.null.asJSON, + nameColumn.asJSON, + infoColumn.asJSON, + abs(nameColumn).asJSON, + abs(infoColumn).asJSON, + ]), """ + SELECT \ + '[1, 2, 3]', \ + NULL, \ + "name", \ + "info", \ + ABS("name"), \ + ABS("info") \ + FROM "player" + """) + + try assertEqualSQL(db, player.select([ + Database.jsonArray([ + #"[1, 2, 3]"#.databaseValue.asJSON, + DatabaseValue.null.asJSON, + nameColumn.asJSON, + infoColumn.asJSON, + abs(nameColumn).asJSON, + abs(infoColumn).asJSON, + ]) + ]), """ + SELECT JSON_ARRAY(\ + JSON('[1, 2, 3]'), \ + NULL, \ + JSON("name"), \ + JSON("info"), \ + JSON(ABS("name")), \ + JSON(ABS("info"))\ + ) FROM "player" + """) + } + } + + func test_Database_jsonArray() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonArray(1...4), """ + JSON_ARRAY(1, 2, 3, 4) + """) + + try assertEqualSQL(db, Database.jsonArray([1, 2, 3, 4]), """ + JSON_ARRAY(1, 2, 3, 4) + """) + + try assertEqualSQL(db, Database.jsonArray([1, 2, "3", 4]), """ + JSON_ARRAY(1, 2, '3', 4) + """) + + // Note: this JSON(JSON_EXTRACT(...)) is useful, when the extracted value is a string that contains JSON + try assertEqualSQL(db, player + .select( + Database.jsonArray([ + nameColumn, + nameColumn.asJSON, + infoColumn, + infoColumn["score"], + infoColumn["score"].asJSON, + infoColumn.jsonExtract(atPath: "address"), + infoColumn.jsonExtract(atPath: "address").asJSON, + infoColumn.jsonRepresentation(atPath: "address"), + infoColumn.jsonRepresentation(atPath: "address").asJSON, + ] as [any SQLExpressible]) + ), """ + SELECT JSON_ARRAY(\ + "name", \ + JSON("name"), \ + JSON("info"), \ + "info" ->> 'score', \ + JSON("info" ->> 'score'), \ + JSON_EXTRACT("info", 'address'), \ + JSON(JSON_EXTRACT("info", 'address')), \ + "info" -> 'address', \ + "info" -> 'address'\ + ) FROM "player" + """) + + let alias = TableAlias(name: "p") + + try assertEqualSQL(db, player + .aliased(alias) + .select( + alias[ + Database.jsonArray([ + nameColumn, + nameColumn.asJSON, + infoColumn, + infoColumn["score"], + infoColumn.jsonExtract(atPath: "address"), + infoColumn.jsonRepresentation(atPath: "address"), + ] as [any SQLExpressible]) + ] + ), """ + SELECT JSON_ARRAY(\ + "p"."name", \ + JSON("p"."name"), \ + JSON("p"."info"), \ + "p"."info" ->> 'score', \ + JSON_EXTRACT("p"."info", 'address'), \ + "p"."info" -> 'address'\ + ) FROM "player" "p" + """) + + try assertEqualSQL(db, player + .aliased(alias) + .select( + Database.jsonArray([ + alias[nameColumn], + alias[nameColumn.asJSON], + alias[infoColumn], + alias[infoColumn["score"]], + alias[infoColumn.jsonExtract(atPath: "address")], + alias[infoColumn.jsonRepresentation(atPath: "address")], + ] as [any SQLExpressible]) + ), """ + SELECT JSON_ARRAY(\ + "p"."name", \ + JSON("p"."name"), \ + JSON("p"."info"), \ + "p"."info" ->> 'score', \ + JSON_EXTRACT("p"."info", 'address'), \ + "p"."info" -> 'address'\ + ) FROM "player" "p" + """) + + try assertEqualSQL(db, player + .aliased(alias) + .select( + Database.jsonArray([ + alias[nameColumn], + alias[nameColumn].asJSON, + alias[infoColumn], + alias[infoColumn]["score"], + alias[infoColumn].jsonExtract(atPath: "address"), + alias[infoColumn].jsonRepresentation(atPath: "address"), + ] as [any SQLExpressible]) + ), """ + SELECT JSON_ARRAY(\ + "p"."name", \ + JSON("p"."name"), \ + JSON("p"."info"), \ + "p"."info" ->> 'score', \ + JSON_EXTRACT("p"."info", 'address'), \ + "p"."info" -> 'address'\ + ) FROM "player" "p" + """) + } + } + + func test_Database_jsonArrayLength() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonArrayLength("[1,2,3,4]"), """ + JSON_ARRAY_LENGTH('[1,2,3,4]') + """) + + try assertEqualSQL(db, player.select(Database.jsonArrayLength(nameColumn)), """ + SELECT JSON_ARRAY_LENGTH("name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonArrayLength(infoColumn)), """ + SELECT JSON_ARRAY_LENGTH("info") FROM "player" + """) + } + } + + func test_Database_jsonArrayLength_atPath() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonArrayLength(#"{"one":[1,2,3]}"#, atPath: "$.one"), """ + JSON_ARRAY_LENGTH('{"one":[1,2,3]}', '$.one') + """) + + try assertEqualSQL(db, player.select(Database.jsonArrayLength(nameColumn, atPath: "$.a")), """ + SELECT JSON_ARRAY_LENGTH("name", '$.a') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonArrayLength(#"{"one":[1,2,3]}"#, atPath: nameColumn)), """ + SELECT JSON_ARRAY_LENGTH('{"one":[1,2,3]}', "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonArrayLength(infoColumn, atPath: "$.a")), """ + SELECT JSON_ARRAY_LENGTH("info", '$.a') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonArrayLength(#"{"one":[1,2,3]}"#, atPath: infoColumn)), """ + SELECT JSON_ARRAY_LENGTH('{"one":[1,2,3]}', "info") FROM "player" + """) + } + } + + func test_Database_jsonErrorPosition() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3042000 else { + throw XCTSkip("JSON_ERROR_JSON is not available") + } +#else + guard #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) else { + throw XCTSkip("JSON_ERROR_JSON is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonErrorPosition(#" { "a": [ "test" ] } "#), """ + JSON_ERROR_POSITION(' { "a": [ "test" ] } ') + """) + + try assertEqualSQL(db, player.select(Database.jsonErrorPosition(nameColumn)), """ + SELECT JSON_ERROR_POSITION("name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonErrorPosition(infoColumn)), """ + SELECT JSON_ERROR_POSITION("info") FROM "player" + """) + } + } + + func test_Database_jsonExtract_atPath() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonExtract(#"{"a":123}"#, atPath: "$.a"), """ + JSON_EXTRACT('{"a":123}', '$.a') + """) + + try assertEqualSQL(db, player.select(Database.jsonExtract(nameColumn, atPath: "$.a")), """ + SELECT JSON_EXTRACT("name", '$.a') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonExtract(infoColumn, atPath: "$.a")), """ + SELECT JSON_EXTRACT("info", '$.a') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonExtract(#"{"a":123}"#, atPath: nameColumn)), """ + SELECT JSON_EXTRACT('{"a":123}', "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonExtract(#"{"a":123}"#, atPath: infoColumn)), """ + SELECT JSON_EXTRACT('{"a":123}', "info") FROM "player" + """) + } + } + + func test_Database_jsonExtract_atPaths() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonExtract(#"{"a":2,"c":[4,5]}"#, atPaths: ["$.c", "$.a"]), """ + JSON_EXTRACT('{"a":2,"c":[4,5]}', '$.c', '$.a') + """) + + try assertEqualSQL(db, player.select(Database.jsonExtract(nameColumn, atPaths: ["$.c", "$.a"])), """ + SELECT JSON_EXTRACT("name", '$.c', '$.a') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonExtract(infoColumn, atPaths: ["$.c", "$.a"])), """ + SELECT JSON_EXTRACT("info", '$.c', '$.a') FROM "player" + """) + } + } + + func test_Database_jsonInsert() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonInsert("[1,2,3,4]", ["$[#]": #"{"e":5}"#]), """ + JSON_INSERT('[1,2,3,4]', '$[#]', '{"e":5}') + """) + + try assertEqualSQL(db, Database.jsonInsert("[1,2,3,4]", ["$[#]": #"{"e":5}"#.databaseValue.asJSON]), """ + JSON_INSERT('[1,2,3,4]', '$[#]', JSON('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonInsert("[1,2,3,4]", ["$[#]": Database.json(#"{"e":5}"#)]), """ + JSON_INSERT('[1,2,3,4]', '$[#]', JSON('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonInsert("[1,2,3,4]", ["$[#]": Database.jsonObject(["e": 5])]), """ + JSON_INSERT('[1,2,3,4]', '$[#]', JSON_OBJECT('e', 5)) + """) + + try assertEqualSQL(db, player.select(Database.jsonInsert(nameColumn, ["$[#]": 99])), """ + SELECT JSON_INSERT("name", '$[#]', 99) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonInsert(infoColumn, ["$[#]": 99])), """ + SELECT JSON_INSERT("info", '$[#]', 99) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonInsert("[1,2,3,4]", ["$[#]": nameColumn])), """ + SELECT JSON_INSERT('[1,2,3,4]', '$[#]', "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonInsert("[1,2,3,4]", ["$[#]": infoColumn])), """ + SELECT JSON_INSERT('[1,2,3,4]', '$[#]', JSON("info")) FROM "player" + """) + } + } + + func test_Database_jsonReplace() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": #"{"e":5}"#]), """ + JSON_REPLACE('{"a":2,"c":4}', '$.a', '{"e":5}') + """) + + try assertEqualSQL(db, Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": #"{"e":5}"#.databaseValue.asJSON]), """ + JSON_REPLACE('{"a":2,"c":4}', '$.a', JSON('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": Database.json(#"{"e":5}"#)]), """ + JSON_REPLACE('{"a":2,"c":4}', '$.a', JSON('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": Database.jsonObject(["e": 5])]), """ + JSON_REPLACE('{"a":2,"c":4}', '$.a', JSON_OBJECT('e', 5)) + """) + + try assertEqualSQL(db, player.select(Database.jsonReplace(nameColumn, ["$.a": 99])), """ + SELECT JSON_REPLACE("name", '$.a', 99) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonReplace(infoColumn, ["$.a": 99])), """ + SELECT JSON_REPLACE("info", '$.a', 99) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": nameColumn])), """ + SELECT JSON_REPLACE('{"a":2,"c":4}', '$.a', "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": infoColumn])), """ + SELECT JSON_REPLACE('{"a":2,"c":4}', '$.a', JSON("info")) FROM "player" + """) + } + } + + func test_Database_jsonSet() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": #"{"e":5}"#]), """ + JSON_SET('{"a":2,"c":4}', '$.a', '{"e":5}') + """) + + try assertEqualSQL(db, Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": #"{"e":5}"#.databaseValue.asJSON]), """ + JSON_SET('{"a":2,"c":4}', '$.a', JSON('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": Database.json(#"{"e":5}"#)]), """ + JSON_SET('{"a":2,"c":4}', '$.a', JSON('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": Database.jsonObject(["e": 5])]), """ + JSON_SET('{"a":2,"c":4}', '$.a', JSON_OBJECT('e', 5)) + """) + + try assertEqualSQL(db, player.select(Database.jsonSet(nameColumn, ["$.a": 99])), """ + SELECT JSON_SET("name", '$.a', 99) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonSet(infoColumn, ["$.a": 99])), """ + SELECT JSON_SET("info", '$.a', 99) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": nameColumn])), """ + SELECT JSON_SET('{"a":2,"c":4}', '$.a', "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": infoColumn])), """ + SELECT JSON_SET('{"a":2,"c":4}', '$.a', JSON("info")) FROM "player" + """) + } + } + + func test_Database_jsonObject_from_Dictionary() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL( + db, + Database.jsonObject([ + "a": 2, + ] as [String: Int]), """ + JSON_OBJECT('a', 2) + """) + + try assertEqualSQL( + db, + Database.jsonObject([ + "c": #"{"e":5}"#, + ] as [String: any SQLExpressible]), """ + JSON_OBJECT('c', '{"e":5}') + """) + + try assertEqualSQL( + db, + Database.jsonObject([ + "c": #"{"e":5}"#.databaseValue.asJSON, + ] as [String: any SQLExpressible]), """ + JSON_OBJECT('c', JSON('{"e":5}')) + """) + + try assertEqualSQL( + db, + Database.jsonObject([ + "c": Database.jsonObject(["e": 5]), + ]), """ + JSON_OBJECT('c', JSON_OBJECT('e', 5)) + """) + + try assertEqualSQL( + db, + Database.jsonObject([ + "c": Database.json(#"{"e":5}"#), + ]), """ + JSON_OBJECT('c', JSON('{"e":5}')) + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonObject([ + "a": nameColumn, + ]) + ), """ + SELECT JSON_OBJECT('a', "name") FROM "player" + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonObject([ + "c": infoColumn, + ]) + ), """ + SELECT JSON_OBJECT('c', JSON("info")) FROM "player" + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonObject([ + "a": Database.json(nameColumn), + ]) + ), """ + SELECT JSON_OBJECT('a', JSON("name")) FROM "player" + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonObject([ + "c": Database.json(infoColumn), + ]) + ), """ + SELECT JSON_OBJECT('c', JSON("info")) FROM "player" + """) + } + } + + func test_Database_jsonObject_from_Array() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + // Ordered Array + + try assertEqualSQL( + db, + Database.jsonObject([ + (key: "a", value: 2), + (key: "c", value: #"{"e":5}"#), + ] as [(key: String, value: any SQLExpressible)]), """ + JSON_OBJECT('a', 2, 'c', '{"e":5}') + """) + + try assertEqualSQL( + db, + Database.jsonObject([ + (key: "a", value: 2), + (key: "c", value: #"{"e":5}"#.databaseValue.asJSON), + ] as [(key: String, value: any SQLExpressible)]), """ + JSON_OBJECT('a', 2, 'c', JSON('{"e":5}')) + """) + + try assertEqualSQL( + db, + Database.jsonObject([ + (key: "a", value: 2), + (key: "c", value: Database.jsonObject(["e": 5])), + ] as [(key: String, value: any SQLExpressible)]), """ + JSON_OBJECT('a', 2, 'c', JSON_OBJECT('e', 5)) + """) + + try assertEqualSQL( + db, + Database.jsonObject([ + (key: "a", value: 2), + (key: "c", value: Database.json(#"{"e":5}"#)), + ] as [(key: String, value: any SQLExpressible)]), """ + JSON_OBJECT('a', 2, 'c', JSON('{"e":5}')) + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonObject([ + (key: "a", value: nameColumn), + (key: "c", value: infoColumn), + ] as [(key: String, value: any SQLExpressible)]) + ), """ + SELECT JSON_OBJECT('a', "name", 'c', JSON("info")) FROM "player" + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonObject([ + (key: "a", value: Database.json(nameColumn)), + (key: "c", value: Database.json(infoColumn)), + ] as [(key: String, value: SQLExpression)]) + ), """ + SELECT JSON_OBJECT('a', JSON("name"), 'c', JSON("info")) FROM "player" + """) + } + } + + func test_Database_jsonObject_from_KeyValuePairs() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + // Ordered Array + + try assertEqualSQL( + db, + Database.jsonObject([ + "a": 2, + "c": #"{"e":5}"#, + ] as KeyValuePairs), """ + JSON_OBJECT('a', 2, 'c', '{"e":5}') + """) + + try assertEqualSQL( + db, + Database.jsonObject([ + "a": 2, + "c": #"{"e":5}"#.databaseValue.asJSON, + ] as KeyValuePairs), """ + JSON_OBJECT('a', 2, 'c', JSON('{"e":5}')) + """) + + try assertEqualSQL( + db, + Database.jsonObject([ + "a": 2, + "c": Database.jsonObject(["e": 5]), + ] as KeyValuePairs), """ + JSON_OBJECT('a', 2, 'c', JSON_OBJECT('e', 5)) + """) + + try assertEqualSQL( + db, + Database.jsonObject([ + "a": 2, + "c": Database.json(#"{"e":5}"#), + ] as KeyValuePairs), """ + JSON_OBJECT('a', 2, 'c', JSON('{"e":5}')) + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonObject([ + "a": nameColumn, + "c": infoColumn, + ] as KeyValuePairs) + ), """ + SELECT JSON_OBJECT('a', "name", 'c', JSON("info")) FROM "player" + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonObject([ + "a": Database.json(nameColumn), + "c": Database.json(infoColumn), + ] as KeyValuePairs) + ), """ + SELECT JSON_OBJECT('a', JSON("name"), 'c', JSON("info")) FROM "player" + """) + } + } + + func test_Database_jsonPatch() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonPatch(#"{"a":1,"b":2}"#, with: #"{"c":3,"d":4}"#), """ + JSON_PATCH('{"a":1,"b":2}', '{"c":3,"d":4}') + """) + + try assertEqualSQL(db, player.select(Database.jsonPatch(#"{"a":1,"b":2}"#, with: nameColumn)), """ + SELECT JSON_PATCH('{"a":1,"b":2}', "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonPatch(#"{"a":1,"b":2}"#, with: infoColumn)), """ + SELECT JSON_PATCH('{"a":1,"b":2}', "info") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonPatch(nameColumn, with: #"{"c":3,"d":4}"#)), """ + SELECT JSON_PATCH("name", '{"c":3,"d":4}') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonPatch(infoColumn, with: #"{"c":3,"d":4}"#)), """ + SELECT JSON_PATCH("info", '{"c":3,"d":4}') FROM "player" + """) + } + } + + func test_Database_jsonRemove_atPath() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonRemove("[0,1,2,3,4]", atPath: "$[2]"), """ + JSON_REMOVE('[0,1,2,3,4]', '$[2]') + """) + + try assertEqualSQL(db, player.select(Database.jsonRemove(nameColumn, atPath: "$[2]")), """ + SELECT JSON_REMOVE("name", '$[2]') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonRemove("[0,1,2,3,4]", atPath: nameColumn)), """ + SELECT JSON_REMOVE('[0,1,2,3,4]', "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonRemove(infoColumn, atPath: "$[2]")), """ + SELECT JSON_REMOVE("info", '$[2]') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonRemove("[0,1,2,3,4]", atPath: infoColumn)), """ + SELECT JSON_REMOVE('[0,1,2,3,4]', "info") FROM "player" + """) + } + } + + func test_Database_jsonRemove_atPaths() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonRemove("[0,1,2,3,4]", atPaths: ["$[2]", "$[0]"]), """ + JSON_REMOVE('[0,1,2,3,4]', '$[2]', '$[0]') + """) + + try assertEqualSQL(db, player.select(Database.jsonRemove(nameColumn, atPaths: ["$[2]", "$[0]"])), """ + SELECT JSON_REMOVE("name", '$[2]', '$[0]') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonRemove(infoColumn, atPaths: ["$[2]", "$[0]"])), """ + SELECT JSON_REMOVE("info", '$[2]', '$[0]') FROM "player" + """) + } + } + + func test_Database_jsonType() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#), """ + JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}') + """) + + try assertEqualSQL(db, player.select(Database.jsonType(nameColumn)), """ + SELECT JSON_TYPE("name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonType(infoColumn)), """ + SELECT JSON_TYPE("info") FROM "player" + """) + } + } + + func test_Database_jsonType_atPath() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#, atPath: "$.a"), """ + JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}', '$.a') + """) + + try assertEqualSQL(db, player.select(Database.jsonType(nameColumn, atPath: "$.a")), """ + SELECT JSON_TYPE("name", '$.a') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonType(infoColumn, atPath: "$.a")), """ + SELECT JSON_TYPE("info", '$.a') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#, atPath: nameColumn)), """ + SELECT JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}', "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#, atPath: infoColumn)), """ + SELECT JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}', "info") FROM "player" + """) + } + } + + func test_Database_jsonIsValid() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonIsValid(#"{"x":35""#), """ + JSON_VALID('{"x":35"') + """) + + try assertEqualSQL(db, player.select(Database.jsonIsValid(nameColumn)), """ + SELECT JSON_VALID("name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonIsValid(infoColumn)), """ + SELECT JSON_VALID("info") FROM "player" + """) + } + } + + func test_Database_jsonQuote() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonQuote(#"{"e":5}"#), """ + JSON_QUOTE('{"e":5}') + """) + + try assertEqualSQL(db, Database.jsonQuote(#"{"e":5}"#.databaseValue.asJSON), """ + JSON_QUOTE(JSON('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonQuote(Database.json(#"{"e":5}"#)), """ + JSON_QUOTE(JSON('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonQuote(Database.jsonObject(["e": 5])), """ + JSON_QUOTE(JSON_OBJECT('e', 5)) + """) + + try assertEqualSQL(db, player.select(Database.jsonQuote(nameColumn)), """ + SELECT JSON_QUOTE("name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonQuote(infoColumn)), """ + SELECT JSON_QUOTE(JSON("info")) FROM "player" + """) + } + } + + func test_Database_jsonGroupArray() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, player.select(Database.jsonGroupArray(nameColumn)), """ + SELECT JSON_GROUP_ARRAY("name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonGroupArray(infoColumn)), """ + SELECT JSON_GROUP_ARRAY(JSON("info")) FROM "player" + """) + } + } + + func test_Database_jsonGroupObject() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("key", .text) + t.column("value", .jsonText) + } + let player = Table("player") + let keyColumn = Column("key") + let valueColumn = JSONColumn("value") + + try assertEqualSQL(db, player.select(Database.jsonGroupObject(key: keyColumn, value: valueColumn)), """ + SELECT JSON_GROUP_OBJECT("key", JSON("value")) FROM "player" + """) + } + } + + func test_index_and_generated_columns() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.primaryKey("id", .integer) + t.column("address", .jsonText) + t.column("country", .text) + .generatedAs(JSONColumn("address")["country"]) + .indexed() + } + + XCTAssertEqual(Array(sqlQueries.suffix(2)), [ + """ + CREATE TABLE "player" ("id" INTEGER PRIMARY KEY, "address" TEXT, "country" TEXT GENERATED ALWAYS AS ("address" ->> 'country') VIRTUAL) + """, + """ + CREATE INDEX "player_on_country" ON "player"("country") + """, + ]) + + try db.create(index: "player_on_address", on: "player", expressions: [ + JSONColumn("address")["country"], + JSONColumn("address")["city"], + JSONColumn("address")["street"], + ]) + + XCTAssertEqual(lastSQLQuery, """ + CREATE INDEX "player_on_address" ON "player"("address" ->> 'country', "address" ->> 'city', "address" ->> 'street') + """) + + try db.execute(literal: """ + INSERT INTO player VALUES ( + NULL, + '{"street": "Rue de Belleville", "city": "Paris", "country": "France"}' + ) + """) + + try XCTAssertEqual(String.fetchOne(db, sql: "SELECT country FROM player"), "France") + } + } + +// TODO: Enable when those apis are ready. +// func test_ColumnAssignment() throws { +// #if GRDBCUSTOMSQLITE || GRDBCIPHER +// // Prevent SQLCipher failures +// guard sqlite3_libversion_number() >= 3038000 else { +// throw XCTSkip("JSON support is not available") +// } +// #else +// guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else { +// throw XCTSkip("JSON support is not available") +// } +// #endif +// +// try makeDatabaseQueue().inDatabase { db in +// try db.create(table: "player") { t in +// t.column("name", .text) +// t.column("info", .jsonText) +// } +// +// struct Player: TableRecord { } +// +// try Player.updateAll(db, [ +// JSONColumn("info").jsonPatch(with: Database.jsonObject(["city": "Paris"])) +// ]) +// XCTAssertEqual(lastSQLQuery, """ +// UPDATE "player" SET "info" = JSON_PATCH("info", JSON_OBJECT('city', 'Paris')) +// """) +// +// try Player.updateAll(db, [ +// JSONColumn("info").jsonRemove(atPath: "$.country") +// ]) +// print(lastSQLQuery!) +// XCTAssertEqual(lastSQLQuery, """ +// UPDATE "player" SET "info" = JSON_REMOVE("info", '$.country') +// """) +// +// try Player.updateAll(db, [ +// JSONColumn("info").jsonRemove(atPaths: ["$.country", "$.city"]) +// ]) +// print(lastSQLQuery!) +// XCTAssertEqual(lastSQLQuery, """ +// UPDATE "player" SET "info" = JSON_REMOVE("info", '$.country', '$.city') +// """) +// } +// } +} From 908f8b242afb185a951f203c0ace5352a86bc717 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Oct 2023 20:32:36 +0200 Subject: [PATCH 20/24] Prepare documentation for JSON --- GRDB/Documentation.docc/DatabaseSchema.md | 2 +- GRDB/Documentation.docc/GRDB.md | 8 +------- GRDB/Documentation.docc/QueryInterface.md | 14 ++++++++++---- GRDB/QueryInterface/SQL/Column.swift | 17 +++++++++++++++++ GRDB/QueryInterface/SQL/SQLExpression.swift | 11 ----------- 5 files changed, 29 insertions(+), 23 deletions(-) diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index 5e466a204..bef295891 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -24,7 +24,7 @@ When a schema change is not directly supported by SQLite, or not available on th Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below. -When those conventions are not applied, or not applicable, you will have to perform extra configurations. +When those conventions are not applied, or not applicable, you will have to perform extra configurations. ### Table names should be English, singular, and camelCased diff --git a/GRDB/Documentation.docc/GRDB.md b/GRDB/Documentation.docc/GRDB.md index cf3bb29a0..e79c8a527 100644 --- a/GRDB/Documentation.docc/GRDB.md +++ b/GRDB/Documentation.docc/GRDB.md @@ -93,14 +93,8 @@ let players: [Player] = try dbQueue.read { db in - - -### Responding to Database Changes +### Database Tools - - -### Full-Text Search - - - -### Combine Publishers - - ``DatabasePublishers`` diff --git a/GRDB/Documentation.docc/QueryInterface.md b/GRDB/Documentation.docc/QueryInterface.md index 39357bd47..6faeae9a2 100644 --- a/GRDB/Documentation.docc/QueryInterface.md +++ b/GRDB/Documentation.docc/QueryInterface.md @@ -17,16 +17,21 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R - ``PersistableRecord`` - ``TableRecord`` -### Associations +### Expressions -- ``Association`` +- ``Column`` +- ``SQLExpression`` -### Query Interface Requests +### Requests - ``CommonTableExpression`` - ``QueryInterfaceRequest`` - ``Table`` +### Associations + +- ``Association`` + ### Errors - ``RecordError`` @@ -34,9 +39,10 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R ### Supporting Types +- ``ColumnExpression`` - ``DerivableRequest`` - ``SQLExpressible`` - ``SQLSpecificExpressible`` +- ``SQLSubqueryable`` - ``SQLOrderingTerm`` - ``SQLSelectable`` -- ``SQLSubqueryable`` diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index c540eca4d..a81c07d0a 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -27,6 +27,7 @@ public protocol ColumnExpression: SQLSpecificExpressible { } extension ColumnExpression { + /// Returns an SQL column. public var sqlExpression: SQLExpression { .column(name) } @@ -65,11 +66,27 @@ extension ColumnExpression where Self == Column { /// A column in a database table. /// +/// For example: +/// +/// ```swift +/// struct Player: TableRecord { +/// var score: Int +/// } +/// +/// let maximumScore = try dbQueue.read { db in +/// // SELECT MAX(score) FROM player +/// try Player +/// .select(max(Column("score")), as: Int.self) +/// .fetchOne(db) +/// } +/// ``` +/// /// ## Topics /// /// ### Standard Columns /// /// - ``rowID-3bn70`` +/// - ``rank`` /// /// ### Creating A Column /// diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 6545b6aad..b9186c788 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -2001,12 +2001,6 @@ extension SQLExpression { /// A type that can be used as an SQL expression. /// /// Related SQLite documentation -/// -/// ## Topics -/// -/// ### Supporting Type -/// -/// - ``SQLExpression`` public protocol SQLExpressible { /// Returns an SQL expression. var sqlExpression: SQLExpression { get } @@ -2031,11 +2025,6 @@ extension SQLExpressible where Self == Column { /// /// ## Topics /// -/// ### Column Expressions -/// -/// - ``Column`` -/// - ``ColumnExpression`` -/// /// ### Applying a Collation /// /// - ``collating(_:)-2mr78`` From 1f0b52a0122b8f6ddcdf7ab329d50eb01aee96a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Oct 2023 20:34:31 +0200 Subject: [PATCH 21/24] JSON documentation --- GRDB/Documentation.docc/DatabaseSchema.md | 2 + GRDB/Documentation.docc/GRDB.md | 1 + GRDB/Documentation.docc/JSON.md | 151 ++++++++++++++++++++ GRDB/Documentation.docc/QueryInterface.md | 2 + GRDB/JSON/JSONColumn.swift | 75 ++++++++++ GRDB/JSON/SQLJSONExpressible.swift | 103 +++++++++++++ GRDB/QueryInterface/SQL/SQLExpression.swift | 8 +- 7 files changed, 341 insertions(+), 1 deletion(-) create mode 100644 GRDB/Documentation.docc/JSON.md diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index bef295891..10cfc3c9f 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -26,6 +26,8 @@ Even though all schema are supported, some features of the library and of the Sw When those conventions are not applied, or not applicable, you will have to perform extra configurations. +For recommendations specific to JSON columns, see . + ### Table names should be English, singular, and camelCased Make them look like singular Swift identifiers: `player`, `team`, `postalAddress`: diff --git a/GRDB/Documentation.docc/GRDB.md b/GRDB/Documentation.docc/GRDB.md index e79c8a527..f8e875c70 100644 --- a/GRDB/Documentation.docc/GRDB.md +++ b/GRDB/Documentation.docc/GRDB.md @@ -97,4 +97,5 @@ let players: [Player] = try dbQueue.read { db in - - +- - ``DatabasePublishers`` diff --git a/GRDB/Documentation.docc/JSON.md b/GRDB/Documentation.docc/JSON.md new file mode 100644 index 000000000..cbef77137 --- /dev/null +++ b/GRDB/Documentation.docc/JSON.md @@ -0,0 +1,151 @@ +# JSON Support + +Store and use JSON values in SQLite databases. + +## Overview + +SQLite and GRDB can store and fetch JSON values in database columns. Starting SQLite 3.38.0 (iOS 16+, macOS 13.2+, tvOS 17+, and watchOS 9+), JSON values can be manipulated at the database level. + +## Store and fetch JSON values + +### JSON columns in the database schema + +It is recommended to store JSON values in text columns. In the example below, we create a ``Database/ColumnType/jsonText`` column with ``Database/create(table:options:body:)``: + +```swift +try db.create(table: "player") { t in + t.primaryKey("id", .text) + t.column("name", .text).notNull() + t.column("address", .jsonText).notNull() // A JSON column +} +``` + +> Note: `.jsonText` and `.text` are equivalent, because both build a TEXT column in SQL. Yet the former better describes the intent of the column. +> +> Note: SQLite JSON functions and operators are [documented](https://www.sqlite.org/json1.html#interface_overview) to throw errors if any of their arguments are binary blobs. That's the reason why it is recommended to store JSON as text. + +> Tip: When an application performs queries on values embedded inside JSON columns, indexes can help performance: +> +> ```swift +> // CREATE INDEX "player_on_country" +> // ON "player"("address" ->> 'country') +> try db.create( +> index: "player_on_country", +> on: "player", +> expressions: [ +> JSONColumn("address")["country"], +> ]) +> +> // SELECT * FROM player +> // WHERE "address" ->> 'country' = 'FR' +> let germanPlayers = try Player +> .filter(JSONColumn("address")["country"] == "DE") +> .fetchAll(db) +> ``` + +### Strict and flexible JSON schemas + +[Codable Records](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records) handle both strict and flexible JSON schemas. + +**For strict schemas**, use `Codable` properties. They will be stored as JSON strings in the database: + +```swift +struct Address: Codable { + var street: String + var city: String + var country: String +} + +struct Player: Codable { + var id: String + var name: String + + // Stored as a JSON string + // {"street": "...", "city": "...", "country": "..."} + var address: Address +} + +extension Player: FetchableRecord, PersistableRecord { } +``` + +**For flexible schemas**, use `String` or `Data` properties. + +In the specific case of `Data` properties, it is recommended to store them as text in the database, because SQLite JSON functions and operators are [documented](https://www.sqlite.org/json1.html#interface_overview) to throw errors if any of their arguments are binary blobs. This encoding is automatic with ``DatabaseDataEncodingStrategy/text``: + +```swift +// JSON String property +struct Player: Codable { + var id: String + var name: String + var address: String // JSON string +} + +extension Player: FetchableRecord, PersistableRecord { } + +// JSON Data property, saved as text in the database +struct Team: Codable { + var id: String + var color: String + var info: Data // JSON UTF8 data +} + +extension Team: FetchableRecord, PersistableRecord { + // Support SQLite JSON functions and operators + // by storing JSON data as database text: + static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text +} +``` + +## Manipulate JSON values at the database level + +[SQLite JSON functions and operators](https://www.sqlite.org/json1.html) are available starting SQLite 3.38.0 (iOS 16+, macOS 13.2+, tvOS 17+, and watchOS 9+). + +Functions such as `JSON`, `JSON_EXTRACT`, `JSON_PATCH` and others are available as static methods on `Database`: ``Database/json(_:)``, ``Database/jsonExtract(_:atPath:)``, ``Database/jsonPatch(_:with:)``, etc. + +See the full list below. + +## JSON table-valued functions + +The JSON table-valued functions `json_each` and `json_tree` are not supported. + +## Topics + +### JSON Values + +- ``SQLJSONExpressible`` +- ``JSONColumn`` + +### Access JSON subcomponents, and query JSON values, at the SQL level + +The `->` and `->>` SQL operators are available on the ``SQLJSONExpressible`` protocol. + +- ``Database/jsonArrayLength(_:)`` +- ``Database/jsonArrayLength(_:atPath:)`` +- ``Database/jsonExtract(_:atPath:)`` +- ``Database/jsonExtract(_:atPaths:)`` +- ``Database/jsonType(_:)`` +- ``Database/jsonType(_:atPath:)`` + +### Build new JSON values at the SQL level + +- ``Database/json(_:)`` +- ``Database/jsonArray(_:)-8xxe3`` +- ``Database/jsonArray(_:)-469db`` +- ``Database/jsonObject(_:)`` +- ``Database/jsonQuote(_:)`` +- ``Database/jsonGroupArray(_:)`` +- ``Database/jsonGroupObject(key:value:)`` + +### Modify JSON values at the SQL level + +- ``Database/jsonInsert(_:_:)`` +- ``Database/jsonPatch(_:with:)`` +- ``Database/jsonReplace(_:_:)`` +- ``Database/jsonRemove(_:atPath:)`` +- ``Database/jsonRemove(_:atPaths:)`` +- ``Database/jsonSet(_:_:)`` + +### Validate JSON values at the SQL level + +- ``Database/jsonErrorPosition(_:)`` +- ``Database/jsonIsValid(_:)`` diff --git a/GRDB/Documentation.docc/QueryInterface.md b/GRDB/Documentation.docc/QueryInterface.md index 6faeae9a2..f09b20f47 100644 --- a/GRDB/Documentation.docc/QueryInterface.md +++ b/GRDB/Documentation.docc/QueryInterface.md @@ -20,6 +20,7 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R ### Expressions - ``Column`` +- ``JSONColumn`` - ``SQLExpression`` ### Requests @@ -42,6 +43,7 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R - ``ColumnExpression`` - ``DerivableRequest`` - ``SQLExpressible`` +- ``SQLJSONExpressible`` - ``SQLSpecificExpressible`` - ``SQLSubqueryable`` - ``SQLOrderingTerm`` diff --git a/GRDB/JSON/JSONColumn.swift b/GRDB/JSON/JSONColumn.swift index 97faef0a4..6ca345dd7 100644 --- a/GRDB/JSON/JSONColumn.swift +++ b/GRDB/JSON/JSONColumn.swift @@ -1,3 +1,78 @@ +/// A JSON column in a database table. +/// +/// ## Overview +/// +/// `JSONColumn` has benefits over ``Column`` for database columns that +/// contain JSON strings. +/// +/// It behaves like a regular `Column`, with all extra conveniences and +/// behaviors of ``SQLJSONExpressible``. +/// +/// For example, the sample code below directly accesses the "countryCode" +/// key of the "address" JSON column: +/// +/// ```swift +/// struct Player: Codable { +/// var id: Int64 +/// var name: String +/// var address: Address +/// } +/// +/// struct Address: Codable { +/// var street: String +/// var city: String +/// var countryCode: String +/// } +/// +/// extension Player: FetchableRecord, PersistableRecord { +/// enum Columns { +/// static let id = Column(CodingKeys.id) +/// static let name = Column(CodingKeys.name) +/// static let address = JSONColumn(CodingKeys.address) // JSONColumn! +/// } +/// } +/// +/// try dbQueue.write { db in +/// // In a real app, table creation should happen in a migration. +/// try db.create(table: "player") { t in +/// t.autoIncrementedPrimaryKey("id") +/// t.column("name", .text).notNull() +/// t.column("address", .jsonText).notNull() +/// } +/// +/// // Fetch all country codes +/// // SELECT DISTINCT address ->> 'countryCode' FROM player +/// let countryCodes: [String] = try Player +/// .select(Player.Columns.address["countryCode"], as: String.self) +/// .distinct() +/// .fetchAll(db) +/// } +/// ``` +/// +/// > Tip: When you can not create a `JSONColumn`, you'll get the same +/// > convenient access to JSON subcomponents +/// > with ``SQLSpecificExpressible/asJSON``. +/// > +/// > For example, the above sample can be adapted as below: +/// > +/// > ```swift +/// > extension Player: FetchableRecord, PersistableRecord { +/// > // That's another valid way to define columns. +/// > // But we don't have any JSONColumn this time. +/// > enum Columns: String, ColumnExpression { +/// > case id, name, address +/// > } +/// > } +/// > +/// > try dbQueue.write { db in +/// > // Fetch all country codes +/// > // SELECT DISTINCT address ->> 'countryCode' FROM player +/// > let countryCodes: [String] = try Player +/// > .select(Player.Columns.address.asJSON["countryCode"], as: String.self) +/// > .distinct() +/// > .fetchAll(db) +/// > } +/// > ``` public struct JSONColumn: ColumnExpression, SQLJSONExpressible { public var name: String diff --git a/GRDB/JSON/SQLJSONExpressible.swift b/GRDB/JSON/SQLJSONExpressible.swift index be395be29..fed63174c 100644 --- a/GRDB/JSON/SQLJSONExpressible.swift +++ b/GRDB/JSON/SQLJSONExpressible.swift @@ -1,3 +1,106 @@ +/// A type of SQL expression that is interpreted as a JSON value. +/// +/// ## Overview +/// +/// JSON values that conform to `SQLJSONExpressible` have two purposes: +/// +/// - They provide Swift APIs for accessing their JSON subcomponents at +/// the SQL level. +/// +/// - When used in a JSON-building function such as +/// ``Database/jsonArray(_:)-8xxe3`` or ``Database/jsonObject(_:)``, +/// they are parsed and interpreted as JSON, not as plain strings. +/// +/// To build a JSON value, create a ``JSONColumn``, or call the +/// ``SQLSpecificExpressible/asJSON`` property of any +/// other expression. +/// +/// For example, here are some JSON values: +/// +/// ```swift +/// // JSON columns: +/// JSONColumn("info") +/// Column("info").asJSON +/// +/// // The JSON array [1, 2, 3]: +/// "[1, 2, 3]".databaseValue.asJSON +/// +/// // A JSON value that will trigger a +/// // "malformed JSON" SQLite error when +/// // parsed by SQLite: +/// "{foo".databaseValue.asJSON +/// ``` +/// +/// The expressions below are not JSON values: +/// +/// ```swift +/// // A plain column: +/// Column("info") +/// +/// // Plain strings: +/// "[1, 2, 3]" +/// "{foo" +/// ``` +/// +/// ## Access JSON subcomponents +/// +/// JSON values provide access to the [`->` and `->>` SQL operators](https://www.sqlite.org/json1.html) +/// and other SQLite JSON functions: +/// +/// ```swift +/// let info = JSONColumn("info") +/// +/// // SELECT info ->> 'firstName' FROM player +/// // → 'Arthur' +/// let firstName = try Player +/// .select(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) +/// .fetchOne(db) +/// ``` +/// +/// ## Build JSON objects and arrays from JSON values +/// +/// When used in a JSON-building function such as +/// ``Database/jsonArray(_:)-8xxe3`` or ``Database/jsonObject(_:)-5iswr``, +/// JSON values are parsed and interpreted as JSON, not as plain strings. +/// +/// In the example below, we can see how the `JSONColumn` is interpreted as +/// JSON, while the `Column` with the same name is interpreted as a +/// plain string: +/// +/// ```swift +/// let elements: [any SQLExpressible] = [ +/// JSONColumn("address"), +/// Column("address"), +/// ] +/// +/// let array = Database.jsonArray(elements) +/// +/// // SELECT JSON_ARRAY(JSON(address), address) FROM player +/// // → '[{"country":"FR"},"{\"country\":\"FR\"}"]' +/// // <--- object ---> <------ string ------> +/// let json = try Player +/// .select(array, as: String.self) +/// .fetchOne(db) +/// ``` +/// +/// ## Topics +/// +/// ### Accessing JSON subcomponents +/// +/// - ``subscript(_:)`` +/// - ``jsonExtract(atPath:)`` +/// - ``jsonExtract(atPaths:)`` +/// - ``jsonRepresentation(atPath:)`` +/// +/// ### Supporting Types +/// +/// - ``AnySQLJSONExpressible`` public protocol SQLJSONExpressible: SQLSpecificExpressible { } extension ColumnExpression where Self: SQLJSONExpressible { diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index b9186c788..89b809cbb 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1930,7 +1930,7 @@ extension SQLExpression { /// // info -> 'address' /// DatabaseValue.null /// Database.json("[1, 2, 3]") - /// JSONColumn("info").jsonString(forKey: "address") + /// JSONColumn("info").jsonRepresentation(forKey: "address") /// /// // isJSONValue is false /// // @@ -2032,6 +2032,8 @@ extension SQLExpressible where Self == Column { /// /// ### SQL Functions & Operators /// +/// See also JSON functions in . +/// /// - ``abs(_:)-5l6xp`` /// - ``average(_:)`` /// - ``capitalized`` @@ -2052,6 +2054,10 @@ extension SQLExpressible where Self == Column { /// - ``uppercased`` /// - ``SQLDateModifier`` /// +/// ### Interpreting an expression as JSON +/// +/// - ``asJSON`` +/// /// ### Creating Ordering Terms /// /// - ``asc`` From d64de2bbdb1349ca27a8d0c76fcc9707284b78a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Oct 2023 20:36:00 +0200 Subject: [PATCH 22/24] CHANGELOG --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 474cae004..b85e72fea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -120,6 +120,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: [#1429](https://github.com/groue/GRDB.swift/pull/1429) by [@JhonnyBillM](https://github.com/JhonnyBillM): Allow `DatabaseValueConvertible` types to customize their database JSON format - **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method. +- **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions +- **New**: Codable records can specify coding strategies for their `Data` properties. See [#1436](https://github.com/groue/GRDB.swift/pull/1436) for more information. +- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/json) article provides an overview of JSON handling. ## 6.18.0 From 0eb973b6db5358d426ad706979bf0905ee0db91a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Oct 2023 21:54:07 +0200 Subject: [PATCH 23/24] Record types with an auto-incremented id should avoid the `Identifiable` protocol. --- CHANGELOG.md | 3 ++- GRDB/Documentation.docc/DatabaseSchema.md | 5 ---- .../RecordRecommendedPractices.md | 27 ++++++++++++++++--- GRDB/Documentation.docc/RecordTimestamps.md | 8 +++--- README.md | 22 ++++++++++++++- 5 files changed, 50 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b85e72fea..7f23497cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -119,10 +119,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release - **New**: [#1429](https://github.com/groue/GRDB.swift/pull/1429) by [@JhonnyBillM](https://github.com/JhonnyBillM): Allow `DatabaseValueConvertible` types to customize their database JSON format -- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method. - **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions +- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method. - **New**: Codable records can specify coding strategies for their `Data` properties. See [#1436](https://github.com/groue/GRDB.swift/pull/1436) for more information. - **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/json) article provides an overview of JSON handling. +- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/v6.18.0/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol. ## 6.18.0 diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index 10cfc3c9f..b3f12f73d 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -165,11 +165,6 @@ struct Player: Codable { var score: Int } -extension Player: Identifiable { - // Required because the primary key column is not 'id' - var id: Int64? { rowid } -} - extension Player: FetchableRecord, MutablePersistableRecord { // Required because the primary key // is the hidden rowid column. diff --git a/GRDB/Documentation.docc/RecordRecommendedPractices.md b/GRDB/Documentation.docc/RecordRecommendedPractices.md index a7a0acf31..405bb8735 100644 --- a/GRDB/Documentation.docc/RecordRecommendedPractices.md +++ b/GRDB/Documentation.docc/RecordRecommendedPractices.md @@ -61,16 +61,16 @@ Thanks to this database schema, the application will always process *consistent **Define one record type per database table.** This record type will be responsible for writing in this table. -**Let's start from regular structs** whose properties match the columns in their database table. Those structs conform to the standard [`Identifiable`] protocol because they have an identifier (the primary key). They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows. +**Let's start from regular structs** whose properties match the columns in their database table. They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows. ```swift -struct Author: Codable, Identifiable { +struct Author: Codable { var id: Int64? var name: String var countryCode: String? } -struct Book: Codable, Identifiable { +struct Book: Codable { var id: Int64? var authorId: Int64 var title: String @@ -129,7 +129,7 @@ let books = try dbQueue.read { db in > t.column("countryCode", .text) // Can be NULL > } > -> struct Author: Codable, Identifiable { +> struct Author: Codable { > var id: Int64? > var name: String // Not optional > var countryCode: String? // Optional @@ -150,6 +150,25 @@ let books = try dbQueue.read { db in > try Author.find(db, id: authorID) > } > ``` +> +> Take care that **`Identifiable` is not a good fit for optional ids**. You will frequently meet optional ids for records with auto-incremented ids: +> +> ```swift +> struct Player: Codable { +> var id: Int64? // Optional ids are not suitable for Identifiable +> var name: String +> var score: Int +> } +> +> extension Player: FetchableRecord, MutablePersistableRecord { +> // Update auto-incremented id upon successful insertion +> mutating func didInsert(_ inserted: InsertionSuccess) { +> id = inserted.rowID +> } +> } +> ``` +> +> For more details about auto-incremented ids and `Identifiable`, see [issue #1435](https://github.com/groue/GRDB.swift/issues/1435#issuecomment-1740857712). ### Record Types Hide Intimate Database Details diff --git a/GRDB/Documentation.docc/RecordTimestamps.md b/GRDB/Documentation.docc/RecordTimestamps.md index 8b529912d..44fb2e5e8 100644 --- a/GRDB/Documentation.docc/RecordTimestamps.md +++ b/GRDB/Documentation.docc/RecordTimestamps.md @@ -25,7 +25,7 @@ try db.create(table: "player") { t in t.column("score", .integer).notNull() } -struct Player: Identifiable { +struct Player { var id: Int64? var creationDate: Date? var modificationDate: Date? @@ -156,7 +156,7 @@ When you fetch timestamped records from the database, it may be inconvenient to ```swift let player = try dbQueue.read { db - try Player.find(db, id: 1) + try Player.find(db, key: 1) } player.creationDate // optional 😕 player.modificationDate // optional 😕 @@ -166,7 +166,7 @@ A possible technique is to define two record types: one that deals with players ```swift /// `Player` deals with unsaved players -struct Player: Identifiable { +struct Player { var id: Int64? // optional var creationDate: Date? // optional var modificationDate: Date? // optional @@ -244,7 +244,7 @@ You can copy it in your application, or use it as an inspiration. Not all apps h ```swift // The base Player type - struct Player: Identifiable { + struct Player { var id: Int64? var creationDate: Date? var modificationDate: Date? diff --git a/README.md b/README.md index 53447ca80..0bd1f8456 100644 --- a/README.md +++ b/README.md @@ -2502,7 +2502,7 @@ try Player.deleteAll(db, ids: [1, 2, 3]) > **Note**: `Identifiable` is not available on all application targets, and not all tables have a single-column primary key. GRDB provides other methods that deal with primary and unique keys, but they won't check the type of their arguments: > > ```swift -> // Those methods are not type-checked +> // Available on non-Identifiable types > try Player.fetchOne(db, key: 1) > try Player.fetchOne(db, key: ["email": "arthur@example.com"]) > try Country.fetchAll(db, keys: ["FR", "US"]) @@ -2515,6 +2515,26 @@ try Player.deleteAll(db, ids: [1, 2, 3]) > try Player.deleteAll(db, keys: [1, 2, 3]) > ``` +> **Note**: It is not recommended to use `Identifiable` on record types that use an auto-incremented primary key: +> +> ```swift +> // AVOID declaring Identifiable conformance when key is auto-incremented +> struct Player { +> var id: Int64? // Not an id suitable for Identifiable +> var name: String +> var score: Int +> } +> +> extension Player: FetchableRecord, MutablePersistableRecord { +> // Update auto-incremented id upon successful insertion +> mutating func didInsert(_ inserted: InsertionSuccess) { +> id = inserted.rowID +> } +> } +> ``` +> +> For a detailed rationale, please see [issue #1435](https://github.com/groue/GRDB.swift/issues/1435#issuecomment-1740857712). + Some database tables have a single-column primary key which is not called "id": ```swift From 703e3c2b689ec7dc8bb78762d1888511582b5133 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Oct 2023 22:06:27 +0200 Subject: [PATCH 24/24] v6.19.0 --- CHANGELOG.md | 5 ++++- GRDB.swift.podspec | 2 +- README.md | 2 +- Support/Info.plist | 2 +- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f23497cf..761b2f3ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 6.x Releases +- `6.19.x` Releases - [6.19.0](#6190) - `6.18.x` Releases - [6.18.0](#6180) - `6.17.x` Releases - [6.17.0](#6170) - `6.16.x` Releases - [6.16.0](#6160) @@ -116,7 +117,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- -## Next Release +## 6.19.0 + +Released October 4, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.18.0...v6.19.0) - **New**: [#1429](https://github.com/groue/GRDB.swift/pull/1429) by [@JhonnyBillM](https://github.com/JhonnyBillM): Allow `DatabaseValueConvertible` types to customize their database JSON format - **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 0a43f6275..10db1323c 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '6.18.0' + s.version = '6.19.0' 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 0bd1f8456..21c8cc021 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ CI Status

-**Latest release**: September 1, 2023 • [version 6.18.0](https://github.com/groue/GRDB.swift/tree/v6.18.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) +**Latest release**: October 4, 2023 • [version 6.19.0](https://github.com/groue/GRDB.swift/tree/v6.19.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) **Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+ diff --git a/Support/Info.plist b/Support/Info.plist index 3c0450ca8..1e11afaac 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 6.18.0 + 6.19.0 CFBundleSignature ???? CFBundleVersion