Skip to content

Instantly share code, notes, and snippets.

@keithpitt
Created February 14, 2017 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keithpitt/4a0d81f3c02aca1f029f523f6800cd4c to your computer and use it in GitHub Desktop.
Save keithpitt/4a0d81f3c02aca1f029f523f6800cd4c to your computer and use it in GitHub Desktop.
class IDSequenceResetter
def reset(connection)
@cached_sql ||= {}
sql = @cached_sql[connection] ||=
begin
sequences = connection.execute(%{SELECT c.relname FROM pg_class c WHERE c.relkind = 'S'}).values.flatten
"".tap do |sql|
sequences.each do |name|
next if not name.ends_with?("id_seq")
sql << %{ALTER SEQUENCE #{connection.quote_table_name(name)} RESTART WITH 1;\n}
end
end
end
connection.execute sql
end
end
RSpec.configure do |config|
id_sequence_resetter = IDSequenceResetter.new
config.before do |example|
id_sequence_resetter.reset(ActiveRecord::Base.connection)
id_sequence_resetter.reset(RecordWithOtherDatabase.connection)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment