Bargain23
Bargain23

Reputation: 1973

How to interpolate an Elixir list in an execute statement in Ecto migrations?

How do I perform this migration:

types = ["a", "b", "c"]
execute "UPDATE table SET type='d' WHERE type in #{types}" 

Normally, you would do something like this:

execute "UPDATE table SET type='d' WHERE type in ('a', 'b', 'c')"

but what if the types come from a list of a variable length?

Upvotes: 1

Views: 202

Answers (1)

Peaceful James
Peaceful James

Reputation: 2235

Here is a (probably bad) way of doing it:

types = ["a", "b", "c"]
execute "UPDATE table SET type='d' WHERE type in ('#{Enum.join(types, "', '")}')"

That just builds the string. There is probably a better way, involving passing a function to execute, like this (from the docs):

execute(fn -> repo().query!("select 'Anonymous function query …';", [], [log: :info]) end)

https://hexdocs.pm/ecto_sql/Ecto.Migration.html#execute/1

which would look like:

execute(fn -> repo().query!("update table set type='d' where type = any($1)", [types]) end)

Upvotes: 1

Related Questions