Skip to content
Browse files

Make create_table! only attempt to drop the table if it already exists

Before, it dropped the table unconditionally, then attempted to
create it.  This can hide bugs, since there are other reasons a
drop would fail besides nonexistence of the table.  The most
common cause would be that there are other tables that still
reference the table. Because the previous implementation did
rescue nil, the error got swallowed and you then got an error
during the CREATE TABLE statement saying the table already
exists.
  • Loading branch information...
1 parent daa3ff1 commit 14924593579dfeac29399feda0738b817cb2cebc @jeremyevans committed
Showing with 22 additions and 6 deletions.
  1. +4 −0 CHANGELOG
  2. +9 −4 lib/sequel/database/schema_methods.rb
  3. +9 −2 spec/core/schema_spec.rb
View
4 CHANGELOG
@@ -1,5 +1,9 @@
=== HEAD
+* Make create_table! only attempt to drop the table if it already exists (jeremyevans)
+
+* Remove custom table_exists? implementations in the oracle and postgres adapters (jeremyevans)
+
* Handle another type of disconnection in the postgres adapter (jeremyevans)
* Handle disconnections in the ado adapter and do postgres subadapter (jeremyevans)
View
13 lib/sequel/database/schema_methods.rb
@@ -99,17 +99,22 @@ def create_table(name, options={}, &block)
nil
end
- # Forcibly creates a table, attempting to drop it unconditionally (and catching any errors), then creating it.
+ # Forcibly create a table, attempting to drop it if it already exists, then creating it.
#
# DB.create_table!(:a){Integer :a}
- # # DROP TABLE a
+ # # SELECT * FROM a LIMIT a -- check existence
+ # # DROP TABLE a -- drop table if already exists
# # CREATE TABLE a (a integer)
def create_table!(name, options={}, &block)
- drop_table(name) rescue nil
+ drop_table(name) if table_exists?(name)
create_table(name, options, &block)
end
- # Creates the table unless the table already exists
+ # Creates the table unless the table already exists.
+ #
+ # DB.create_table?(:a){Integer :a}
+ # # SELECT * FROM a LIMIT a -- check existence
+ # # CREATE TABLE a (a integer) -- if it doesn't already exist
def create_table?(name, options={}, &block)
if supports_create_table_if_not_exists?
create_table(name, options.merge(:if_not_exists=>true), &block)
View
11 spec/core/schema_spec.rb
@@ -555,8 +555,15 @@
@db = SchemaDummyDatabase.new
end
- specify "should drop the table and then create it" do
- @db.create_table!(:cats) {}
+ specify "should create the table if it does not exist" do
+ @db.meta_def(:table_exists?){|a| false}
+ @db.create_table!(:cats){|*a|}
+ @db.sqls.should == ['CREATE TABLE cats ()']
+ end
+
+ specify "should drop the table before creating it if it already exists" do
+ @db.meta_def(:table_exists?){|a| true}
+ @db.create_table!(:cats){|*a|}
@db.sqls.should == ['DROP TABLE cats', 'CREATE TABLE cats ()']
end
end

0 comments on commit 1492459

Please sign in to comment.
Something went wrong with that request. Please try again.