Skip to content

Commit

Permalink
Add support for multi-statement query
Browse files Browse the repository at this point in the history
Since Rails 5.2, fixtures use multi-statement query when inserting.
rails/rails#31422

However, since `database_rewinder` does not support multi-statement
query, tables inserted by fixture is not cleaned.
This patch also adds support to allow to retrieve the table where insert
was done even if a query is multi-statement.
  • Loading branch information
y-yagi committed Aug 9, 2018
1 parent 976b8c6 commit 9ffd294
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
16 changes: 9 additions & 7 deletions lib/database_rewinder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,15 @@ def record_inserted_table(connection, sql)
end
end or return

match = sql.match(/\A\s*INSERT(?:\s+IGNORE)?(?:\s+INTO)?\s+(?:\.*[`"]?([^.\s`"]+)[`"]?)*/i)
return unless match

table = match[1]
if table
cleaner.inserted_tables << table unless cleaner.inserted_tables.include? table
cleaner.pool ||= connection.pool
sql.split(';').each do |statement|
match = statement.match(/\A\s*INSERT(?:\s+IGNORE)?(?:\s+INTO)?\s+(?:\.*[`"]?([^.\s`"]+)[`"]?)*/i)
next unless match

table = match[1]
if table
cleaner.inserted_tables << table unless cleaner.inserted_tables.include? table
cleaner.pool ||= connection.pool
end
end
end

Expand Down
8 changes: 8 additions & 0 deletions test/database_rewinder_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@ def perform_insert(sql)
SQL
assert_equal ['foos'], @cleaner.inserted_tables
end

test 'with multi statement query' do
perform_insert <<-SQL
INSERT INTO "foos" ("name") VALUES (?);
INSERT INTO "bars" ("name") VALUES (?)
SQL
assert_equal ['foos', 'bars'], @cleaner.inserted_tables
end
end

sub_test_case 'Database accepts more than one dots in an object notation (e.g. SQLServer)' do
Expand Down

0 comments on commit 9ffd294

Please sign in to comment.