DEV Community

Marcøs
Marcøs

Posted on • Updated on

Elixir - schema drop

See Files on Github
config.exs
mix.exs
schema_drop.exs

There may be cases when you share a database (but not a schema) with other applications. So using mix ecto.drop may not be an option. In this case, dropping the schema may be a better alternative.

First configure your ecto migrations settings in config.exs.

config :portishead, Portishead.Repo,
  migration_default_prefix: "portishead",
  migration_source: "portishead_schema_migrations"
Enter fullscreen mode Exit fullscreen mode

Add schema_drop.exs script to the priv/repo folder. The script gets the schema and migration table from the config and runs raw sql to drop them. This script is using PL/pgSQL.

Repo.query!("DROP SCHEMA IF EXISTS #{schema} CASCADE")
Repo.query!("DROP TABLE IF EXISTS #{migration_table}")
Enter fullscreen mode Exit fullscreen mode

In mix.exs, add an alias to drop the schema

  defp aliases do
    [
      "ecto.schema.drop": ["run priv/repo/schema_drop.exs"]
    ]
  end
Enter fullscreen mode Exit fullscreen mode

From the shell, you can now run

$ mix ecto.schema.drop
Enter fullscreen mode Exit fullscreen mode

or you can add an aliases to use ecto.schema.drop

  defp aliases do
    [
      "ecto.schema.reset": ["ecto.schema.drop", "ecto.setup"]
    ]
  end
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)