Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Advanced Migration By Aye Mon Tun

2  To change database schema in consistent and easy way  In ruby code Migration? 11/25/2013 2Web Application Engineering

3  Database independant  Version control  No need to memorize SQL modifications Advantages 11/25/2013 3Web Application Engineering

4  MySQL  PostgreSQL  SQLite  SQL Server  Sybase  Oracle Database Support 11/25/2013 4Web Application Engineering

5  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

6  Name  By default, Rails generates migrations that look like:Rails e.g. 20130717013526_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

7  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

8 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

9 class CreateAuthors < ActiveRecord::Migration def change create_table :authors do |t| t.string :name end G migration 11/25/2013 9Web Application Engineering

10  $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/2013 10Web Application Engineering

11  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=20130717013526 $rake db:migrate:down VERSION=20130717013526  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=20130717013526 $rake db:redo VERSION=20130717013526  To redo or rollback a specific migration, use VERSION keyword $rake db:rollback VERSION=20130717013526 $rake db:redo VERSION=20130717013526  To view the current status of database $rake db:migrate:status Managing migrations 11/25/2013 11Web Application Engineering

12  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 ---------------- 20131119193940 20131119194201 20131119220208 (3 rows) 11/25/2013 12Web Application Engineering

13 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/2013 13Web Application Engineering

14  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/2013 14Web Application Engineering

15  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/2013 15Web Application Engineering

16 -$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/2013 16Web Application Engineering

17 -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/2013 17Web Application Engineering

18 $ 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/2013 18Web Application Engineering

19  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/2013 19Web Application Engineering

20  Use rename_table method Renaming Table 11/25/2013 20Web Application Engineering

21  $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/2013 21Web Application Engineering

22  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: 300000) end Using a model after changing its table 11/25/2013 22Web Application Engineering

23  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/2013 23Web Application Engineering

24  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/2013 24Web Application Engineering

25  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/2013 25Web Application Engineering

26 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/2013 26Web Application Engineering

27 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/2013 27Web Application Engineering

28  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/2013 28Web Application Engineering

29 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

30 require_relative '2012121212_example_migration' class FixupExampleMigration < ActiveRecord::Migration def change revert ExampleMigration create_table(:apples) do |t| t.string :variety end 11/25/2013 30Web Application Engineering Reversible migrations

31  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(email: 'mon@gmail.com') end  set ActiveRecord::Migration.verbose = false to show no message Controlling Verbosity 11/25/2013 31Web Application Engineering

32  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/2013 32Web Application Engineering

33 http://api.rubyonrails.org/classes/ActiveRecord/Migration.html http://www.tutorialspoint.com/ruby-on-rails/rails-migrations.htm http://ruby.about.com/od/rubyonrails/a/migrations.htm http://www.oracle.com/technetwork/articles/kern-rails-migrations- 100756.html http://www.oracle.com/technetwork/articles/kern-rails-migrations- 100756.html http://jacqueschirag.wordpress.com/2007/08/12/rants-about-rails-database- migrations/ http://jacqueschirag.wordpress.com/2007/08/12/rants-about-rails-database- migrations/ http://simononsoftware.com/why-ruby-on-rails-migrations-dont-work/ http://en.wikibooks.org/wiki/Ruby_on_Rails/ActiveRecord/Migrations https://www.youtube.com/watch?v=A3G2GTu3P3o https://www.youtube.com/watch?v=kwaeAIamXZ8 https://www.youtube.com/watch?v=CBl8aE6WdxY References 11/25/2013 33Web Application Engineering

34  Any Question? Thank You 11/25/2013 34Web Application Engineering


Download ppt "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."

Similar presentations


Ads by Google