SlideShare ist ein Scribd-Unternehmen logo
1 von 26
ROR Lab. Season 2
 - The 5th Round -


Database
Migrations

 September 1st, 2012

   Hyoseong Choi
     ROR Lab.
Migration?


• To change Database
• in Ruby code


                       ROR Lab.
Why?

• In the legacy web development, what if you
  modify a sql statement directly?
 • You should announce your colleagues to
    implement your sql modification.
 • You should remember it in the following
    deployment.


                                      ROR Lab.
Advantages
    Migration          Sqlite3
  Active Record        MySQL
                       Postgres
                       Oracle
  schema_migrations
  $ rake db:migrate
    db/schema.rb


                      ROR Lab.
To Create
    Migration Files

• $ rails generate model Post title:string
• $ rails generate scaffold Post title:string
• $ rails generate migration
  AddContentToPosts content:text



                                         ROR Lab.
g Model | Scaffold
                                                 rails 3.1 ~>
class CreateProducts < ActiveRecord::Migration    class CreateProducts < ActiveRecord::Migration
  def up                                            def change
    create_table :products do |t|                     create_table :products do |t|
      t.string :name                                    t.string :name
      t.text :description                               t.text :description
                                                   
      t.timestamps                                      t.timestamps
    end                                               end
  end                                               end
                                                  end
  def down
    drop_table :products
  end




                                                   add columns or tables

                                                                                        ROR Lab.
g Migration

class AddReceiveNewsletterToUsers < ActiveRecord::Migration
  def up
    change_table :users do |t|
      t.boolean :receive_newsletter, :default => false
    end
    User.update_all ["receive_newsletter = ?", true]
  end
 
  def down
    remove_column :users, :receive_newsletter
  end
end




                                                              ROR Lab.
To Destroy
    Migration Files

• $ rails destroy model Post title:string
• $ rails destroy scaffold Post title:string
• $ rails destroy migration
  AddContentToPosts content:text



                                         ROR Lab.
Rake it~

• $ rake db:migrate        “up” state

• $ rake db:rollback “down” state
• $ rake db:migrate:status
                                ROR Lab.
Rake it~
                                                                     mysql> select * from schema_migrations;

$ rake db:migrate:status                                             +----------------+
                                                                     | version     |
database: medibook_development                                       +----------------+
                                                                     | 20120531061820 |
 Status Migration ID Migration Name                                  | 20120531105534 |
--------------------------------------------------                   | 20120531124444 |
                                                                     | 20120531125446 |
  up    20120531061820 Create users
                                                                     | 20120531133035 |
  up    20120531105534 Rolify create roles                           | 20120601102629 |
  up    20120531124444 Create boards                                 | 20120603223525 |
  up    20120531125446 Create board types                            | 20120603224330 |
  up    20120531133035 Create posts                                  | 20120603224625 |
  up    20120601102629 Create categories                             | 20120604064155 |
  up    20120603223525 Create products                               | 20120604110743 |
                                                                     | 20120702123904 |
  up    20120603224330 Add some fields to users
                                                                     | 20120702125358 |
  up    20120603224625 Add some fields to categories                  | 20120703005951 |
  up    20120604064155 Add category id to products                   | 20120704033651 |
  up    20120604110743 Add attachment product photo to products      | 20120728014210 |
  up    20120702123904 Add view count to products                    | 20120728061841 |
  up    20120702125358 Create comments                               | 20120728102213 |
  up    20120703005951 Create favourites                             | 20120729053924 |
  up    20120704033651 Add account to users                          | 20120804011723 |
                                                                     | 20120804012821 |
  up    20120728014210 Add devise to users
                                                                     | 20120804013538 |
  up    20120728061841 Remove password digest from users             | 20120808023400 |
  up    20120728102213 Create user groups                            | 20120810071351 |
  up    20120729053924 Create users groups                           +----------------+
  up    20120804011723 Add user details to users                     34 rows in set (0.00 sec)
  up    20120804012821 Create affiliations
  up    20120804013538 Add some fields to affiliations
  up    20120808023400 Add attachment company logo to affiliations
  up    20120810071351 Add active to users

                                                                                         ROR Lab.
A Migration File

 CreateProducts Class
✴20080906120000_create_products.rb
 AddDetailToProducts Class
✴20080906120001_add_details_to_prod
 ucts.rb


                              ROR Lab.
schema_migrations
• db/schema.rb
• A database table : history of migrations

                     $ rake db:migrate:status
                        • up
                        • down

                                        ROR Lab.
Up & Down Methods (1)
 class CreateProducts < ActiveRecord::Migration
   def up
     create_table :products do |t|
       t.string :name
       t.text :description
  
       t.timestamps
     end
   end
  
   def down
     drop_table :products
   end
 end




                                                  ROR Lab.
Up & Down Methods (2)
 class AddReceiveNewsletterToUsers < ActiveRecord::Migration
   def up
     change_table :users do |t|
       t.boolean :receive_newsletter, :default => false
     end
     User.update_all ["receive_newsletter = ?", true]
   end
  
   def down
     remove_column :users, :receive_newsletter
   end
 end




                                                               ROR Lab.
Up & Down Methods (3)
  class ExampleMigration < ActiveRecord::Migration
    def up
      create_table :products do |t|
        t.references :category
      end
      #add a foreign key
      execute <<-SQL
        ALTER TABLE products
          ADD CONSTRAINT fk_products_categories
          FOREIGN KEY (category_id)
          REFERENCES categories(id)
      SQL
      add_column :users, :home_page_url, :string
      rename_column :users, :email, :email_address
    end
   
    def down
      rename_column :users, :email_address, :email
      remove_column :users, :home_page_url
      execute <<-SQL
        ALTER TABLE products
          DROP FOREIGN KEY fk_products_categories
      SQL
      drop_table :products
    end
  end




                                                     ROR Lab.
Up & Down Methods (3)
  class ExampleMigration < ActiveRecord::Migration
    def up
      create_table :products do |t|
        t.references :category
      end
      #add a foreign key
      execute <<-SQL
        ALTER TABLE products
          ADD CONSTRAINT fk_products_categories
          FOREIGN KEY (category_id)
          REFERENCES categories(id)
      SQL
      add_column :users, :home_page_url, :string
      rename_column :users, :email, :email_address
    end
   
    def down
      rename_column :users, :email_address, :email
      remove_column :users, :home_page_url
      execute <<-SQL
        ALTER TABLE products
          DROP FOREIGN KEY fk_products_categories
      SQL
      drop_table :products
    end
  end




                                                     ROR Lab.
Change Method
class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name                         • create_table
      t.text :description                    • add_column
                                             • add_index
      t.timestamps                           • rename_table
    end                                      • rename_column
  end                                        • rename_index
end
                                             • add_timestamps
                                             • remove_timestamps




                                                        ROR Lab.
Running Migrations
                                                       db/schema.rb



                                   db:schema:dump
  UP
       $ rake db:migrate
       $ rake db:migrate VERSION=20090906120000
       $ rake db:migrate:up VERSION=20090906120000

DOWN
       $ rake db:rollback
       $ rake db:rollback STEP=3
       $ rake db:migrate:redo STEP=3




                                                     ROR Lab.
Running Migrations
                                                     database: medibook_development

                                                      Status Migration ID
                                                     --------------------------
                                                       up    20120531061820

UP                                                     up
                                                       up
                                                             20120531105534
                                                             20120531124444
                                                       up    20120531125446
     $ rake db:migrate                                 up    20120531133035
                                                       up    20120601102629
     $ rake db:migrate VERSION=20120702125358          up    20120603223525
                                                       up    20120603224330
     $ rake db:migrate:down VERSION=20120702125358     up    20120603224625
                                                       up    20120604064155
                                                       up    20120604110743
                                                       up    20120702123904
                                                       up    20120702125358
                                                       up    20120703005951
                                                       up    20120704033651
                                                       up    20120728014210
                                                       up    20120728061841
                                                       up    20120728102213
                                                       up    20120729053924
                                                       up    20120804011723

            db:migrate:down                            up
                                                       up
                                                             20120804012821
                                                             20120804013538
                                                       up    20120808023400
                                                       up    20120810071351




                                                                        ROR Lab.
Running Migrations
                                                   database: medibook_development

                                                    Status Migration ID
                                                   --------------------------
                                                     up    20120531061820

UP                                                   up
                                                     up
                                                           20120531105534
                                                           20120531124444
                                                     up    20120531125446
     $ rake db:migrate                               up    20120531133035
                                                     up    20120601102629
     $ rake db:migrate VERSION=20120702125358        up    20120603223525
                                                     down 20120603224330
     $ rake db:migrate:up VERSION=20120702125358     down 20120603224625
                                                     down 20120604064155
                                                     down 20120604110743
                                                     down 20120702123904
                                                     down 20120702125358
                                                     down 20120703005951
                                                     down 20120704033651
                                                     down 20120728014210
                                                     down 20120728061841
                                                     down 20120728102213
                                                     down 20120729053924
                                                     down 20120804011723

                   db:migrate:up                     down 20120804012821
                                                     down 20120804013538
                                                     down 20120808023400
                                                     down 20120810071351




                                                                      ROR Lab.
Running Migrations
                                     database: medibook_development

                                      Status Migration ID
                                     --------------------------
                                       up    20120531061820

UP   $ rake db:rollback
                                       up
                                       up
                                             20120531105534
                                             20120531124444
                                       up    20120531125446
     $ rake db:migrate:redo            up    20120531133035
                                       up    20120601102629
     $ rake db:rollback STEP=3         up    20120603223525
                                       up    20120603224330
     $ rake db:migrate:redo STEP=3     up    20120603224625
                                       up    20120604064155
                                       up    20120604110743
                                       up    20120702123904
                                       up    20120702125358
                                       up    20120703005951
                                       up    20120704033651
                                       up    20120728014210
                                       up    20120728061841
                                       up    20120728102213
                                       up    20120729053924
                                       up    20120804011723

              db:migrate:down          up
                                       up
                                             20120804012821
                                             20120804013538
                                       up    20120808023400
                                       up    20120810071351




                                                        ROR Lab.
App DB Init
                    using db/schema.rb

$ rake db:setup                                $ rake db:reset
1. db:create                                     1. db:drop
2. db:schema:load                                2. db:setup
3. db:seed

    https://github.com/rails/rails/commit/983815632cc1d316c7c803a47be28f1abe6698fb



                                                                               ROR Lab.
Add & Remove
     Columns
• AddXXXToYYY
• RemoveXXXFromYYY
$ rails g migration AddNameToUsers
$ rails g migration RemoveNameFromUsers


                                 ROR Lab.
Model in Migration
• YourTable.reset_column_information
   # db/migrate/20100513121110_add_flag_to_product.rb
    
   class AddFlagToProduct < ActiveRecord::Migration
     class Product < ActiveRecord::Base
     end
    
     def change
       add_column :products, :flag, :integer
       Product.reset_column_information
       Product.all.each do |product|
         product.update_attributes!(:flag => false)
       end
     end
   end




• Alice and Bob’s Story
                                                       ROR Lab.
Schema works

• $ rake db:schema:dump
    called by db:migrate
    create schema.rb


• $ rake db:schema:load
    load schema.rb


                           ROR Lab.
감사합니다.

Weitere ähnliche Inhalte

Ähnlich wie Rails Database Migration, Season 2

Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails Mohit Jain
 
Incremental View Maintenance with Coral, DBT, and Iceberg
Incremental View Maintenance with Coral, DBT, and IcebergIncremental View Maintenance with Coral, DBT, and Iceberg
Incremental View Maintenance with Coral, DBT, and IcebergWalaa Eldin Moustafa
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelpauldix
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelpauldix
 
Tableau course curriculum
Tableau course curriculumTableau course curriculum
Tableau course curriculumMadhukar Reddy
 
Dexterity in the Wild
Dexterity in the WildDexterity in the Wild
Dexterity in the WildDavid Glick
 
Mercury Testdirector8.0 Admin Slides
Mercury Testdirector8.0 Admin SlidesMercury Testdirector8.0 Admin Slides
Mercury Testdirector8.0 Admin Slidestelab
 
Rails DB migrations
Rails DB migrationsRails DB migrations
Rails DB migrationsDenys Kurets
 
Profiling Mondrian MDX Requests in a Production Environment
Profiling Mondrian MDX Requests in a Production EnvironmentProfiling Mondrian MDX Requests in a Production Environment
Profiling Mondrian MDX Requests in a Production EnvironmentRaimonds Simanovskis
 
Vendor session myFMbutler DoSQL 2
Vendor session myFMbutler DoSQL 2Vendor session myFMbutler DoSQL 2
Vendor session myFMbutler DoSQL 2Koen Van Hulle
 
Library management system
Library management systemLibrary management system
Library management systemsiddiqui241993
 
Liquibase & Flyway @ Baltic DevOps
Liquibase & Flyway @ Baltic DevOpsLiquibase & Flyway @ Baltic DevOps
Liquibase & Flyway @ Baltic DevOpsAndrei Solntsev
 
PgConf US 2015 - ALTER DATABASE ADD more SANITY
PgConf US 2015  - ALTER DATABASE ADD more SANITYPgConf US 2015  - ALTER DATABASE ADD more SANITY
PgConf US 2015 - ALTER DATABASE ADD more SANITYOleksii Kliukin
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weiboshaokun
 

Ähnlich wie Rails Database Migration, Season 2 (20)

Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
 
Incremental View Maintenance with Coral, DBT, and Iceberg
Incremental View Maintenance with Coral, DBT, and IcebergIncremental View Maintenance with Coral, DBT, and Iceberg
Incremental View Maintenance with Coral, DBT, and Iceberg
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
 
WOdka
WOdkaWOdka
WOdka
 
Tableau course curriculum
Tableau course curriculumTableau course curriculum
Tableau course curriculum
 
Two database findings
Two database findingsTwo database findings
Two database findings
 
Dexterity in the Wild
Dexterity in the WildDexterity in the Wild
Dexterity in the Wild
 
Mercury Testdirector8.0 Admin Slides
Mercury Testdirector8.0 Admin SlidesMercury Testdirector8.0 Admin Slides
Mercury Testdirector8.0 Admin Slides
 
J query
J queryJ query
J query
 
Rails DB migrations
Rails DB migrationsRails DB migrations
Rails DB migrations
 
Linq to sql
Linq to sqlLinq to sql
Linq to sql
 
Profiling Mondrian MDX Requests in a Production Environment
Profiling Mondrian MDX Requests in a Production EnvironmentProfiling Mondrian MDX Requests in a Production Environment
Profiling Mondrian MDX Requests in a Production Environment
 
Vendor session myFMbutler DoSQL 2
Vendor session myFMbutler DoSQL 2Vendor session myFMbutler DoSQL 2
Vendor session myFMbutler DoSQL 2
 
Library management system
Library management systemLibrary management system
Library management system
 
Liquibase & Flyway @ Baltic DevOps
Liquibase & Flyway @ Baltic DevOpsLiquibase & Flyway @ Baltic DevOps
Liquibase & Flyway @ Baltic DevOps
 
AngularJS
AngularJSAngularJS
AngularJS
 
Intro to Rails 4
Intro to Rails 4Intro to Rails 4
Intro to Rails 4
 
PgConf US 2015 - ALTER DATABASE ADD more SANITY
PgConf US 2015  - ALTER DATABASE ADD more SANITYPgConf US 2015  - ALTER DATABASE ADD more SANITY
PgConf US 2015 - ALTER DATABASE ADD more SANITY
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 

Mehr von RORLAB

Getting Started with Rails (4)
Getting Started with Rails (4) Getting Started with Rails (4)
Getting Started with Rails (4) RORLAB
 
Getting Started with Rails (3)
Getting Started with Rails (3) Getting Started with Rails (3)
Getting Started with Rails (3) RORLAB
 
Getting Started with Rails (2)
Getting Started with Rails (2)Getting Started with Rails (2)
Getting Started with Rails (2)RORLAB
 
Getting Started with Rails (1)
Getting Started with Rails (1)Getting Started with Rails (1)
Getting Started with Rails (1)RORLAB
 
Self join in active record association
Self join in active record associationSelf join in active record association
Self join in active record associationRORLAB
 
Asset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsAsset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsRORLAB
 
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개RORLAB
 
Active Support Core Extension (3)
Active Support Core Extension (3)Active Support Core Extension (3)
Active Support Core Extension (3)RORLAB
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)RORLAB
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)RORLAB
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2RORLAB
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2RORLAB
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2RORLAB
 
Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2RORLAB
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2RORLAB
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2RORLAB
 
Active Record Association (2), Season 2
Active Record Association (2), Season 2Active Record Association (2), Season 2
Active Record Association (2), Season 2RORLAB
 
ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2RORLAB
 
ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2RORLAB
 
ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2RORLAB
 

Mehr von RORLAB (20)

Getting Started with Rails (4)
Getting Started with Rails (4) Getting Started with Rails (4)
Getting Started with Rails (4)
 
Getting Started with Rails (3)
Getting Started with Rails (3) Getting Started with Rails (3)
Getting Started with Rails (3)
 
Getting Started with Rails (2)
Getting Started with Rails (2)Getting Started with Rails (2)
Getting Started with Rails (2)
 
Getting Started with Rails (1)
Getting Started with Rails (1)Getting Started with Rails (1)
Getting Started with Rails (1)
 
Self join in active record association
Self join in active record associationSelf join in active record association
Self join in active record association
 
Asset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsAsset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on Rails
 
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
 
Active Support Core Extension (3)
Active Support Core Extension (3)Active Support Core Extension (3)
Active Support Core Extension (3)
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
 
Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2
 
Active Record Association (2), Season 2
Active Record Association (2), Season 2Active Record Association (2), Season 2
Active Record Association (2), Season 2
 
ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2
 
ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2
 
ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2
 

Kürzlich hochgeladen

Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 

Kürzlich hochgeladen (20)

Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 

Rails Database Migration, Season 2

  • 1. ROR Lab. Season 2 - The 5th Round - Database Migrations September 1st, 2012 Hyoseong Choi ROR Lab.
  • 2. Migration? • To change Database • in Ruby code ROR Lab.
  • 3. Why? • In the legacy web development, what if you modify a sql statement directly? • You should announce your colleagues to implement your sql modification. • You should remember it in the following deployment. ROR Lab.
  • 4. Advantages Migration Sqlite3 Active Record MySQL Postgres Oracle schema_migrations $ rake db:migrate db/schema.rb ROR Lab.
  • 5. To Create Migration Files • $ rails generate model Post title:string • $ rails generate scaffold Post title:string • $ rails generate migration AddContentToPosts content:text ROR Lab.
  • 6. g Model | Scaffold rails 3.1 ~> class CreateProducts < ActiveRecord::Migration class CreateProducts < ActiveRecord::Migration   def up   def change     create_table :products do |t|     create_table :products do |t|       t.string :name       t.string :name       t.text :description       t.text :description           t.timestamps       t.timestamps     end     end   end   end   end   def down     drop_table :products   end add columns or tables ROR Lab.
  • 7. g Migration class AddReceiveNewsletterToUsers < ActiveRecord::Migration   def up     change_table :users do |t|       t.boolean :receive_newsletter, :default => false     end     User.update_all ["receive_newsletter = ?", true]   end     def down     remove_column :users, :receive_newsletter   end end ROR Lab.
  • 8. To Destroy Migration Files • $ rails destroy model Post title:string • $ rails destroy scaffold Post title:string • $ rails destroy migration AddContentToPosts content:text ROR Lab.
  • 9. Rake it~ • $ rake db:migrate “up” state • $ rake db:rollback “down” state • $ rake db:migrate:status ROR Lab.
  • 10. Rake it~ mysql> select * from schema_migrations; $ rake db:migrate:status +----------------+ | version | database: medibook_development +----------------+ | 20120531061820 | Status Migration ID Migration Name | 20120531105534 | -------------------------------------------------- | 20120531124444 | | 20120531125446 | up 20120531061820 Create users | 20120531133035 | up 20120531105534 Rolify create roles | 20120601102629 | up 20120531124444 Create boards | 20120603223525 | up 20120531125446 Create board types | 20120603224330 | up 20120531133035 Create posts | 20120603224625 | up 20120601102629 Create categories | 20120604064155 | up 20120603223525 Create products | 20120604110743 | | 20120702123904 | up 20120603224330 Add some fields to users | 20120702125358 | up 20120603224625 Add some fields to categories | 20120703005951 | up 20120604064155 Add category id to products | 20120704033651 | up 20120604110743 Add attachment product photo to products | 20120728014210 | up 20120702123904 Add view count to products | 20120728061841 | up 20120702125358 Create comments | 20120728102213 | up 20120703005951 Create favourites | 20120729053924 | up 20120704033651 Add account to users | 20120804011723 | | 20120804012821 | up 20120728014210 Add devise to users | 20120804013538 | up 20120728061841 Remove password digest from users | 20120808023400 | up 20120728102213 Create user groups | 20120810071351 | up 20120729053924 Create users groups +----------------+ up 20120804011723 Add user details to users 34 rows in set (0.00 sec) up 20120804012821 Create affiliations up 20120804013538 Add some fields to affiliations up 20120808023400 Add attachment company logo to affiliations up 20120810071351 Add active to users ROR Lab.
  • 11. A Migration File CreateProducts Class ✴20080906120000_create_products.rb AddDetailToProducts Class ✴20080906120001_add_details_to_prod ucts.rb ROR Lab.
  • 12. schema_migrations • db/schema.rb • A database table : history of migrations $ rake db:migrate:status • up • down ROR Lab.
  • 13. Up & Down Methods (1) class CreateProducts < ActiveRecord::Migration   def up     create_table :products do |t|       t.string :name       t.text :description         t.timestamps     end   end     def down     drop_table :products   end end ROR Lab.
  • 14. Up & Down Methods (2) class AddReceiveNewsletterToUsers < ActiveRecord::Migration   def up     change_table :users do |t|       t.boolean :receive_newsletter, :default => false     end     User.update_all ["receive_newsletter = ?", true]   end     def down     remove_column :users, :receive_newsletter   end end ROR Lab.
  • 15. Up & Down Methods (3) class ExampleMigration < ActiveRecord::Migration   def up     create_table :products do |t|       t.references :category     end     #add a foreign key     execute <<-SQL       ALTER TABLE products         ADD CONSTRAINT fk_products_categories         FOREIGN KEY (category_id)         REFERENCES categories(id)     SQL     add_column :users, :home_page_url, :string     rename_column :users, :email, :email_address   end     def down     rename_column :users, :email_address, :email     remove_column :users, :home_page_url     execute <<-SQL       ALTER TABLE products         DROP FOREIGN KEY fk_products_categories     SQL     drop_table :products   end end ROR Lab.
  • 16. Up & Down Methods (3) class ExampleMigration < ActiveRecord::Migration   def up     create_table :products do |t|       t.references :category     end     #add a foreign key     execute <<-SQL       ALTER TABLE products         ADD CONSTRAINT fk_products_categories         FOREIGN KEY (category_id)         REFERENCES categories(id)     SQL     add_column :users, :home_page_url, :string     rename_column :users, :email, :email_address   end     def down     rename_column :users, :email_address, :email     remove_column :users, :home_page_url     execute <<-SQL       ALTER TABLE products         DROP FOREIGN KEY fk_products_categories     SQL     drop_table :products   end end ROR Lab.
  • 17. Change Method class CreateProducts < ActiveRecord::Migration   def change     create_table :products do |t|       t.string :name • create_table       t.text :description • add_column   • add_index       t.timestamps • rename_table     end • rename_column   end • rename_index end • add_timestamps • remove_timestamps ROR Lab.
  • 18. Running Migrations db/schema.rb db:schema:dump UP $ rake db:migrate $ rake db:migrate VERSION=20090906120000 $ rake db:migrate:up VERSION=20090906120000 DOWN $ rake db:rollback $ rake db:rollback STEP=3 $ rake db:migrate:redo STEP=3 ROR Lab.
  • 19. Running Migrations database: medibook_development Status Migration ID -------------------------- up 20120531061820 UP up up 20120531105534 20120531124444 up 20120531125446 $ rake db:migrate up 20120531133035 up 20120601102629 $ rake db:migrate VERSION=20120702125358 up 20120603223525 up 20120603224330 $ rake db:migrate:down VERSION=20120702125358 up 20120603224625 up 20120604064155 up 20120604110743 up 20120702123904 up 20120702125358 up 20120703005951 up 20120704033651 up 20120728014210 up 20120728061841 up 20120728102213 up 20120729053924 up 20120804011723 db:migrate:down up up 20120804012821 20120804013538 up 20120808023400 up 20120810071351 ROR Lab.
  • 20. Running Migrations database: medibook_development Status Migration ID -------------------------- up 20120531061820 UP up up 20120531105534 20120531124444 up 20120531125446 $ rake db:migrate up 20120531133035 up 20120601102629 $ rake db:migrate VERSION=20120702125358 up 20120603223525 down 20120603224330 $ rake db:migrate:up VERSION=20120702125358 down 20120603224625 down 20120604064155 down 20120604110743 down 20120702123904 down 20120702125358 down 20120703005951 down 20120704033651 down 20120728014210 down 20120728061841 down 20120728102213 down 20120729053924 down 20120804011723 db:migrate:up down 20120804012821 down 20120804013538 down 20120808023400 down 20120810071351 ROR Lab.
  • 21. Running Migrations database: medibook_development Status Migration ID -------------------------- up 20120531061820 UP $ rake db:rollback up up 20120531105534 20120531124444 up 20120531125446 $ rake db:migrate:redo up 20120531133035 up 20120601102629 $ rake db:rollback STEP=3 up 20120603223525 up 20120603224330 $ rake db:migrate:redo STEP=3 up 20120603224625 up 20120604064155 up 20120604110743 up 20120702123904 up 20120702125358 up 20120703005951 up 20120704033651 up 20120728014210 up 20120728061841 up 20120728102213 up 20120729053924 up 20120804011723 db:migrate:down up up 20120804012821 20120804013538 up 20120808023400 up 20120810071351 ROR Lab.
  • 22. App DB Init using db/schema.rb $ rake db:setup $ rake db:reset 1. db:create 1. db:drop 2. db:schema:load 2. db:setup 3. db:seed https://github.com/rails/rails/commit/983815632cc1d316c7c803a47be28f1abe6698fb ROR Lab.
  • 23. Add & Remove Columns • AddXXXToYYY • RemoveXXXFromYYY $ rails g migration AddNameToUsers $ rails g migration RemoveNameFromUsers ROR Lab.
  • 24. Model in Migration • YourTable.reset_column_information # db/migrate/20100513121110_add_flag_to_product.rb   class AddFlagToProduct < ActiveRecord::Migration   class Product < ActiveRecord::Base   end     def change     add_column :products, :flag, :integer     Product.reset_column_information     Product.all.each do |product|       product.update_attributes!(:flag => false)     end   end end • Alice and Bob’s Story ROR Lab.
  • 25. Schema works • $ rake db:schema:dump called by db:migrate create schema.rb • $ rake db:schema:load load schema.rb ROR Lab.
  • 27.  

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n