Upload
denys-kurets
View
346
Download
1
Embed Size (px)
Citation preview
Database migrations in Rails
Denys Kurets
Agenda
- What are database migrations;
- Database migrations in Rails;
- Best practices;
What are database migrations?
In software engineering, schema migration (also database migration, database change
management) refers to the management of incremental, reversible changes to
relational database schemas. A schema migration is performed on a database
whenever it is necessary to update or revert that database's schema to some newer or
older version.
© Wikipedia
Migrations are a feature of Active Record that allows you to evolve your database schema over time.
Rather than write schema modifications in pure SQL, migrations allow you to use an easy Ruby DSL to
describe changes to your tables.
What are database migrations?
Flow:
• Use Ruby code (Database independent);
• Run rake task;
• Other developer run rake task;
• Run rake task during deploy
Database migrations in Rails
Database migrations in Rails
Migration are classes:
Database migrations in Rails
• Database independent way;
• db/migrate - directory;
• YYYYMMDDHHMMSS_add_details_to_products.rb;
• Execute method allows you to execute arbitrary SQL;
• Migrations are wrapped in transaction(PostgreSQL or r SQLite3, not support
MySQL*);
* stackoverflow
Database migrations in Rails
rails g model Product name:string description:text
rails g scaffold Product name:string description:text
rails g migration AddShortToProducts short:text
rails g migration RemoveShortFromProducts short:text
To create migration files:
Database migrations in Rails
Add and Remove Columns:
• AddXXXtoYYY
• RemoveXXXFromYYY
rails g migration AddShortToProducts short:text
rails g migration RemoveShortFromProducts short:text
create_table
Methods for db structure changing
create_table :friends do |t| t.string :first_name t.string :last_name t.string :email t.timestampsend
change_table
change_table :friends do |t| t.remove :last_name, :first_name t.string :phone_number t.index :phone_numberend
add_column
change_column :friends, :last_name, :string
change_column
add_column :friends, :first_name, :stringadd_column :friends, :last_name, :integer
Methods for db structure changing
remove_column :friends, :surname
remove_column
rename_column :friends, :last_name, :surname
rename_column
remove_index :friends, :email
remove_index
add_index :friends, :email
drop_table :friends
add_index
drop_table
add_foreign_key :articles, :authors
add_foreign_key & remove_foreign_key
● :binary● :boolean● :date● :datetime● :decimal● :float
Column Types:
Database migrations in Rails
● :integer● :primary_key● :string● :text● :time● :timestamp● :references
Change method● add_column
● add_foreign_key
● add_index
● add_reference
● add_timestamps
● change_column_default
● change_column_null
● create_join_table
● create_table
● disable_extension
● drop_join_table
● drop_table
● enable_extension
● remove_column
● remove_foreign_key
● remove_index
● remove_reference
● remove_timestamps
● rename_column
● rename_index
● rename_table
class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.string :name t.text :description
t.timestamps null: false end endend
Up and Down methods
Database migrations in Railsrake db:migrate #up
rake db:rollback #down
rake db:migrate:status
rake db:version #current actual migration version
rake db:migrate VERSION=20151117195012 #migrate to version
rake db:migrate:up VERSION=20151117195012 #migrate specific
rake db:migrate:down VERSION=20151117195012 #migrate specific
rake db:migrate:redo VERSION=20151117195012 #migrate down and up
rake db:rollback STEP=3 #revert last 3 migrations
rake db:migrate RAILS_ENV=test #run in test environment
More commands:
Database migrations in Rails (How it works?)
Database migrations in Rails
rake db:migrate:down VERSION=20150321134933
rake db:rollback
rake db:migrate
rake db:rollback STEP=3
rake db:migrate VERSION=20151124211406
rake db:migrate:up VERSION=20151124211419
Database migrations in Rails
Init app database:
Database migrations in Rails
rake db:setup
1. db:create2. db:schema:load3. db:seed
rake db:reset
1. db:drop2. db:setup
db/schema.rb:
• “...schema dumps are the authoritative source for your database schema... ”
• “...two ways to dump the schema… This is set in config/application.rb by the config.
active_record.schema_format setting, which may be either :sql or :ruby”
Database migrations in Rails
rake db:schema:dump #called by db:migrate
rake db:schema:load
Output of migrations:• suppress_messages - Takes a block as an argument and suppresses any output
generated by the block.
• say - Takes a message argument and outputs it as is. A second boolean argument
can be passed to specify whether to indent or not.
• say_with_time - Outputs text along with how long it took to run its block. If the
block returns an integer it assumes it is the number of rows affected.
Database migrations in Rails
Best practices
• “...developers should not be afraid to clear out the old migrations directory, dump a new schema, and continue on from there...”;
• Never have data only migrations, or migration that change existing data;• Keep the schema.rb (or structure.sql) under version control;• Use rake db:schema:load instead of rake db:migrate to initialize an empty
database;• When writing constructive migrations (adding tables or columns), use the change
method instead of up and down methods;• Enforce default values in the migrations themselves instead of in the application
layer;• Atomic changes;
References
1. https://en.wikipedia.org/wiki/Schema_migration
2. http://edgeguides.rubyonrails.org/active_record_migrations.html
3. https://github.com/bbatsov/rails-style-guide#migrations
4. http://stackoverflow.com/questions/10301794/difference-between-rake-dbmigrate-dbreset-and-dbschemaload
5. http://stackoverflow.com/questions/9884429/rails-what-does-schema-rb-do
6. http://stackoverflow.com/questions/686852/rolling-back-a-failed-rails-migration
7. http://www.slideshare.net/seapy/rails-database-migrations-rorlab-season-33
8. http://kottans.org/ruby-slides/public/models/#migrations-topic
9. https://gist.github.com/pyk/8569812
10. http://www.toptal.com/ruby-on-rails/top-10-mistakes-that-rails-programmers-make
11. https://robots.thoughtbot.com/referential-integrity-with-foreign-keys
12. https://www.google.com.ua/
13. http://selectedproblems.blogspot.com/2011/09/rails-migrations-best-practices.html
"the only stupid question is the one that isn't asked"
Thank you!