sezaru

sezaru

Use Ecto schema directly or convert to a custom struct?

Hello,

I have a question that probably is somewhat opinion-based.

Basically, when you have a schema for some persisted data in your database, do you use it directly in your code or do you convert it to another struct first?

Example

Say, I have a table to store financial data:

schema "candles" do
  field :timestamp, :utc_datetime_usec
  field :open, :decimal
  field :close, :decimal
  field :high, :decimal
  field :low, :decimal
  field :volume, :decimal
end

It’s typespec would be like this:

@type t :: %__MODULE__{
        __meta__: Ecto.Schema.Metadata.t(),
        id: integer | nil,
        timestamp: DateTime.t() | nil,
        open: Decimal.t() | nil,
        close: Decimal.t() | nil,
        high: Decimal.t() | nil,
        low: Decimal.t() | nil,
        volume: Decimal.t() | nil
      }

Normally what I do is create a struct like this in another module:

defmodule Candle do
  defstruct [:timestamp, :open, :close, :high, :low, :volume]
end

And whenever I read from the database, I always convert from the schema to the struct I created, and that struct is what is used in the rest of the program.

Do you think this is necessary or just a waste of CPU cycles? Can you see any advantages/disadvantages from each approach?

Most Liked

Adzz

Adzz

Great question. This is similar to many discussions i’ve had at work in a few teams.

On the surface it seems like that would be extra work for not much gain. Especially as ecto is super flexible, allowing us to define a schema that only use some of the fields on the table, and allowing virtual fields.

However, I too use this approach, with one adjustment; I make the structs embedded schemas so all of them are ecto structs.

Why? So that i have a clear separation between business logic and the database.

I took a while to get used to the approach, it’s not necessary for every application, it adds some overhead.

But if you do it well where the data is stored is an implementation detail, allowing you yo easily pull things out and move them around without touching the domain logic.

I could have domain fields made from several db tables or even from different APIs.

That kind of approach is taking influence from DDD and hexagonal architecture, so could be more pros / cons in that literature.

al2o3cr

al2o3cr

You’ve described what you’re doing, but not why. What advantage were you aiming for when setting up this pattern?

IMO this feels like boilerplate: you’re literally winding up with the same maps modulo a couple keys.

If you were feeling really fancy you could even do it with key-tweaking:

%CandleSchema{timestamp: ..., etc etc}
|> Map.from_struct()
|> Map.drop([:__meta__])
|> struct!(Candle)

Where Next?

Popular in Questions Top

minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
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
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
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
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement