Advanced Migration By Aye Mon Tun.  To change database schema in consistent and easy way  In ruby code Migration? 11/25/2013 2Web Application Engineering.

Slides:



Advertisements
Similar presentations
The Librarian Web Page Carol Wolf CS396X. Create new controller  To create a new controller that can manage more than just books, type ruby script/generate.
Advertisements

Let’s try Oracle. Accessing Oracle The Oracle system, like the SQL Server system, is client / server. For SQL Server, –the client is the Query Analyser.
Introduction to Structured Query Language (SQL)
SQL components In Oracle. SQL in Oracle SQL is made up of 4 components: –DDL Data Definition Language CREATE, ALTER, DROP, TRUNCATE. Creates / Alters.
SQL Data Definition II Stanislava Armstrong 1SQL Data Definition II.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 9: Data Definition Language.
Murali Mani SQL DDL and Oracle utilities. Murali Mani Datatypes in SQL INT (or) INTEGER FLOAT (or) REAL DECIMAL (n, m) CHAR (n) VARCHAR (n) DATE, TIME.
Introduction to Structured Query Language (SQL)
SQL Overview Defining a Schema CPSC 315 – Programming Studio Spring 2008 Project 1, Lecture 3 Slides adapted from those used by Jeffrey Ullman, via Jennifer.
Kirkwood Center for Continuing Education Introduction to PHP and MySQL By Fred McClurg, Copyright © 2010 All Rights Reserved. 1.
Ruby on Rails Creating a Rails Application Carol E Wolf CS396X.
Introduction To Databases IDIA 618 Fall 2014 Bridget M. Blodgett.
1 CSE 480: Database Systems Lecture 9: SQL-DDL Reference: Read Chapter of the textbook.
SQL Overview Defining a Schema CPSC 315 – Programming Studio Slides adapted from those used by Jeffrey Ullman, via Jennifer Welch Via Yoonsuck Choe.
Rails and Grails. To get started Make sure you have java installed You can get the sdk and jre at:
1 Dr Alexiei Dingli Web Science Stream Models, Views and Controllers.
Database Technical Session By: Prof. Adarsh Patel.
Taking ActiveRecord to the Next Level Blythe Dunham
Databases. Database A database is an organized collection of related data.
Constraints  Constraints are used to enforce rules at table level.  Constraints prevent the deletion of a table if there is dependencies.  The following.
Ruby on Rails Your first app. Rails files app/ Contains the controllers, models, views and assets for your application. You’ll focus on this folder for.
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
1 SQL Tarek El-Shishtawy Professor Ass. Of Computer Engineering.
Chapter 5: Part 1: DDL STRUCTURED QUERY LANGUAGE (SQL)
Kirkwood Center for Continuing Education Introduction to PHP and MySQL By Fred McClurg, Copyright © 2015, Fred McClurg, All Rights.
1 Structured Query Language (SQL). 2 Contents SQL – I SQL – II SQL – III SQL – IV.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Associations INFO 2310: Topics in Web Design and Programming.
Ruby on Rails: Databases. Rails Database Familiar Table Concept Naming convention – lower case, plural (i.e. tweets) How to Access (find), Update, Delete.
SQL: DDL. SQL Statements DDL - data definition language –Defining and modifying data structures (metadata): database, tables, views, etc. DML - data manipulation.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
Constraints cis 407 Types of Constraints & Naming Key Constraints Unique Constraints Check Constraints Default Constraints Misc Rules and Defaults Triggers.
Tables and Constraints Oracle PL/SQL. Datatypes The SQL Data Definition Language Commands (or DDL) enable us to create, modify and remove database data.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Visual Programing SQL Overview Section 1.
Chapter 15 © 2013 by Pearson Overview of Rails - Rails is a development framework for Web-based applications - Based on MVC architecture for applications.
CS 338The Relational Model2-1 The Relational Model Lecture Topics Overview of SQL Underlying relational model Relational database structure SQL DDL and.
1 Migration. 2 What’s Migration? Migration –Isolates database differences Allows you to write schema updates without worries about differences –Helps.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
ITS232 Introduction To Database Management Systems Siti Nurbaya Ismail Faculty of Computer Science & Mathematics, Universiti Teknologi MARA (UiTM), Kedah.
Altering Tables and Constraints Database Systems Objectives Add and modify columns. Add, enable, disable, or remove constraints. Drop a table. Remove.
1 CS 430 Database Theory Winter 2005 Lecture 11: SQL DDL.
A Guide to SQL, Eighth Edition Chapter Six Updating Data.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
IS6146 Databases for Management Information Systems Lecture 3: SQL III – The DDL Rob Gleasure robgleasure.com.
CS 160 and CMPE/SE 131 Software Engineering February 9 Class Meeting Department of Computer Science Department of Computer Engineering San José State University.
Starting with Oracle SQL Plus. Today in the lab… Connect to SQL Plus – your schema. Set up two tables. Find the tables in the catalog. Insert four rows.
Migrations Carol Wolf CS 396X. ISBNTitleAuthorImage EmmaAustenemma.jpg Oliver TwistDickenstwist.jpg HamletShakespearehamlet.jpg.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
1 11g NEW FEATURES ByVIJAY. 2 AGENDA  RESULT CACHE  INVISIBLE INDEXES  READ ONLY TABLES  DDL WAIT OPTION  ADDING COLUMN TO A TABLE WITH DEFAULT VALUE.
Physical Model Lecture 11. Physical Data Model The last step is the physical design phase, In this phase data is – Store – Organized and – Access.
Lec-7. The IN Operator The IN operator allows you to specify multiple values in a WHERE clause. SQL IN Syntax SELECT column_name(s) FROM table_name WHERE.
Oracle 11g: SQL Chapter 5 Data Manipulation and Transaction Control.
Rob Gleasure robgleasure.com
Rob Gleasure robgleasure.com
Managing Tables, Data Integrity, Constraints by Adrienne Watt
Module 5: Implementing Data Integrity by Using Constraints
STRUCTURED QUERY LANGUAGE
Agile Web Development with Ruby and Rails
Model for Student Table
CS122 Using Relational Databases and SQL
Chapter 2: Creating And Modifying Database Tables
CS3220 Web and Internet Programming SQL and MySQL
CS1222 Using Relational Databases and SQL
CS3220 Web and Internet Programming SQL and MySQL
CS122 Using Relational Databases and SQL
Presentation transcript:

Advanced Migration By Aye Mon Tun

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

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

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

 To generate migration file with CreateAuthors class which includes name variable with string type.  $rails generate model Author name:string  $rails generate scaffold Author name:string  $rails generate migration CreateAuthors na me:string  To generate empty migration file  $rails generate migration CreateAuthor How to create Migration File 11/25/2013 5Web Application Engineering

 Name  By default, Rails generates migrations that look like:Rails e.g _create_authors.rb  The prefix is a generation timestamp (in UTC)  Place  In db/migrate folder You can turn timestamped migrations off by setting: config.active_record.timestamped_migrations = false in application.rb Migration file 11/25/2013 6Web Application Engineering

 A migration file is of two forms to change database (to redo and undo).  -Using change method Class FileName<AticveRecord::Migration def change end  -Using up and down methods Class FileName<AticveRecord::Migration def up end def down end Anatomy of Migration file 11/25/2013 7Web Application Engineering

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

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

 $rails destroy model Author name:string  $rails destroy scaffold Author name:string  $rails destroy migration CreateAuthors name:string How to destroy migration file 11/25/ Web Application Engineering

 To execute database changes or migration files $rake db:migrate  To execute a specific migration, use its version with up and down keywords $rake db:migrate:up VERSION= $rake db:migrate:down VERSION=  To rollback last database changes $rake db:rollback  To redo database changes $rake db:redo  To define how many migrations will be redone or rollback, use STEP keyword $rake db:rollback VERSION= $rake db:redo VERSION=  To redo or rollback a specific migration, use VERSION keyword $rake db:rollback VERSION= $rake db:redo VERSION=  To view the current status of database $rake db:migrate:status Managing migrations 11/25/ Web Application Engineering

 It contains the version numbers of all the migrations applied  Active Record uses the information to keep track of database changes Schema_migrations Table version (3 rows) 11/25/ Web Application Engineering

1) :binary 2) :boolean 3) :date 4) :datetime 5) :decimal 6) :float 7) :integer 8) :string 9) :time 10) :timestamp Data types support 11/25/ Web Application Engineering

 For each type of column  :default => value  :limit => size  :null => true or false  :polymorphic =>  For :decimal type  :precision => value  :scale => value class CreateShops < ActiveRecord::Migration def change create_table :shops do |t| t.string :name :limit => 20, default => 'Restaurant', :null => false t.decimal :price, :precision => 6, :scale => 2 end Column Type options 11/25/ Web Application Engineering

 add_column  add_index  add_reference  add_timestamps  create_table  create_join_table  drop_table (must supply a block)  drop_join_table (must supply a block)  remove_timestamps  rename_column  rename_index  remove_reference  rename_table Available transformations 11/25/ Web Application Engineering

-$rails g migration CreateXXX column list -Use create_table to create a table -Use drop_table to drop table class CreateAuthors < ActiveRecord: : Migration def up create_table :authors do |t| t.string :name end def down drop_table :authors end Table creation and dropping 11/25/ Web Application Engineering

-Use change_table to change an existing table class ChangeAuthors < ActiveRecord: : Migration def change change_table :authors do |t| t.float :income t.change :income, :string t.text :background end Changing Table 11/25/ Web Application Engineering

$ rails g migration CreateJoinTableCustomerProduct customer product class CreateJoinTableCustomerProduct < ActiveRecord::Migration def change create_join_table :customers, :products do |t| t.index [:customer_id, :product_id] t.index [:product_id, :customer_id] end Joining Tables 11/25/ Web Application Engineering

 By Default, rails creates tables with default primary key called id.  To prevent auto-generated primary key, set id to false create_table :customers, {:id=>false} do |t|... end  To define a primary key create_table :customers, {:primary_key=>:customer_id} do |t|... end Overriding Primary Key Setting 11/25/ Web Application Engineering

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

 $rails g migration AddColumnNameToTableName column:type  $rails g migration AddRateToBooks rate:string  $rails g migration AddbookToBooks book:integer:index  $rails g migrations AddAuthorRefToBooks author:references  $rails g migrations RemoveColumnNameFromBooks rate:string  $rails g migrations RemoveRateFromBooks rate:string  $rails g migrations RemovebookFrombooks book:integer  $rails g migrations RemoveAuthorRefFromBooks author:references Adding and removing columns 11/25/ Web Application Engineering

 Use reset_column_information to ensure that a model has the latest column data from after a new column was added  $rails g migration AddIncomeToAuthors income:integer class AddIncomeToAuthors < ActiveRecord::Migration def up add_column :authors, :income, :integer Author.reset_column_information a=Author.find('Mon Mon') a.update(income: ) end Using a model after changing its table 11/25/ Web Application Engineering

 Migration can be used to populate data into database tables  $rails g migration CreateBooks name:string class CreateBooks < ActiveRecord: : Migration def up create_table :books do |t| t.string :name :limit => 32, null =>false end Book.create :name => “English” Book.create :name => “Maths” Book.create :name => “Computer Science” end def down drop_table :books end Inializing data in table 11/25/ Web Application Engineering

 If the database adapter supports DDL transactions, all migrations will automatically be wrapped in a transaction. There are queries that you can’t execute inside a transaction though, and for these situations you can turn the automatic transactions off. class ChangeColumn < ActiveRecord::Migration disable_ddl_transaction! def up execute "ALTER SEQUENCE name RENAME TO new_name” end Transactional Migrations 11/25/ Web Application Engineering

 sometimes you need to do something in SQL not abstracted directly by migrations:  Use execute method execute "UPDATE authors SET name='Mon' WHERE name = 'Mon Mon'" How to use SQL 11/25/ Web Application Engineering

Adding and Removing Foreign Key -Includes gem 'foreigner' in GemFile and run bundle install -Use add_foreign_key and remove_foreign_key method in migration file class AddForeignKey < ActiveRecord::Migration def up add_foreign_key :cars, :users end def down remove_foreign_key :cars, :users end 11/25/ Web Application Engineering

class ExampleMigration < ActiveRecord::Migration def change create_table :products do |t| t.references :category end reversible do |dir| dir.up do #add a foreign key execute “ALTER TABLE products ADD CONSTRAINT fk_products_categories FOREIGN KEY (category_id) REFERENCES categories(id)” end dir.down do execute “ALTER TABLE products DROP FOREIGN KEY fk_products_categories” end Adding Foreign Key Constraints 11/25/ Web Application Engineering

 Use reversible or revert class ChangeProductsPrice < ActiveRecord::Migration def change reversible do |dir| change_table :products do |t| dir.up { t.change :price, :string } dir.down { t.change :price, :integer } end  class ChangeProductsPrice < ActiveRecord::Migration  def up  change_table :products do |t|  t.change :price, :string  end Reversible migrations 11/25/ Web Application Engineering

11/25/2013 Web Application Engineering29   def down  change_table :products do |t|  t.change :price, :integer  end #If a command cannot be reversed, an ActiveRecord::IrreversibleMigration exception will be raised when the migration is moving down. (see list of irreversible commands in ActiveRecord::Migration::CommandRecorder.) raise ActiveRecord: :Irresversible Migration Reversible migrations

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

 insert your own messages and benchmarks by using the say_with_time method: def up... say_with_time "Updating Author income..." do author=Authors.find_by_name(“Aye Mon Tun”) author.update( end  set ActiveRecord::Migration.verbose = false to show no message Controlling Verbosity 11/25/ Web Application Engineering

 Use RAILS_ENV variable  $rake db:migrate RAILS_ENV=production  $rake db:migrate RAILS_ENV=test Running Migration For production and test databases 11/25/ Web Application Engineering

html html migrations/ migrations/ References 11/25/ Web Application Engineering

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