postgres error: duplicate key violates unique constraint

by Rich Brant on June 16, 2009

Postgres doesn’t seem to handle imports very well. At least not as gracefully as MySQL. When the primary key sequence of a table gets out of whack, you can reset it via psql directly:

SELECT setval('table_name_id_seq', (SELECT MAX(id) FROM table_name)+1);

But that doesn’t see to solve the problem for my rails application. This does:

ActiveRecord::Base.connection.reset_pk_sequence!('table_name')

I posted this because all roads seem to lead to the former solution and not the latter..

This is an easy way to reset all the keys (from the console):

ActiveRecord::Base.connection.tables.each{|t| ActiveRecord::Base.connection.reset_pk_sequence!(t) unless t == 'schema_info'}

Leave a Comment

Previous post:

Next post: