Elixir’s Ecto ORM is great, but sometimes I find myself missing the
schema.rb from Rails. It’s handy to crack open
schema.rb to really see what’s going on in the database. It’s a bigger part of my workflow than I realized. Ecto doesn’t give you quite the same functionality right out of the box, but I’ve found a way to get pretty close.
Ecto 2.0 provides us with a dump task which can be run using
mix ecto.dump. This will generate a
structure.sql file in
./priv/repo/ containing a
SQL representation of your database’s current schema.
Definitely closer. We can commit this
structure.sql, but now every time we migrate or rollback the database we’ll have to remember to run
mix ecto.dump to keep it up to date. If only there was a sub-header that could tell us how to improve this situation…
Integrating Ecto.Dump Into Our Mix Tasks
First, make sure you’re using at least version 2.0 or greater of Ecto (at the time of writing the most recent version was 2.0.0-rc.3). Then in your
mix.exs) add the following to your
"db.migrate": ["ecto.migrate", "ecto.dump"] "db.rollback": ["ecto.rollback", "ecto.dump"]
So now your
aliases function in your
Mixfile should look something like:
defp aliases do ["ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], "db.migrate": ["ecto.migrate", "ecto.dump"], # alias we added "db.rollback": ["ecto.rollback", "ecto.dump"], # alias we added "test": ["ecto.create --quiet", "ecto.migrate", "test"]] end
Now whenever you run
mix db.migrate or
mix db.rollback your
structure.sql will automatically be updated. This is especially handy for making sure that a migration can be rolled back (run the migration,
git diff the
structure.sql to see if we got what we wanted, rollback the migration,
git diff the
structure.sql again to see if it rollback properly).
You could also alias over
ecto.rollback if you’re already used to typing them like so:
"ecto.migrate": ["ecto.migrate", "ecto.dump"] "ecto.rollback": ["ecto.rollback", "ecto.dump"]
That’s all it takes to essentially get a
schema.rb-like file from Rails in your Ecto project and, more importantly, how to get it into your workflow.
DevMynd – custom software development services with practice areas in digital strategy, human-centered design, UI/UX, and mobile and web application development.