在ecto迁移中读取html文件

时间:2019-06-04 14:53:55

标签: elixir ecto

我正在尝试从priv/repo/templates中读取一个html文件,并将其作为字符串值插入到表中:

def change do
  consultant_engagement_html = File.read!(Application.app_dir(:enterprise, "priv/repo/templates") <> "/consultant_engagement.html")
  execute "INSERT INTO rapid_contract_templates(name, html, type, inserted_at, updated_at) VALUES('Consultant Engagement', 'consultant_engagement', '#{consultant_engagement_html}', '#{DateTime.utc_now}', '#{DateTime.utc_now}')"
end

但是,运行迁移时出现此错误:

(Postgrex.Error) ERROR 42601 (syntax_error): syntax error at or near "written"

“书面”是在html文件中找到的单词。

1 个答案:

答案 0 :(得分:1)

如果HTML中包含任何单引号,它将使查询中的转义混乱,从而导致语法无效。正确的做法是为此使用适当的Repo API:

MyApp.Repo.query! "INSERT INTO rapid_contract_templates(name, html, type, inserted_at, updated_at) VALUES('Consultant Engagement', 'consultant_engagement', $1, $2, $3)",
                  [consultant_engagement_html, DateTime.utc_now, DateTime.utc_now]

但是通常不建议在迁移过程中执行数据加载,因为这些是独立的问题。也许使用种子文件(如果使用的是Phoenix,则包括其中的文件)会是更好的方法?