0

What Happened?

We migrated from MySQL to Postgres and had Laravel re-run it's migrations with the psql driver instead of mysql. Worked great - it setup the database just fine. Since we are moving from Laravel to Rails, we created rails migrations to rename fields to be more 'rails-like' as well as to import the db data(not the structure) into postgres. We have run into a lot of issues from this, but most importantly sequences are jacked for auto increments now. They are trying to start from 1.

What Can I Not Figure Out?

I can manually reset all of them using something like SELECT pg_catalog.setval('availabilities_id_seq', 700, false); but that isn't very helpful as we do this on multiple environments with so many tables. Is there a way you can think of to find the last autoincrement id and then set the sequence from that?

In case you're curious, here is the Rails migration to move the data incase anyone has tips on how we did this wrong (my_models being the array of tables):

my_models.each do |m|
  puts m
  "Mysql#{m}".constantize.find_each(batch_size: 100) do |old_model|
    new_model = m.constantize.new
    new_model.attributes = old_model.attributes
    new_model.save
  end
end
Du3
  • 1,424
  • 6
  • 18
  • 36

1 Answers1

1

You can check the following discussions:

  1. Postgresql - Using subqueries with alter sequence expressions
  2. How to reset postgres' primary key sequence when it falls out of sync?

PostgreSQL wiki also have a possible solution to you case: Fixing Sequences.

Community
  • 1
  • 1
marcospereira
  • 12,045
  • 3
  • 46
  • 52