隨著時間的推移,管理基於SQL的腳本簡直成了夢魇。Rails則通過ActiveRecord Migration解決了這個問題。Sam Livingston-Gray編寫了一個獨立的Ruby小工具,來生成層次化的遷移腳本。因為SQL腳本通常都比較繁復冗贅,因此Sam將SQL和Ruby相結合創建了SQrbL。
你可以這樣來編寫腳本:
include Sqrbl
Sqrbl.migration do
@output_directory='/path/to/generated/sql' group "Widgets" do
step "Create widgets" do
up do
helpers do
def widget_import_note
'"Imported from old_widgets"' end end
action "Migrate old_widgets" do
<<-SQL
#{
insert_into("new_widgets", {
:name => 'widget_name',
:part_num => 'CONCAT("X_", part_number)',
:note => widget_import_note,
})
}
FROM old_widgets
SQL
end end down do
action "Drop imported organizational contacts" do
'DELETE FROM new_widgets WHERE note LIKE "Imported from old_widgets"' end end end end
group 'Second Group' do
step 'Step one' do
up { write '-- Step one up' }
down { write '-- Step one down' }
end step 'Step two' do
up { write '-- Step two up' }
down { write '-- Step two down'}
end end
end
於是SQrbL會生成如下文件:
/path/to/generated/sql/up/1_widgets/1_create_widgets.sql
/path/to/generated/sql/down/1_widgets/1_create_widgets.sql
/path/to/generated/sql/up/2_second_group/1_step_one.sql
/path/to/generated/sql/down/2_second_group/1_step_one.sql
/path/to/generated/sql/up/2_second_group/2_step_two.sql
/path/to/generated/sql/down/2_second_group/2_step_two.sql
/path/to/generated/sql/all_up.sql
/path/to/generated/sql/all_down.sql
例如all_up.sql中的SQL語句便是:
-- Migrate old_widgetsINSERT INTO new_widgets (
name,
part_num,
note
)
SELECT widget_name AS name,
CONCAT("X_", part_number) AS part_num,
"Imported from old_widgets" AS note
FROM old_widgets
-- Step one up-- Step two up
目前,SQrbL還僅能通過insert_into來簡化INSERT語句。
盡管對於已經使用ActiveRecord Migration的開發者來說,並沒有什麼理由再去使用SQrbL,然而它依然適合於那些尋找快速且簡單的獨立工具的人們。當前SQrbL的版本是0.1.3,尚缺乏一套適合的SQL DSL。