JSONColumn and SQLJSONExpressible

This commit is contained in:
Gwendal Roué committed 2023-10-04 19:55:12 +02:00
1 parent ed01d40ba9
commit 546e8aa77c
5 files changed
+373

No files matched your search

+8
View File
@@ -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 = "<group>"; };
560233C82724338800529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = "<group>"; };
5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONFunctions.swift; sourceTree = "<group>"; };
5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONExpressible.swift; sourceTree = "<group>"; };
5603CEB82AC862EC00CF097D /* JSONColumn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumn.swift; sourceTree = "<group>"; };
56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = "<group>"; };
560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = "<group>"; };
5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
@@ -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 */,
+16
View File
@@ -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
}
}
+332
View File
@@ -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: <https://www.sqlite.org/json1.html#jptr>
///
/// - 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: <https://www.sqlite.org/json1.html#jex>
///
/// - 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: <https://www.sqlite.org/json1.html#jex>
///
/// - parameter paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public func jsonExtract<C>(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: <https://www.sqlite.org/json1.html#jptr>
///
/// - 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: <https://www.sqlite.org/json1.html#jptr>
///
/// - 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: <https://www.sqlite.org/json1.html#jex>
///
/// - 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: <https://www.sqlite.org/json1.html#jex>
///
/// - parameter paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public func jsonExtract<C>(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: <https://www.sqlite.org/json1.html#jptr>
///
/// - 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: <https://www.sqlite.org/json1.html#jpatch>
// 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: <https://www.sqlite.org/json1.html#jrm>
// ///
// /// - 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: <https://www.sqlite.org/json1.html#jrm>
// ///
// /// - Parameters:
// /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
// public func jsonRemove<C>(atPaths paths: C)
// -> ColumnAssignment
// where C: Collection, C.Element: SQLExpressible
// {
// .init(columnName: name, value: Database.jsonRemove(self, atPaths: paths))
// }
//
// }
#endif
@@ -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:
+8
View File
@@ -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 = "<group>"; };
560233D027243A9100529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = "<group>"; };
5603CEBF2AC862F800CF097D /* SQLJSONFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONFunctions.swift; sourceTree = "<group>"; };
5603CEC02AC862F800CF097D /* SQLJSONExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONExpressible.swift; sourceTree = "<group>"; };
5603CEC12AC862F800CF097D /* JSONColumn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumn.swift; sourceTree = "<group>"; };
56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = "<group>"; };
560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = "<group>"; };
5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
@@ -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 */,