fbpx logo-new mail facebook Dribble Social Icon Linkedin Social Icon Twitter Social Icon Github Social Icon Instagram Social Icon Arrow_element diagonal-decor rectangle-decor search arrow circle-flat
Development

Getting A Schema File From Elixir’s Ecto

Michael Crismali Tandem Alum

last updated April 28, 2016

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.Dump

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

Perfect!

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 Mixfile (mix.exs) add the following to your mix aliases:

"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.migrate and ecto.rollback if you’re already used to typing them like so:

"ecto.migrate": ["ecto.migrate", "ecto.dump"]
"ecto.rollback": ["ecto.rollback", "ecto.dump"]

Conclusion

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.

Tandem – custom software development services with practice areas in digital strategy, human-centered design, UI/UX, and mobile and web application development.

Let’s do something great together

We do our best work in close collaboration with our clients. Let’s find some time for you to chat with a member of our team.

Say Hi