Using AnyJSON #1811
Replies: 1 comment 4 replies
-
Hello @Artem-Viveritsa, To refresh my ideas, I read the JSON Support article in GRDB doc. You're describing what this document calls a "flexible schema" (it is not fixed, but controlled by the remote service). So I'd suggest: Store the JSON as JSON text in the database. JSON blobs are supposed to be JSONB (not the same format as in PostgreSQL), but not all versions of SQLite have support for JSONB. Sticking to JSON text is good enough: try db.create(table: "myRecord") { t in
t.primaryKey("id", .text)
t.column("info", .jsonText).notNull() // A JSON column
} Expose this JSON as a struct MyRecord: Codable {
var id: String
var info: Data // JSON UTF8 data
}
extension MyRecord: FetchableRecord, PersistableRecord {
static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy {
.text
}
} Finally, only perform conversions from this // There's no need to decode JSON in this scenario,
// so we should not spend CPU cycles decoding JSON:
let myRecord = try MyRecord.find(db, id: "42")
try myRecord.delete(db) -- That's my two cents. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi! I have a remote postgres with which I synchronize GRDB for each user. One of the columns is of type jsonb with completely different data. There can be both json objects and just values at the top level without keys.
The AnyJSON code from the Supabase client was perfect for working with such data:
AnyJSON.swift
My question is, what is the most correct way from the point of view of the GRDB architecture to save and read this data locally? String or data? Where is the best place to convert them from AnyJSON to something more suitable? Search or filtering by this field is not supposed.
There are options for writing initializers from Row, encoders and decoders, DatabaseValueConvertible for this column and several more. In general, what is the most competent approach?
Beta Was this translation helpful? Give feedback.
All reactions