Ecto:每次迁移之前或之后的 运行 sql 脚本

Ecto: run sql script before or after each migration

我想在未来的某个时间为每个月创建(如果不存在)分区表:

execute """
CREATE TABLE IF NOT EXISTS #{table}_p#{start_date.year}_#{month}
PARTITION OF #{table} FOR VALUES
FROM ('#{start_date}')
TO ('#{stop_date}')
"""

我 运行 它是动态的,例如:从今天开始的下一个 12 个月。 我想在迁移期间创建它,但 运行 每次迁移开始时都创建它。我无法使用 Repo,因为在迁移时它尚未开始。我没有找到任何使用 Ecto.Migration api.

的能力

你有什么想法可以实现吗?

我在 ecto 3.5.0 中添加的功能的支持下完成了它。我添加了单独的迁移文件夹,用于所谓的 'repeated_migrations'.

  @doc """
  repeated migrations are run each deploy(e.g: ensure partitions). Repetition achieved by down method that does nothing.
  """
  def run_repeated_migrations do
    for repo <- repos() do
      path = Ecto.Migrator.migrations_path(repo, "repeated_migrations")
      {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, path, :up, all: true))
      {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, path, :down, all: true))
    end
  end

repeated_migrations/20210427134701_partition_creation.exs

中的方法
  def down do
    # to make this migration repeatable we run 'up' following by 'down'. Down do nothing.
    execute "SELECT 1"
  end