-
-
Save marceloemanoel/1949770 to your computer and use it in GitHub Desktop.
disabling referential integrity examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment