在 ecto 迁移中读取 html 文件

Reading an html file in an ecto migration

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

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"

"written" 是在 html 文件中找到的一个词。

如果 HTML 中有任何单引号,它会弄乱查询中的转义,导致语法无效。正确的做法是为此使用正确的 Repo API:

MyApp.Repo.query! "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]

但是通常不鼓励在迁移中执行数据加载,因为这些是不同的问题。也许使用种子文件(如果您使用的是 Phoenix,其中包含一个)会是更好的方法吗?