Skip to content

Commit ab097f9

Browse files
Bartosz Suchodolskibotandrose
authored andcommitted
Use RESTRICT instead of CASCADE when truncating with postgres
1 parent fe24fc9 commit ab097f9

2 files changed

Lines changed: 9 additions & 1 deletion

File tree

lib/database_cleaner/active_record/truncation.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ def database_tables
189189

190190
def truncate_tables(table_names)
191191
return if table_names.nil? || table_names.empty?
192-
execute("TRUNCATE TABLE #{table_names.map{|name| quote_table_name(name)}.join(', ')} RESTART IDENTITY CASCADE;")
192+
execute("TRUNCATE TABLE #{table_names.map{|name| quote_table_name(name)}.join(', ')} RESTART IDENTITY RESTRICT;")
193193
end
194194

195195
def pre_count_truncate_tables(tables)

spec/database_cleaner/active_record/truncation_spec.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
before do
3434
2.times { User.create! }
3535
2.times { Agent.create! }
36+
UserProfile.create!(user_id: User.first.id) if helper.db == :postgres
3637
end
3738

3839
it "should truncate all tables" do
@@ -42,6 +43,13 @@
4243
.to([0,0])
4344
end
4445

46+
if helper.db == :postgres
47+
it "should raise exception when trying to truncate table referenced in a foreign key constraint" do
48+
expect { described_class.new(except: ['user_profiles']).clean }
49+
.to raise_error(ActiveRecord::StatementInvalid, /cannot truncate a table referenced in a foreign key constraint/)
50+
end
51+
end
52+
4553
it "should reset AUTO_INCREMENT index of table" do
4654
strategy.clean
4755
expect(User.create.id).to eq 1

0 commit comments

Comments
 (0)