Tagged Union in a Relational Database

really specific question, how does one represent a tagged union in a relational database? take the following typescript type as an example:
type TaggedUnionTable = {
id: string;
} & (
| {
type: 'tag_a';
specific_info_to_tag_a: object;
}
| {
type: 'tag_b';
specific_info_to_tag_b: object;
}
);
type TaggedUnionTable = {
id: string;
} & (
| {
type: 'tag_a';
specific_info_to_tag_a: object;
}
| {
type: 'tag_b';
specific_info_to_tag_b: object;
}
);
I implemented it in postgresql using jsonb type, but there has to be a better option. (answer with sql pls)
3 Replies
🟠 CHANCE
🟠 CHANCEβ€’7mo ago
Following β€” I too ended up going the json route and am still convinced there has to be a better way
Keef
Keefβ€’7mo ago
I generally just use jsonb and when i decode I handle the type narrowing. Serde has some nice handling around it in rust but in typescript I just do the usual if tag .... This looks like a good read as well: https://www.parsonsmatt.org/2019/03/19/sum_types_in_sql.html
Sum Types In SQL
Algebraic datatypes are a powerful feature of functional programming languages.By combining the expressive power of β€œand” and β€œor,” we can solve all kinds of...
Keef
Keefβ€’7mo ago
enugu
Any idea of how to implement tagged unions in Postgres. For example, Tree a = Leaf a | Branch (Tree a, Tree a)This is one data type feature which would be great to have. I know you can create separate tables for each option in the type and use an id, but is a direct type implementation possible?Dont need polymorphism(say a = String). Even a non ...
Hacker News