Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails reset ALL Postgres sequences?

Tags:

The following works in the Rails 3 console to reset Postgres sequences:

ActiveRecord::Base.connection.reset_pk_sequence!('menucontrols') ActiveRecord::Base.connection.reset_pk_sequence!('statuscodes') ActiveRecord::Base.connection.reset_pk_sequence!('wostatuses') ActiveRecord::Base.connection.reset_pk_sequence!('taskstatuses') ActiveRecord::Base.connection.reset_pk_sequence!('priorities') ActiveRecord::Base.connection.reset_pk_sequence!('actcodes') 

Is there a command that would reset ALL of them instead of having to do each one individually?

Thanks for the help!

like image 389
Reddirt Avatar asked Feb 25 '15 15:02

Reddirt


2 Answers

This is easier

ActiveRecord::Base.connection.tables.each do |t|   ActiveRecord::Base.connection.reset_pk_sequence!(t) end 
like image 103
Leaniman Avatar answered Sep 22 '22 09:09

Leaniman


I found one way to do it from this posting: Reset PostgreSQL

I placed the following into seed.rb and ran rake db:seed

ActiveRecord::Base.connection.tables.each do |table|   result = ActiveRecord::Base.connection.execute("SELECT id FROM #{table} ORDER BY id DESC LIMIT 1") rescue ( puts "Warning: not procesing table #{table}. Id is missing?" ; next )   ai_val = result.any? ? result.first['id'].to_i + 1 : 1   puts "Resetting auto increment ID for #{table} to #{ai_val}"   ActiveRecord::Base.connection.execute("ALTER SEQUENCE #{table}_id_seq RESTART WITH #{ai_val}") end 
like image 32
Reddirt Avatar answered Sep 21 '22 09:09

Reddirt