Skip to content

Commit 4e0546c

Browse files
committed
Use single query to retrieve indexes in PostgreSQL
1 parent 614639c commit 4e0546c

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,13 @@ def indexes(table_name) # :nodoc:
8787
scope = quoted_scope(table_name)
8888

8989
result = query(<<~SQL, "SCHEMA")
90-
SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid,
91-
pg_catalog.obj_description(i.oid, 'pg_class') AS comment, d.indisvalid
90+
SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid),
91+
pg_catalog.obj_description(i.oid, 'pg_class') AS comment, d.indisvalid,
92+
ARRAY(
93+
SELECT pg_get_indexdef(d.indexrelid, k + 1, true)
94+
FROM generate_subscripts(d.indkey, 1) AS k
95+
ORDER BY k
96+
) AS columns
9297
FROM pg_class t
9398
INNER JOIN pg_index d ON t.oid = d.indrelid
9499
INNER JOIN pg_class i ON d.indexrelid = i.oid
@@ -105,9 +110,10 @@ def indexes(table_name) # :nodoc:
105110
unique = row[1]
106111
indkey = row[2].split(" ").map(&:to_i)
107112
inddef = row[3]
108-
oid = row[4]
109-
comment = row[5]
110-
valid = row[6]
113+
comment = row[4]
114+
valid = row[5]
115+
columns = row[6]
116+
111117
using, expressions, include, nulls_not_distinct, where = inddef.scan(/ USING (\w+?) \((.+?)\)(?: INCLUDE \((.+?)\))?( NULLS NOT DISTINCT)?(?: WHERE (.+))?\z/m).flatten
112118

113119
orders = {}
@@ -117,7 +123,8 @@ def indexes(table_name) # :nodoc:
117123
if indkey.include?(0)
118124
columns = expressions
119125
else
120-
columns = column_names_from_column_numbers(oid, indkey)
126+
decoder = PG::TextDecoder::Array.new
127+
columns = decoder.decode(columns)
121128

122129
# prevent INCLUDE columns from being matched
123130
columns.reject! { |c| include_columns.include?(c) }

0 commit comments

Comments
 (0)