SlideShare a Scribd company logo
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.timestamps
end
change_table
change_table :friends do |t|
t.remove :last_name, :first_name
t.string :phone_number
t.index :phone_number
end
add_column
change_column :friends, :last_name, :string
change_column
add_column :friends, :first_name, :string
add_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
end
end
Up and Down methods
Database migrations in Rails
rake 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:create
2. db:schema:load
3. db:seed
rake db:reset
1. db:drop
2. 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!

More Related Content

What's hot

Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛
Wen-Tien Chang
 
The evolution of Apache Calcite and its Community
The evolution of Apache Calcite and its CommunityThe evolution of Apache Calcite and its Community
The evolution of Apache Calcite and its Community
Julian Hyde
 
Introduction to Docker
Introduction to DockerIntroduction to Docker
Introduction to Docker
Aditya Konarde
 
Securing MongoDB to Serve an AWS-Based, Multi-Tenant, Security-Fanatic SaaS A...
Securing MongoDB to Serve an AWS-Based, Multi-Tenant, Security-Fanatic SaaS A...Securing MongoDB to Serve an AWS-Based, Multi-Tenant, Security-Fanatic SaaS A...
Securing MongoDB to Serve an AWS-Based, Multi-Tenant, Security-Fanatic SaaS A...
MongoDB
 
Maven tutorial
Maven tutorialMaven tutorial
Maven tutorial
Dragos Balan
 
Docker Introduction
Docker IntroductionDocker Introduction
Docker Introduction
Robert Reiz
 
Code Coverage Revised : EclEmma on JaCoCo
Code Coverage Revised : EclEmma on JaCoCoCode Coverage Revised : EclEmma on JaCoCo
Code Coverage Revised : EclEmma on JaCoCo
Evgeny Mandrikov
 
Cloud Native Java GraalVM 이상과 현실
Cloud Native Java GraalVM 이상과 현실Cloud Native Java GraalVM 이상과 현실
Cloud Native Java GraalVM 이상과 현실
Taewan Kim
 
RSpec 讓你愛上寫測試
RSpec 讓你愛上寫測試RSpec 讓你愛上寫測試
RSpec 讓你愛上寫測試
Wen-Tien Chang
 
Avanthi Guduru ( Oracle DBA) Resume
Avanthi Guduru ( Oracle DBA) ResumeAvanthi Guduru ( Oracle DBA) Resume
Avanthi Guduru ( Oracle DBA) Resume
Avanthi Guduru
 
Container Orchestration with Docker Swarm and Kubernetes
Container Orchestration with Docker Swarm and KubernetesContainer Orchestration with Docker Swarm and Kubernetes
Container Orchestration with Docker Swarm and Kubernetes
Will Hall
 
Oracle 12c and its pluggable databases
Oracle 12c and its pluggable databasesOracle 12c and its pluggable databases
Oracle 12c and its pluggable databases
Gustavo Rene Antunez
 
Getting Started With Docker | Docker Tutorial | Docker Training | Edureka
Getting Started With Docker | Docker Tutorial | Docker Training | EdurekaGetting Started With Docker | Docker Tutorial | Docker Training | Edureka
Getting Started With Docker | Docker Tutorial | Docker Training | Edureka
Edureka!
 
Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...
Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...
Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...
Simplilearn
 
Node.js and the MySQL Document Store
Node.js and the MySQL Document StoreNode.js and the MySQL Document Store
Node.js and the MySQL Document Store
Rui Quelhas
 
Docker Introduction
Docker IntroductionDocker Introduction
Docker Introduction
Peng Xiao
 
LINQ
LINQLINQ
Maven
MavenMaven
Intro To Docker
Intro To DockerIntro To Docker
Intro To Docker
Jessica Lucci
 
Selenium web driver
Selenium web driverSelenium web driver
Selenium web driver
Roman Savitskiy
 

What's hot (20)

Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛
 
The evolution of Apache Calcite and its Community
The evolution of Apache Calcite and its CommunityThe evolution of Apache Calcite and its Community
The evolution of Apache Calcite and its Community
 
Introduction to Docker
Introduction to DockerIntroduction to Docker
Introduction to Docker
 
Securing MongoDB to Serve an AWS-Based, Multi-Tenant, Security-Fanatic SaaS A...
Securing MongoDB to Serve an AWS-Based, Multi-Tenant, Security-Fanatic SaaS A...Securing MongoDB to Serve an AWS-Based, Multi-Tenant, Security-Fanatic SaaS A...
Securing MongoDB to Serve an AWS-Based, Multi-Tenant, Security-Fanatic SaaS A...
 
Maven tutorial
Maven tutorialMaven tutorial
Maven tutorial
 
Docker Introduction
Docker IntroductionDocker Introduction
Docker Introduction
 
Code Coverage Revised : EclEmma on JaCoCo
Code Coverage Revised : EclEmma on JaCoCoCode Coverage Revised : EclEmma on JaCoCo
Code Coverage Revised : EclEmma on JaCoCo
 
Cloud Native Java GraalVM 이상과 현실
Cloud Native Java GraalVM 이상과 현실Cloud Native Java GraalVM 이상과 현실
Cloud Native Java GraalVM 이상과 현실
 
RSpec 讓你愛上寫測試
RSpec 讓你愛上寫測試RSpec 讓你愛上寫測試
RSpec 讓你愛上寫測試
 
Avanthi Guduru ( Oracle DBA) Resume
Avanthi Guduru ( Oracle DBA) ResumeAvanthi Guduru ( Oracle DBA) Resume
Avanthi Guduru ( Oracle DBA) Resume
 
Container Orchestration with Docker Swarm and Kubernetes
Container Orchestration with Docker Swarm and KubernetesContainer Orchestration with Docker Swarm and Kubernetes
Container Orchestration with Docker Swarm and Kubernetes
 
Oracle 12c and its pluggable databases
Oracle 12c and its pluggable databasesOracle 12c and its pluggable databases
Oracle 12c and its pluggable databases
 
Getting Started With Docker | Docker Tutorial | Docker Training | Edureka
Getting Started With Docker | Docker Tutorial | Docker Training | EdurekaGetting Started With Docker | Docker Tutorial | Docker Training | Edureka
Getting Started With Docker | Docker Tutorial | Docker Training | Edureka
 
Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...
Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...
Docker Compose | Docker Compose Tutorial | Docker Tutorial For Beginners | De...
 
Node.js and the MySQL Document Store
Node.js and the MySQL Document StoreNode.js and the MySQL Document Store
Node.js and the MySQL Document Store
 
Docker Introduction
Docker IntroductionDocker Introduction
Docker Introduction
 
LINQ
LINQLINQ
LINQ
 
Maven
MavenMaven
Maven
 
Intro To Docker
Intro To DockerIntro To Docker
Intro To Docker
 
Selenium web driver
Selenium web driverSelenium web driver
Selenium web driver
 

Similar to Rails DB migrations

12 Introduction to Rails
12 Introduction to Rails12 Introduction to Rails
12 Introduction to Rails
Deepak Hagadur Bheemaraju
 
Handling Database Deployments
Handling Database DeploymentsHandling Database Deployments
Handling Database Deployments
Mike Willbanks
 
Liquibase case study
Liquibase case studyLiquibase case study
Liquibase case study
Vivek Dhayalan
 
Evolutionary database design
Evolutionary database designEvolutionary database design
Evolutionary database design
Salehein Syed
 
Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014
Michael Renner
 
Sql server-dba
Sql server-dbaSql server-dba
Sql server-dba
NaviSoft
 
Schema migration in agile environmnets
Schema migration in agile environmnetsSchema migration in agile environmnets
Schema migration in agile environmnets
Vivek Dhayalan
 
Jasig Rubyon Rails
Jasig Rubyon RailsJasig Rubyon Rails
Jasig Rubyon Rails
Paul Pajo
 
Sql server
Sql serverSql server
Sql server
Puja Gupta
 
Change RelationalDB to GraphDB with OrientDB
Change RelationalDB to GraphDB with OrientDBChange RelationalDB to GraphDB with OrientDB
Change RelationalDB to GraphDB with OrientDB
Apaichon Punopas
 
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptxShshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
086ChintanPatel1
 
AWS RDS Migration Tool
AWS RDS Migration Tool AWS RDS Migration Tool
8028.ppt
8028.ppt8028.ppt
8028.ppt
PVinayIT
 
Evolutionary Database Design
Evolutionary Database DesignEvolutionary Database Design
Evolutionary Database Design
Andrei Solntsev
 
MODULE 5.pptx
MODULE 5.pptxMODULE 5.pptx
MODULE 5.pptx
lathass5
 
Database schema management in Ruby apps
Database schema management in Ruby appsDatabase schema management in Ruby apps
Database schema management in Ruby apps
Vsevolod Romashov
 
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Ontico
 
Sqlite
SqliteSqlite
Sqlite
Kumar
 
Ruby on Rails
Ruby on RailsRuby on Rails
Rails data migrations
Rails data migrationsRails data migrations
Rails data migrations
Andrei Kaleshka
 

Similar to Rails DB migrations (20)

12 Introduction to Rails
12 Introduction to Rails12 Introduction to Rails
12 Introduction to Rails
 
Handling Database Deployments
Handling Database DeploymentsHandling Database Deployments
Handling Database Deployments
 
Liquibase case study
Liquibase case studyLiquibase case study
Liquibase case study
 
Evolutionary database design
Evolutionary database designEvolutionary database design
Evolutionary database design
 
Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014
 
Sql server-dba
Sql server-dbaSql server-dba
Sql server-dba
 
Schema migration in agile environmnets
Schema migration in agile environmnetsSchema migration in agile environmnets
Schema migration in agile environmnets
 
Jasig Rubyon Rails
Jasig Rubyon RailsJasig Rubyon Rails
Jasig Rubyon Rails
 
Sql server
Sql serverSql server
Sql server
 
Change RelationalDB to GraphDB with OrientDB
Change RelationalDB to GraphDB with OrientDBChange RelationalDB to GraphDB with OrientDB
Change RelationalDB to GraphDB with OrientDB
 
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptxShshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
 
AWS RDS Migration Tool
AWS RDS Migration Tool AWS RDS Migration Tool
AWS RDS Migration Tool
 
8028.ppt
8028.ppt8028.ppt
8028.ppt
 
Evolutionary Database Design
Evolutionary Database DesignEvolutionary Database Design
Evolutionary Database Design
 
MODULE 5.pptx
MODULE 5.pptxMODULE 5.pptx
MODULE 5.pptx
 
Database schema management in Ruby apps
Database schema management in Ruby appsDatabase schema management in Ruby apps
Database schema management in Ruby apps
 
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
 
Sqlite
SqliteSqlite
Sqlite
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
Rails data migrations
Rails data migrationsRails data migrations
Rails data migrations
 

Recently uploaded

14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and MoreManyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
narinav14
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Peter Caitens
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
Luigi Fugaro
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
ervikas4
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
vaishalijagtap12
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 

Recently uploaded (20)

14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and MoreManyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 

Rails DB migrations

  • 1. Database migrations in Rails Denys Kurets
  • 2. Agenda - What are database migrations; - Database migrations in Rails; - Best practices;
  • 3. What are database migrations?
  • 4. 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?
  • 5. Flow: • Use Ruby code (Database independent); • Run rake task; • Other developer run rake task; • Run rake task during deploy Database migrations in Rails
  • 6. Database migrations in Rails Migration are classes:
  • 7. 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
  • 8. 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:
  • 9. Database migrations in Rails Add and Remove Columns: • AddXXXtoYYY • RemoveXXXFromYYY rails g migration AddShortToProducts short:text rails g migration RemoveShortFromProducts short:text
  • 10. create_table Methods for db structure changing create_table :friends do |t| t.string :first_name t.string :last_name t.string :email t.timestamps end change_table change_table :friends do |t| t.remove :last_name, :first_name t.string :phone_number t.index :phone_number end add_column change_column :friends, :last_name, :string change_column add_column :friends, :first_name, :string add_column :friends, :last_name, :integer
  • 11. 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
  • 12. ● :binary ● :boolean ● :date ● :datetime ● :decimal ● :float Column Types: Database migrations in Rails ● :integer ● :primary_key ● :string ● :text ● :time ● :timestamp ● :references
  • 13. 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 end end
  • 14. Up and Down methods
  • 15. Database migrations in Rails rake 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:
  • 16. Database migrations in Rails (How it works?)
  • 17. Database migrations in Rails rake db:migrate:down VERSION=20150321134933 rake db:rollback rake db:migrate
  • 18. rake db:rollback STEP=3 rake db:migrate VERSION=20151124211406 rake db:migrate:up VERSION=20151124211419 Database migrations in Rails
  • 19. Init app database: Database migrations in Rails rake db:setup 1. db:create 2. db:schema:load 3. db:seed rake db:reset 1. db:drop 2. db:setup
  • 20. 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
  • 21. 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
  • 22. 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;
  • 23. 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
  • 24. "the only stupid question is the one that isn't asked"