-
I went through the trouble of modeling a fairly complex API that a lot of reliance on enums with associated values (“union types” as we like to say in Typescript). I wasn’t thinking very hard about data persistence and am now learning that SwiftData doesn't even support these, so before I do a huge refactor, I wanted to investigate alternatives. (also I really really like writing SQL, so GRDB looks right up my alley) This is an example of the sort of record I'm dealing with. Can anyone tell me if recording and retrieving this in GRDB is relatively straightforward?
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hello @EricWVGG,
It is straightforward if the involved types conform to the standard In this case, struct Post: Codable {
var postId: String
var user: User // User is Codable
var date: Date
var text: String
var embed: Embed // Embed is Codable
}
enum Embed: Codable {
case image (EmbeddedImage) // EmbeddedImage is Codable
case video (EmbeddedVideo) // EmbeddedVideo is Codable
} If users should be stored in their own table, then I suggest you read Recommended Practices for Designing Record Types: // The Post struct for users stored in their own table
struct Post: Codable {
var postId: String
var userId: String // Reference (foreign key) to user
var date: Date
var text: String
var embed: Embed // Still stored as JSON
} If embeds also should be stored in separate table(s), then you'll need to encode the union at the level of the database schema. There are multiple possible solutions. Also note that structs should be preferred to classes, when possible, because you'll be happier that way. GRDB does not force records to come to life with all their associated records up and ready. For example, when you want to fetch posts with their users, you'll rather fetch dedicated types, suited to your needs, such as: struct PostWithUser {
var post: Post
var user: User
}
struct UserWithPosts {
var user: User
var posts: [Post]
}
struct UserWithPostCount {
var user: User
var postCount: Int
} See again the "Recommended Practices" linked above for more information. |
Beta Was this translation helpful? Give feedback.
Hello @EricWVGG,
It is straightforward if the involved types conform to the standard
Codable
protocol. See Codable Records.In this case,
user
andembed
will be stored as JSON in the database (not in their own tables):If users should be stored in their own table, then I suggest you read Recommended Practic…