DEV Community

loading...

Elixir - schema drop

Marcøs
Elm/Elixir Developer
Updated on ・1 min read

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"

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}")

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

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

From the shell, you can now run

$ mix ecto.schema.drop

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

  defp aliases do
    [
      "ecto.schema.reset": ["ecto.schema.drop", "ecto.setup"]
    ]
  end

Discussion (0)