Across the team we have to sync source of truth about database shape: schema dump file (Either schema.rb or structure.sql).
To generate right schema.rb
we should follow couple rules.
It's seems to be kinda obvious, but it's not well-spread practice.
TIL: use `RAILS_ENV=test rake db:migrate:reset`!
2. Active Record Migrations
• Ruby DSL to maintain schema modi
fi
cations of DB
• DB independent
• Sync state of db across developers
• ...
3.
4. Good habbits during migrations?
Articles focus mostly about performance, reversibility, safetyness
5. The problems
2 concurrently created migrations
• Alice creates new migration adding post.priority,
runs rake db:migrate ,
performs commit with schema.rb and push to github
• Bob creates new migration adding post.deleted_at,
runs rake db:migrate ,
performs commit with schema.rb and push to github
6.
7. The problems
• Alice merges her changes to base branch
• Bob rebases his commit,
runs rake db:migrate (which adds post.priority from Alice).
He performs commit, merge and push to github
8. The problems
• Cycil fetches base branch,
runs rake db:migrate
and has
a di
ff
erent schema.rb order
😡
9. The problems
others
• Some machines has some additional `public.` gen_random_uuid() pre
fi
x
• Migrations before rails upgrade (<5.1) was initially producing integers, but in
schema they are big-int
10. Preconditions to keep schema.rb fine
• working rake db:migrate:reset
• de
fi
ne constrain about db (major) version
11. Quick solution
• on each schema.rb con
fl
ict, regenerate schema again from scratch
• use test schema for that:
RAILS_ENV=test rake db:migrate:reset
• review schema.rb content after migrations if you did not recreate it
• commit schema.rb :D
12. Ensure right schema.rb state on CI
• recreate db on CI tests and raise if schema.rb changed
• it will detect if somebody:
• forgets to commit new migration
fi
le
• forgets to commit new schema.rb changes
• pushes commit with wrong schema.rb state