Are rake db:create and rake db:migrate idempotent?

rails-migrations, rake, ruby-on-rails

Solution

Yes, they are idempotent and running those two commands should just bring your DB "up-to-date", and once you've running them through to completion, then running them again subsequently should do nothing.

However, a better way to set up a brand new machine is to use

rake db:setup

`db:setup` just runs these tasks in order:

db:create
db:schema:load
db:seed

Notice `db:setup` does not run `db:migrate`, and instead simply runs `db:schema:load`. Migrations are only required when you are upgrading an existing DB to a newer version, since they describe the differences between two versions of your schema. But when you're setting up a new DB entirely, you can skip the whole history of migrations and jump to the most recent state of the schema, i.e., load the current schema with `db:schema:load`. And `db:seed` runs your `db/seeds.rb` file for creating initial data, if relevant to your application.

Run `rake -T` to describe all the Rails Rake tasks in detail, or view the ActiveRecord `databases.rake` source file to read the code directly.

Problem

I'm new to Rails and I'm trying to figure out if `rake db:create` and `rake db:migrate` are idempotent. In other words, can I run these two commands against my DB (postgres or mysql) repeatedly without causing problems? The idea is to automate the Rails deployment, and have these commands run every time the Rails app is deployed. I'd like to make sure that it doesn't hork the database somehow. Any other gotchas around the idempotence of rake db migrations is super appreciated.

Original source