Last active
November 20, 2023 23:18
-
-
Save ruby-fu-ninja/4499099 to your computer and use it in GitHub Desktop.
Update Postgres id sequences on all of your Rails models
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
Dir[Rails.root.join('app', 'models', '*')].each do |path| | |
file = File.basename(path, '.rb') | |
begin | |
klass = file.classify.constantize | |
if klass.respond_to?(:select) | |
max_id = klass.maximum(:id).to_i + 1 | |
sequence = ActiveRecord::Base.connection.execute("SELECT nextval('#{klass.table_name}_id_seq')").first['nextval'].to_i | |
if sequence <= max_id | |
puts "Updating sequence for #{klass.table_name}" | |
ActiveRecord::Base.connection.execute("SELECT setval('#{klass.table_name}_id_seq', (SELECT MAX(id) FROM #{klass.table_name}))") | |
end | |
end | |
rescue ActiveRecord::StatementInvalid | |
puts "Something was wrong with SQL in #{File.basename(file)}" | |
rescue NameError | |
puts "#{File.basename(file)} does not exist" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment