提交 6b2be718 编写于 作者: Y Yves Senn

Merge pull request #18597 from kamipo/add-if-exists-to-drop-table

Add an `:if_exists` option to `drop_table`
* Introduce the `:if_exists` option for `drop_table`.
Example:
drop_table(:posts, if_exists: true)
That would execute:
DROP TABLE IF EXISTS posts
If the table doesn't exist, `if_exists: false` (the default) raises an
exception whereas `if_exists: true` does nothing.
*Cody Cutrer*, *Stefan Kanev*, *Ryuta Kamizono*
* Don't run SQL if attribute value is not changed for update_attribute method.
*Prathamesh Sonpatki*
......
......@@ -380,7 +380,7 @@ def rename_table(table_name, new_name)
# it can be helpful to provide these in a migration's +change+ method so it can be reverted.
# In that case, +options+ and the block will be used by create_table.
def drop_table(table_name, options = {})
execute "DROP TABLE #{quote_table_name(table_name)}"
execute "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}"
end
# Adds a new column to the named table.
......
......@@ -502,7 +502,7 @@ def rename_table(table_name, new_name)
end
def drop_table(table_name, options = {})
execute "DROP#{' TEMPORARY' if options[:temporary]} TABLE #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}"
execute "DROP#{' TEMPORARY' if options[:temporary]} TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}"
end
def rename_index(table_name, old_name, new_name)
......
......@@ -112,7 +112,7 @@ def table_exists?(name)
end
def drop_table(table_name, options = {})
execute "DROP TABLE #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}"
execute "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}"
end
# Returns true if schema exists.
......
......@@ -403,6 +403,17 @@ def test_column_exists_on_table_with_no_options_parameter_supplied
end
end
def test_drop_table_if_exists
connection.create_table(:testings)
assert connection.table_exists?(:testings)
connection.drop_table(:testings, if_exists: true)
assert_not connection.table_exists?(:testings)
end
def test_drop_table_if_exists_nothing_raised
assert_nothing_raised { connection.drop_table(:nonexistent, if_exists: true) }
end
private
def testing_table_with_only_foo_attribute
connection.create_table :testings, :id => false do |t|
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册