Advanced Migration By Aye Mon Tun
To change database schema in consistent and easy way In ruby code Migration? 11/25/2013 2Web Application Engineering
Database independant Version control No need to memorize SQL modifications Advantages 11/25/2013 3Web Application Engineering
MySQL PostgreSQL SQLite SQL Server Sybase Oracle Database Support 11/25/2013 4Web Application Engineering
To generate migration file with CreateAuthors class which includes name variable with string type. $rails generate model Author name:string $rails generate scaffold Author name:string $rails generate migration CreateAuthors na me:string To generate empty migration file $rails generate migration CreateAuthor How to create Migration File 11/25/2013 5Web Application Engineering
Name By default, Rails generates migrations that look like:Rails e.g _create_authors.rb The prefix is a generation timestamp (in UTC) Place In db/migrate folder You can turn timestamped migrations off by setting: config.active_record.timestamped_migrations = false in application.rb Migration file 11/25/2013 6Web Application Engineering
A migration file is of two forms to change database (to redo and undo). -Using change method Class FileName<AticveRecord::Migration def change end -Using up and down methods Class FileName<AticveRecord::Migration def up end def down end Anatomy of Migration file 11/25/2013 7Web Application Engineering
class CreateAuthors < ActiveRecord::Migration def change create_table :authors do |t| t.string :name t.timestamps end G model/scaffold 11/25/2013 8Web Application Engineering
class CreateAuthors < ActiveRecord::Migration def change create_table :authors do |t| t.string :name end G migration 11/25/2013 9Web Application Engineering
$rails destroy model Author name:string $rails destroy scaffold Author name:string $rails destroy migration CreateAuthors name:string How to destroy migration file 11/25/ Web Application Engineering
To execute database changes or migration files $rake db:migrate To execute a specific migration, use its version with up and down keywords $rake db:migrate:up VERSION= $rake db:migrate:down VERSION= To rollback last database changes $rake db:rollback To redo database changes $rake db:redo To define how many migrations will be redone or rollback, use STEP keyword $rake db:rollback VERSION= $rake db:redo VERSION= To redo or rollback a specific migration, use VERSION keyword $rake db:rollback VERSION= $rake db:redo VERSION= To view the current status of database $rake db:migrate:status Managing migrations 11/25/ Web Application Engineering
It contains the version numbers of all the migrations applied Active Record uses the information to keep track of database changes Schema_migrations Table version (3 rows) 11/25/ Web Application Engineering
1) :binary 2) :boolean 3) :date 4) :datetime 5) :decimal 6) :float 7) :integer 8) :string 9) :time 10) :timestamp Data types support 11/25/ Web Application Engineering
For each type of column :default => value :limit => size :null => true or false :polymorphic => For :decimal type :precision => value :scale => value class CreateShops < ActiveRecord::Migration def change create_table :shops do |t| t.string :name :limit => 20, default => 'Restaurant', :null => false t.decimal :price, :precision => 6, :scale => 2 end Column Type options 11/25/ Web Application Engineering
add_column add_index add_reference add_timestamps create_table create_join_table drop_table (must supply a block) drop_join_table (must supply a block) remove_timestamps rename_column rename_index remove_reference rename_table Available transformations 11/25/ Web Application Engineering
-$rails g migration CreateXXX column list -Use create_table to create a table -Use drop_table to drop table class CreateAuthors < ActiveRecord: : Migration def up create_table :authors do |t| t.string :name end def down drop_table :authors end Table creation and dropping 11/25/ Web Application Engineering
-Use change_table to change an existing table class ChangeAuthors < ActiveRecord: : Migration def change change_table :authors do |t| t.float :income t.change :income, :string t.text :background end Changing Table 11/25/ Web Application Engineering
$ rails g migration CreateJoinTableCustomerProduct customer product class CreateJoinTableCustomerProduct < ActiveRecord::Migration def change create_join_table :customers, :products do |t| t.index [:customer_id, :product_id] t.index [:product_id, :customer_id] end Joining Tables 11/25/ Web Application Engineering
By Default, rails creates tables with default primary key called id. To prevent auto-generated primary key, set id to false create_table :customers, {:id=>false} do |t|... end To define a primary key create_table :customers, {:primary_key=>:customer_id} do |t|... end Overriding Primary Key Setting 11/25/ Web Application Engineering
Use rename_table method Renaming Table 11/25/ Web Application Engineering
$rails g migration AddColumnNameToTableName column:type $rails g migration AddRateToBooks rate:string $rails g migration AddbookToBooks book:integer:index $rails g migrations AddAuthorRefToBooks author:references $rails g migrations RemoveColumnNameFromBooks rate:string $rails g migrations RemoveRateFromBooks rate:string $rails g migrations RemovebookFrombooks book:integer $rails g migrations RemoveAuthorRefFromBooks author:references Adding and removing columns 11/25/ Web Application Engineering
Use reset_column_information to ensure that a model has the latest column data from after a new column was added $rails g migration AddIncomeToAuthors income:integer class AddIncomeToAuthors < ActiveRecord::Migration def up add_column :authors, :income, :integer Author.reset_column_information a=Author.find('Mon Mon') a.update(income: ) end Using a model after changing its table 11/25/ Web Application Engineering
Migration can be used to populate data into database tables $rails g migration CreateBooks name:string class CreateBooks < ActiveRecord: : Migration def up create_table :books do |t| t.string :name :limit => 32, null =>false end Book.create :name => “English” Book.create :name => “Maths” Book.create :name => “Computer Science” end def down drop_table :books end Inializing data in table 11/25/ Web Application Engineering
If the database adapter supports DDL transactions, all migrations will automatically be wrapped in a transaction. There are queries that you can’t execute inside a transaction though, and for these situations you can turn the automatic transactions off. class ChangeColumn < ActiveRecord::Migration disable_ddl_transaction! def up execute "ALTER SEQUENCE name RENAME TO new_name” end Transactional Migrations 11/25/ Web Application Engineering
sometimes you need to do something in SQL not abstracted directly by migrations: Use execute method execute "UPDATE authors SET name='Mon' WHERE name = 'Mon Mon'" How to use SQL 11/25/ Web Application Engineering
Adding and Removing Foreign Key -Includes gem 'foreigner' in GemFile and run bundle install -Use add_foreign_key and remove_foreign_key method in migration file class AddForeignKey < ActiveRecord::Migration def up add_foreign_key :cars, :users end def down remove_foreign_key :cars, :users end 11/25/ Web Application Engineering
class ExampleMigration < ActiveRecord::Migration def change create_table :products do |t| t.references :category end reversible do |dir| dir.up do #add a foreign key execute “ALTER TABLE products ADD CONSTRAINT fk_products_categories FOREIGN KEY (category_id) REFERENCES categories(id)” end dir.down do execute “ALTER TABLE products DROP FOREIGN KEY fk_products_categories” end Adding Foreign Key Constraints 11/25/ Web Application Engineering
Use reversible or revert class ChangeProductsPrice < ActiveRecord::Migration def change reversible do |dir| change_table :products do |t| dir.up { t.change :price, :string } dir.down { t.change :price, :integer } end class ChangeProductsPrice < ActiveRecord::Migration def up change_table :products do |t| t.change :price, :string end Reversible migrations 11/25/ Web Application Engineering
11/25/2013 Web Application Engineering29 def down change_table :products do |t| t.change :price, :integer end #If a command cannot be reversed, an ActiveRecord::IrreversibleMigration exception will be raised when the migration is moving down. (see list of irreversible commands in ActiveRecord::Migration::CommandRecorder.) raise ActiveRecord: :Irresversible Migration Reversible migrations
require_relative ' _example_migration' class FixupExampleMigration < ActiveRecord::Migration def change revert ExampleMigration create_table(:apples) do |t| t.string :variety end 11/25/ Web Application Engineering Reversible migrations
insert your own messages and benchmarks by using the say_with_time method: def up... say_with_time "Updating Author income..." do author=Authors.find_by_name(“Aye Mon Tun”) author.update( end set ActiveRecord::Migration.verbose = false to show no message Controlling Verbosity 11/25/ Web Application Engineering
Use RAILS_ENV variable $rake db:migrate RAILS_ENV=production $rake db:migrate RAILS_ENV=test Running Migration For production and test databases 11/25/ Web Application Engineering
html html migrations/ migrations/ References 11/25/ Web Application Engineering
Any Question? Thank You 11/25/ Web Application Engineering