From 96c046d483a5b512a9ac8117aea86b50fb12c901 Mon Sep 17 00:00:00 2001 From: Kevin Triplett Date: Thu, 25 Aug 2011 00:00:30 -0500 Subject: [PATCH] add id_seq reset for PostgreSQL databases --- lib/create_or_update.rb | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lib/create_or_update.rb b/lib/create_or_update.rb index 0a03531..6fa2572 100644 --- a/lib/create_or_update.rb +++ b/lib/create_or_update.rb @@ -24,4 +24,13 @@ class ActiveRecord::Base end record end + + # for PostgreSQL (and others?) we must reset the id sequential to the next + # available highest number. This happens because the create_or_update + # creates records with an id already set, bypassing PostgreSQL's automatic + # incrementing sequential id counter + # Otherwise, we get the dreaded "duplicate key value violates unique constraint" error + def self.postgresql_reset_id_seq + connection.execute("SELECT setval('#{self.table_name}_id_seq'::regclass, MAX(id)) FROM #{self.table_name}") + end end \ No newline at end of file