DEV Community

Marcøs
Marcøs

Posted on • Edited on

2 2

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay