Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Adjust Database Sequences (See related posts)

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

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts