diff --git a/GRDB/JSON/SQLJSONFunctions.swift b/GRDB/JSON/SQLJSONFunctions.swift index 060147ed8..50fc7b29d 100644 --- a/GRDB/JSON/SQLJSONFunctions.swift +++ b/GRDB/JSON/SQLJSONFunctions.swift @@ -341,8 +341,19 @@ extension Database { /// ``` /// /// Related SQLite documentation: - public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression { - .function("JSON_VALID", [value.sqlExpression]) + /// + /// - parameter value: The tested value. + /// - parameter options: See eventual second argument of the + /// `JSON_VALID` function. See . + public static func jsonIsValid( + _ value: some SQLExpressible, + options: JSONValidationOptions? = nil + ) -> SQLExpression { + if let options { + .function("JSON_VALID", [value.sqlExpression, options.rawValue.sqlExpression]) + } else { + .function("JSON_VALID", [value.sqlExpression]) + } } /// The `JSON_QUOTE` SQL function. @@ -425,6 +436,17 @@ extension Database { // MARK: - JSONB extension Database { + public struct JSONValidationOptions: OptionSet, Sendable { + public let rawValue: Int + + public init(rawValue: Int) { self.rawValue = rawValue } + + public static let json = JSONValidationOptions(rawValue: 1) + public static let json5 = JSONValidationOptions(rawValue: 2) + public static let probablyJSONB = JSONValidationOptions(rawValue: 4) + public static let jsonb = JSONValidationOptions(rawValue: 8) + } + /// Validates and returns a binary JSONB representation of the provided /// JSON, with the `JSONB` SQL function. /// diff --git a/Tests/GRDBTests/JSONExpressionsTests.swift b/Tests/GRDBTests/JSONExpressionsTests.swift index 107da0660..796d67fb1 100644 --- a/Tests/GRDBTests/JSONExpressionsTests.swift +++ b/Tests/GRDBTests/JSONExpressionsTests.swift @@ -2077,6 +2077,40 @@ final class JSONExpressionsTests: GRDBTestCase { } } + func test_Database_jsonIsValid_options() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard sqlite3_libversion_number() >= 3045000 else { + throw XCTSkip("JSON_VALID options are not available") + } + + try makeDatabaseQueue().inDatabase { db in + try assertEqualSQL(db, Database.jsonIsValid(#"{"x":35""#, options: .json), """ + JSON_VALID('{"x":35"', 1) + """) + + try assertEqualSQL(db, Database.jsonIsValid(#"{"x":35""#, options: .json5), """ + JSON_VALID('{"x":35"', 2) + """) + + try assertEqualSQL(db, Database.jsonIsValid(#"{"x":35""#, options: .probablyJSONB), """ + JSON_VALID('{"x":35"', 4) + """) + + try assertEqualSQL(db, Database.jsonIsValid(#"{"x":35""#, options: .jsonb), """ + JSON_VALID('{"x":35"', 8) + """) + + try assertEqualSQL(db, Database.jsonIsValid(#"{"x":35""#, options: [.json, .jsonb]), """ + JSON_VALID('{"x":35"', 9) + """) + + } +#else + throw XCTSkip("JSON_VALID options are not available") +#endif + } + func test_Database_jsonQuote() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER // Prevent SQLCipher failures