如何在Ecto迁移中的执行语句中插入Elixir列表?

问题描述

如何执行此迁移:

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

通常,您会执行以下操作:

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

但是如果类型来自可变长度列表怎么办?

解决方法

这是一种(可能很糟糕的)方法:

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

这只是构建字符串。可能有更好的方法,包括将函数传递给execute,如下所示(来自文档):

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

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

如下所示:

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