Fire-Dragon-DoL
Why Ecto needs explicit casting of types when passing arguments to a query without schema?
Hello,
I’m being curious about why Ecto needs explicit casting when passing arguments to a query. I faced the following situation:
amount = %Amount{value: 1, type: "spa"}
Iris.Repo
|> Ecto.Adapters.SQL.query!("insert into prospect_overview(amount) values ($1)", [amount])
The Amount struct implements the behaviour Ecto.Type.
This example doesn’t work though, it require me to explicitly state the type:
amount = %Amount{value: 1, type: "spa"}
Iris.Repo
|> Ecto.Adapters.SQL.query!("insert into prospect_overview(amount) values ($1)", [type(Amount, amount)])
If amount was one of the basic types (string, integer, binaries, booleans, float and array of basic types), I don’t need to cast, however for everything else I need to.
While it totally make sense when using Ecto.Query DSL, since some things might need conversions (e.g. is_nil(something) becomes IS NULL in SQL, I can’t figure out why this is needed when passing params to a “string-based” query:
The struct can definitely implement some kind of protocol to request “auto casting” to the DB type, the basic types are detectable and covered. Shouldn’t the conversion be possible automatically?
Most Liked
idi527
![]()
I think OP stated that %Amount{} is not necessarily an ecto schema struct, so there is no information about which table to insert it into for Repo.insert to work.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









