mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-27 04:14:21 +00:00
JSON documentation
This commit is contained in:
1 parent
908f8b242a
commit
1f0b52a012
7 files changed
+341
-1
No files matched your search
@@ -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 <doc:JSON>.
|
||||
|
||||
### Table names should be English, singular, and camelCased
|
||||
|
||||
Make them look like singular Swift identifiers: `player`, `team`, `postalAddress`:
|
||||
|
||||
@@ -97,4 +97,5 @@ let players: [Player] = try dbQueue.read { db in
|
||||
|
||||
- <doc:DatabaseObservation>
|
||||
- <doc:FullTextSearch>
|
||||
- <doc:JSON>
|
||||
- ``DatabasePublishers``
|
||||
@@ -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(_:)``
|
||||
@@ -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``
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 <doc:JSON>.
|
||||
///
|
||||
/// - ``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``
|
||||
|
||||
Reference in new issue
Block a user