JSONColumn

A JSON column in a database table.

JSONColumn.swift:76
struct JSONColumn

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:

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)
}