maxim

maxim

Another cast vs dump question for a custom Ecto type

Hi folks,

I’ve written custom types before, but this specific case gives me pause, and I wonder if you could explain your reasoning here when deciding how to split this logic between cast and dump.

I have a list of base-3 integers that I store in the database as a :binary (postgres bytea).

The value that I assign looks like this (up to 127 digits):

[0,2,1,0,2,2,1]

The value database stores looks like this

[0,2,1,0,2,2,1] |> Enum.reverse |> Integer.undigits(3) |> :binary.encode_unsigned
# <<5, 112>>

However, I have to run 3 checks:

  1. Is this a list?
  2. Is length in 0..127
  3. Are all digits in 0..2?

What part of this goes into cast, and what goes into dump?

Here’s what I think, correct me if I’m wrong:

  • Cast runs the above 3 checks, but keeps it a list.
  • Dump ALSO runs the 3 checks (in case value was assigned without cast) but converts it into a binary.

However, those 3 things are quite a bit of code. Between 2 guards and an Enum.any? they traverse the whole list a couple of times. If this is correct, am I supposed ignore the fact that I’m running the same logic twice, once for cast and once for dump?

Marked As Solved

LostKobrakai

LostKobrakai

Ecto.Types handle 3 different data representations. Outside data (most often from form inputs, or json fields in the db), runtime data (how your data is put into your structs by ecto and used at runtime) and the database representations as db column.

cast goes from outside data → runtime data
dump goes from anything (outside data or runtime data) → database column data
load goes from database column data → runtime data

For json (map) fields there’s also
json encoding from anything → database json value
cast from database json value → runtime value

The reason why cast/json encoding need to deal with “anything” is because there’s nobody stopping you from inserting data via Repo.insert_all or manipulating a struct manually and there’s no casting involved. So any validation of correct data needs to be done in both cast and dump, where one converts to runtime data and the other to database column data.

Also Liked

axelson

axelson

Scenic Core Team

I like visuals so I made a visual to represent @LostKobrakai’s awesome explanation:

And one thing that sometimes confuses (me at least) is that sometimes the “Outside data” and “Runtime data” have the same representation, for example for Ecto.UUID. Seeing it in this visual form makes the reason behind that easier for me to understand/remember:

10
Post #6
LostKobrakai

LostKobrakai

Already merged:

NobbZ

NobbZ

I’m not sure where to put the checks, but at least I can tell you that you only need to iterate once, roughly like this:

def valid_custom_type?(list) do
  list
  |> Enum.reduce_while(0, fn
    _d, l when l > 127 ->
      {:halt, :invalid}
    d, _l when d not in 0..2 ->
      {:halt, :invalid}
    _d, l ->
      {:cont, l + 1}
  end)
  |> is_integer()
end

This will iterate not more than once and not more than the first 128 digits of the list.

Due to the early return it should not become a bottleneck that soon.

Where Next?

Popular in Questions Top

vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36820 110
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44265 214
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

We're in Beta

About us Mission Statement