Permalink
Browse files

Correct PostgreSQL primary key sequence detection. #2507

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@2680 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
1 parent 86bdbc3 commit 311342d8e231f8429e270dce2b1bf4abeb7b4293 @jeremy jeremy committed Oct 18, 2005
Showing with 22 additions and 13 deletions.
  1. +2 −0 activerecord/CHANGELOG
  2. +20 −13 activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
View
2 activerecord/CHANGELOG
@@ -1,5 +1,7 @@
*1.12.1*
+* Correct PostgreSQL primary key sequence detection. #2507 [tmornini@infomania.com]
+
* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations
*1.12.0* (October 16th, 2005)
View
33 activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -205,28 +205,35 @@ def default_sequence_name(table_name, pk = 'id')
# Set the sequence to the max value of the table's pk.
def reset_pk_sequence!(table)
- sequence, pk = sequence_and_pk_for(table)
- if sequence and pk
+ pk, sequence = pk_and_sequence_for(table)
+ if pk and sequence
select_value <<-end_sql, 'Reset sequence'
SELECT setval('#{sequence}', (SELECT COALESCE(MAX(#{pk})+(SELECT increment_by FROM #{sequence}), (SELECT min_value FROM #{sequence})) FROM #{table}), false)
end_sql
end
end
# Find a table's primary key and sequence.
- def sequence_and_pk_for(table, column = nil)
+ def pk_and_sequence_for(table)
execute(<<-end_sql, 'Find pk sequence')[0]
- SELECT (name.nspname || '.' || seq.relname) AS sequence, attr.attname AS pk
- FROM pg_class seq, pg_attribute attr, pg_depend dep, pg_namespace name, pg_constraint cons
- WHERE seq.oid = dep.objid
- AND seq.relnamespace = name.oid
- AND attr.attrelid = dep.refobjid
- AND attr.attnum = dep.refobjsubid
- AND attr.attrelid = cons.conrelid
- AND attr.attnum = cons.conkey[1]
- AND cons.contype = 'p'
- AND dep.refobjid = '#{table}'::regclass
+ SELECT attr.attname, (name.nspname || '.' || seq.relname)
+ FROM pg_class seq,
+ pg_attribute attr,
+ pg_depend dep,
+ pg_namespace name,
+ pg_constraint cons
+ WHERE seq.oid = dep.objid
+ AND seq.relnamespace = name.oid
+ AND seq.relkind = 'S'
+ AND attr.attrelid = dep.refobjid
+ AND attr.attnum = dep.refobjsubid
+ AND attr.attrelid = cons.conrelid
+ AND attr.attnum = cons.conkey[1]
+ AND cons.contype = 'p'
+ AND dep.refobjid = '#{table}'::regclass
end_sql
+ rescue
+ nil
end

0 comments on commit 311342d

Please sign in to comment.