Single source of truth with type column and tagged union

I am migrating an existing application to Ash, in my documents table, I used to have a type Ecto.Enum that tells me what document type this is, invoice, credit or delivery. Additionally there is a data column (jsonb) that would have multiple embeds_one with the correct schema depending on the type.

In the conversion the data column was converted to a subtype_of: :union and a :type was injected through a migration as needed for tagged unions.

Now I feel like the information is doubled inside each row, the :type column knows what document type it is, but also the :data map.

Should I consider reworking so all queries that need to know the type should now use the type information from the union?

1 Like

Duplicating data and/or denormalizing data isn’t necessarily a huge problem, but with that said, Ash provides tools to help with this kind of thing. If the type field of the union always equals the type attribute of the resource, you could just remove the type column and say something like

calculate :type, Type, expr(thing[:type])

How that expression look depends on the storage type: Ash.Type.Union — ash v3.5.15

1 Like

Hey @zachdaniel, sorry that I didn’t respond.

I was researching how to turn this whole thing into a union type thing with Claude, but it created a type that converted into different structures and the whole thing became a mess.

I then had it restart and use a real union type, but that requires me to get to the data by using the :value each time, not what I wanted.

So I am currently having it merge all attributes for the different types into a single embedded resource.

Still thanks for taking the time to respond.

Herman

1 Like