From 61241833ec54fbb030da490eecc5bc69f44dc86e Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Fri, 10 Feb 2017 10:52:25 +0900 Subject: Revert "Simplify and speed up Postgres query for primary_keys" This reverts commit d6529af2954a67bd57fda45286fa9cfd0ff6b5ac. --- .../postgresql/schema_statements.rb | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) (limited to 'activerecord/lib/active_record') diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb index bd8aab526e..a4b1723fc7 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -426,14 +426,16 @@ module ActiveRecord def primary_keys(table_name) # :nodoc: select_values(<<-SQL.strip_heredoc, "SCHEMA") - SELECT a.attname - FROM pg_index i - CROSS JOIN unnest(i.indkey) as k - JOIN pg_attribute a - ON a.attrelid = i.indrelid - AND a.attnum = k - WHERE i.indrelid = #{quote(quote_table_name(table_name))}::regclass - AND i.indisprimary + WITH pk_constraint AS ( + SELECT conrelid, unnest(conkey) AS connum FROM pg_constraint + WHERE contype = 'p' + AND conrelid = #{quote(quote_table_name(table_name))}::regclass + ), cons AS ( + SELECT conrelid, connum, row_number() OVER() AS rownum FROM pk_constraint + ) + SELECT attr.attname FROM pg_attribute attr + INNER JOIN cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.connum + ORDER BY cons.rownum SQL end -- cgit v1.2.3