9/24/2006

Migrate 初探

一開始對 Migrate 沒啥特別的好感的
因為 SQL 本身已經很成熟了,好像不需要重新造輪子
不過,SQL 雖然成熟,但是各家 RDBMS 又很混亂
你有支援這個,我有支援那個
對程式設計師跨 DB 操作感到很麻煩

對我來說,我的 Server 是用 MySQL
平時操作是使用 phpMyAdmin 這個好用的工具
但是 iBook 上面因為效率的關係,始用比較輕巧的 SQLite
雖然也有SQLite Database Browser這個還不錯的東西
但是總覺得不太好用
這時候,使用 Migration 就是一個不錯的選擇了
裡面 DB 操作管理完全使用 Ruby Code ,可以說是另外一個相當簡單方便的選擇

用 Migration 新增 Table
一開始,進入 Rails 資料夾,先將 config/database.yml 寫好
新增一個 Migration File
ruby script/generate migration add_a_new_table
或是
ruby script/generate model add_a_new_table
他會在 db/migrate/ 新增一個 migration 的 file
前面的數字是 version 的編號

然後進入修改這個file裡面的 self.up method
def self.up
create_table :users do |table|
table.column :name, :string
table.column :login, :string, :null => false
# This column will contain an MD5 hash.
table.column :password, :string, :limit => 32, :null => false
table.column :email, :string
end
end
形式大概是 table.column :column_name , :column_type , :option

Column Type :

Column type 可以指定 integer, float, datetime, date, timestamp, time, text, string, binary, boolean

Column Option
後面的選項可以有:
  • limit ( :limit => “50” )
  • default (:default => “預設值” )
  • null (:null => false 代表 NOT NULL)
Ruby code 寫好之後,打入
rake migrate
這樣就可以新增一個 DB table

不同 Version Control


Migration 有 Version Control 的概念, Version 的編號就是檔案前面的數字。 self.up 就是前進 version 要做的動作,self.down 就是 back version 所需的動作。兩者應該是相對的,一個是 create_table 另外一個就應該是 drop_table,使用方式是
rake migrate VERSION=version_number
例如
rake migrate VERSION=12
或是
rake migrate VERSION=0 (0就是回到最初的狀態)



不同環境的 Migrate
export RAILS_ENV=production
rake migrate
你可以選擇 migration 不同的環境 ( export RAILS_ENV=test , export RAILS_ENV=development )

Drop Table / Rename_table


rename_table :old_name , :new_name
drop_table :table_name

新增刪除修改 Column
add_column(table_name, column_name, type, options)
rename_column(table_name, column_name, new_column_name)
change_column(table_name, column_name, type, options)
remove_column(table_name, column_name)


裡面的 type 跟 option 就是新增 table 裡面的 column_type 跟 option

Index管理

add_index(table_name, column_name, index_type)
remove_index(table_name, column_name)

index_type 就是像是 unique 之類的 type

參考連結
  1. Migration Manual
  2. Rails Wiki
  3. Rails Migration

沒有留言: