marcandre
Ecto `fragment` with variable column
We have two tables with fields of type :map, which are copied from one to the other. I’d like a generic method that can do a query on one subfield, e.g. something like:
defp with_hierarchical_data(model, field) do
from(pa in model,
select: [:id, ^field],
where: fragment("#{^field}->>'selected_plan' IS NOT NULL")
)
end
I get “to prevent SQL injection attacks, fragment(…) does not allow strings to be interpolated as the first argument via the ^ operator, got: "#{^field}->>'selected_plan' IS NOT NULL"”.
In my case, field is a trusted atom. How can I write this (other than writing two nearly identical functions) / bypass this prevention?
I looked for answers in a similar thread but didn’t see a solution
Marked As Solved
cevado
Also Liked
marcandre
l00ker
Try moving the interpolation outside of from.
defp with_hierarchical_data(model, field) do
fd = "#{field}"
from(pa in model,
select: [:id, ^field],
where: fragment("?->>'selected_plan' IS NOT NULL", ^fd)
)
end
Edit: After thinking about this you may not even need to convert field to a string. Just use the atom and I believe it will convert it for you. The key is that you need to use ? and pass ^field as the 2nd argument to fragment()
defp with_hierarchical_data(model, field) do
from(pa in model,
select: [:id, ^field],
where: fragment("?->>'selected_plan' IS NOT NULL", ^field)
)
end
Last Post!
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
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









