Skip to content

Instantly share code, notes, and snippets.

@rponte
Created October 31, 2011 02:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rponte/1326786 to your computer and use it in GitHub Desktop.
Save rponte/1326786 to your computer and use it in GitHub Desktop.
Disabling referential integrity examples with ruby (and probably rails too)
## ORACLE
def disable_referential_integrity(&block) #:nodoc:
sql_constraints = <<-SQL
SELECT constraint_name, owner, table_name
FROM user_constraints
WHERE constraint_type = 'R'
AND status = 'ENABLED'
SQL
old_constraints = select_all(sql_constraints)
begin
old_constraints.each do |constraint|
execute "ALTER TABLE #{constraint["table_name"]} DISABLE CONSTRAINT #{constraint["constraint_name"]}"
end
yield
ensure
old_constraints.each do |constraint|
execute "ALTER TABLE #{constraint["table_name"]} ENABLE CONSTRAINT #{constraint["constraint_name"]}"
end
end
end
## SQLSERVER
def disable_referential_integrity
do_execute "EXEC sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'"
yield
ensure
do_execute "EXEC sp_MSforeachtable 'ALTER TABLE ? CHECK CONSTRAINT ALL'"
end
## MYSQL
def disable_referential_integrity #:nodoc:
old = select_value("SELECT @@FOREIGN_KEY_CHECKS")
begin
update("SET FOREIGN_KEY_CHECKS = 0")
yield
ensure
update("SET FOREIGN_KEY_CHECKS = #{old}")
end
end
## POSTGRES
def disable_referential_integrity #:nodoc:
if supports_disable_referential_integrity? then
execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER ALL" }.join(";"))
end
yield
ensure
if supports_disable_referential_integrity? then
execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER ALL" }.join(";"))
end
end
@rponte
Copy link
Author

rponte commented Feb 16, 2013

More informations about how database_cleaner gem uses thoses methods,
https://github.com/bmabey/database_cleaner/blob/master/lib/database_cleaner/active_record/truncation.rb#L248

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment