# frozen_string_literal: true RSpec.configure do |config| config.around(:each, :disable_foreign_keys => lambda { |v| !!v }) do |example| config.rspeckled_logger.debug("Around Each - Start - #{__FILE__}") options = example.metadata[:disable_foreign_keys] options = case options when ::Array { :tables => options.map(&:to_s) } when ::String, ::Symbol { :tables => [options.to_s] } when ::FalseClass { :tables => [] } when ::TrueClass { :tables => :all } end foreign_key_trigger_disable_statements_sql = <<~HEREDOC SELECT 'ALTER TABLE "' || "pg_namespace"."nspname" || '"."' || "pg_class"."relname" || '" DISABLE TRIGGER "' || "pg_trigger"."tgname" || '";' AS "statement" FROM "pg_trigger" INNER JOIN "pg_class" ON "pg_trigger"."tgrelid" = "pg_class"."oid" INNER JOIN "pg_namespace" ON "pg_class"."relnamespace" = "pg_namespace"."oid" INNER JOIN "pg_proc" ON "pg_trigger"."tgfoid" = "pg_proc"."oid" WHERE regexp_match("pg_proc"."proname", '.*_FKey_.*') IS NOT NULL HEREDOC unless options[:tables] == :all foreign_key_trigger_disable_statements_sql += " AND\n " table_constraint_sql = options[:tables] .map { |table_name| "'#{table_name}'" } .join(', ') foreign_key_trigger_disable_statements_sql += %Q{ "pg_class"."relname" IN (#{table_constraint_sql})} end foreign_key_trigger_disable_statements = ::ActiveRecord::Base.connection.select_values(foreign_key_trigger_disable_statements_sql).join(' ') ::ActiveRecord::Base.transaction do if foreign_key_trigger_disable_statements.blank? puts 'You asked to disable foreign keys but there were no foreign keys found to disable' else ::ActiveRecord::Base.connection.execute(foreign_key_trigger_disable_statements) end example.run end config.rspeckled_logger.debug("Around Each - End - #{__FILE__}") end end