Reputation: 1973
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
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