Created
February 14, 2017 03:26
-
-
Save keithpitt/4a0d81f3c02aca1f029f523f6800cd4c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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