Over a million developers have joined DZone.

Adjust Database Sequences

·
If loading data through fixtures or other means with hard-coded IDs, database sequences may need to be adjusted.  This is written for Oracle.


namespace :db do
  task :adjust_sequences => :environment do
    ActiveRecord::Base.connection.tables.each do |table|
      begin
        count = ActiveRecord::Base.count_by_sql("SELECT MAX(id) FROM #{table}")
        seq = "#{table}_seq"
        ActiveRecord::Base.connection.execute("DROP SEQUENCE #{seq}")
        ActiveRecord::Base.connection.execute("CREATE SEQUENCE #{seq} START WITH #{count+1}")
      rescue => ex
        puts "Failed for #{table} with #{ex.class}"
      end
    end
  end
end
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}