Skip to content

Help with moving Realm object to GRDB object #1830

@ilendemli

Description

@ilendemli

Hey! I am experimenting with moving away from Realm to GRDB and I have some trouble representing an object in GRDB.

I have separated API response models and database models but they have the same structure, having two endpoints that deliver different content but same objects so I represented them like this in Realm:

public final class ResponseObject1: Object {
    public static let id: Int = 1

    @Persisted(primaryKey: true) public var id: Int
    @Persisted public var items: List< ItemObject >
}

public final class ResponseObject2: Object {
    public static let id: Int = 1

    @Persisted(primaryKey: true) public var id: Int
    @Persisted public var items: List< ItemObject >
}

public final class ItemObject: Object {
    @Persisted(primaryKey: true) public var id: String
    @Persisted public var title: String
}

Currently I have done the following for GRDB compatibility:

public struct ResponseObject1: Codable, FetchableRecord, PersistableRecord {
    public static let id: Int = 1

    let id: Int // KEY
    let Items: [ItemObject]
}

public struct ResponseObject2: Codable, FetchableRecord, PersistableRecord {
    public static let id: Int = 1

    let id: Int // KEY
    let Items: [ItemObject]
}

extension ResponseObject1 {
    public static func createTable(using db: Database) throws {
        try db.create(table: databaseTableName) { table in
            table.column("id", .integer).primaryKey(onConflict: .replace)
            table.column("items", .jsonText)
        }
    }
}

Realm does not require for embedded objects to have their own table, but one still can directly get an item by doing object(ItemObject.self, with: primaryKey)
I am not sure if is possible to archive the same with GRDB so I would appreciate some help in this regard.
Currently I am saving the items as jsonText. The idea is to hopefully directly fetch ItemObjects and to delete or update them.
What would you suggest in this case?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions