SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Downloaden Sie, um offline zu lesen
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!

Weitere ähnliche Inhalte

Was ist angesagt?

Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageGiuseppe Arici
 
Java Practical File Diploma
Java Practical File DiplomaJava Practical File Diploma
Java Practical File Diplomamustkeem khan
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentationadamcookeuk
 
Data Persistence in Android with Room Library
Data Persistence in Android with Room LibraryData Persistence in Android with Room Library
Data Persistence in Android with Room LibraryReinvently
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java Hitesh-Java
 
Android chapter02-setup2-emulator
Android chapter02-setup2-emulatorAndroid chapter02-setup2-emulator
Android chapter02-setup2-emulatorguru472
 
Mobile application testing
Mobile application testingMobile application testing
Mobile application testingSoftheme
 
Command Line Arguments in C#
Command Line Arguments in C#Command Line Arguments in C#
Command Line Arguments in C#Ali Hassan
 

Was ist angesagt? (20)

JAVA PPT Part-1 BY ADI.pdf
JAVA PPT Part-1 BY ADI.pdfJAVA PPT Part-1 BY ADI.pdf
JAVA PPT Part-1 BY ADI.pdf
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
Mern stack developement
Mern stack developementMern stack developement
Mern stack developement
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Java Practical File Diploma
Java Practical File DiplomaJava Practical File Diploma
Java Practical File Diploma
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Data Persistence in Android with Room Library
Data Persistence in Android with Room LibraryData Persistence in Android with Room Library
Data Persistence in Android with Room Library
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Firebase.pptx
Firebase.pptxFirebase.pptx
Firebase.pptx
 
11. java methods
11. java methods11. java methods
11. java methods
 
Android chapter02-setup2-emulator
Android chapter02-setup2-emulatorAndroid chapter02-setup2-emulator
Android chapter02-setup2-emulator
 
Mobile application testing
Mobile application testingMobile application testing
Mobile application testing
 
Dvm
DvmDvm
Dvm
 
AndroidManifest
AndroidManifestAndroidManifest
AndroidManifest
 
Java file
Java fileJava file
Java file
 
Command Line Arguments in C#
Command Line Arguments in C#Command Line Arguments in C#
Command Line Arguments in C#
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
Java features
Java featuresJava features
Java features
 

Ähnlich wie Rails DB migrations

Handling Database Deployments
Handling Database DeploymentsHandling Database Deployments
Handling Database DeploymentsMike Willbanks
 
Evolutionary database design
Evolutionary database designEvolutionary database design
Evolutionary database designSalehein Syed
 
Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014Michael Renner
 
Sql server-dba
Sql server-dbaSql server-dba
Sql server-dbaNaviSoft
 
Schema migration in agile environmnets
Schema migration in agile environmnetsSchema migration in agile environmnets
Schema migration in agile environmnetsVivek Dhayalan
 
Jasig Rubyon Rails
Jasig Rubyon RailsJasig Rubyon Rails
Jasig Rubyon RailsPaul Pajo
 
Change RelationalDB to GraphDB with OrientDB
Change RelationalDB to GraphDB with OrientDBChange RelationalDB to GraphDB with OrientDB
Change RelationalDB to GraphDB with OrientDBApaichon Punopas
 
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptxShshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx086ChintanPatel1
 
Evolutionary Database Design
Evolutionary Database DesignEvolutionary Database Design
Evolutionary Database DesignAndrei Solntsev
 
MODULE 5.pptx
MODULE 5.pptxMODULE 5.pptx
MODULE 5.pptxlathass5
 
Database schema management in Ruby apps
Database schema management in Ruby appsDatabase schema management in Ruby apps
Database schema management in Ruby appsVsevolod 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
SqliteKumar
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 

Kürzlich hochgeladen (20)

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 

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"