@@ -143,7 +143,7 @@ RETURNS text AS $$
143
143
DECLARE
144
144
q text = ' ' ;
145
145
tab regclass = selector; -- For clarity
146
- cols name [] = ARRAY[]::name [];
146
+ cols text [] = ARRAY[]::text [];
147
147
col name;
148
148
sub record;
149
149
pk text = NULL ;
@@ -179,36 +179,42 @@ BEGIN
179
179
|| format(E' SELECT to_json(%1$I) AS %4$I FROM %1$I\n '
180
180
' WHERE %1$I.%2$I = %3$I.%4$I' ,
181
181
fks[1 ].other, fks[1 ].refs[1 ], tab, col);
182
- cols := cols
183
- || name(format(' %I.%I' , ' sub/' || cardinality(subselects), col));
182
+ cols := cols || format(' %I.%I' , ' sub/' || cardinality(subselects), col);
184
183
ELSE
185
- cols := cols || name( format(' %I' , col) );
184
+ cols := cols || format(' %I' , col);
186
185
END IF;
187
186
WHEN FOUND AND sub .body IS NOT NULL THEN -- Index into a column
188
187
subselects := subselects || graphql .to_sql (sub .selector ,
189
188
sub .predicate ,
190
189
sub .body ,
191
190
tab);
192
- cols := cols
193
- || name(format(' %I.%I' , ' sub/' || cardinality(subselects), col));
191
+ cols := cols || format(' %I.%I' , ' sub/' || cardinality(subselects), col);
194
192
WHEN NOT FOUND THEN -- It might be a reference to another table
195
193
subselects := subselects || graphql .to_sql (regclass(sub .selector ),
196
194
sub .predicate ,
197
195
sub .body ,
198
196
tab);
199
197
cols := cols
200
- || name( format(' %I.%I' ,
201
- ' sub/' || cardinality(subselects),
202
- sub .selector ) );
198
+ || format(' %I.%I' ,
199
+ ' sub/' || cardinality(subselects),
200
+ sub .selector );
203
201
ELSE
204
202
RAISE EXCEPTION ' Not able to interpret this selector: %' , sub .selector ;
205
203
END CASE;
206
204
END LOOP;
207
205
DECLARE
208
206
column_expression text ;
209
207
BEGIN
210
- IF cols > ARRAY[]::name[] THEN
211
- column_expression := array_to_string(cols, ' , ' );
208
+ IF cols > ARRAY[]::text [] THEN
209
+ -- - We want a temporary record type to to pass to json_agg or to_json as
210
+ -- - a single parameter so that column names are preserved. So we select
211
+ -- - all the columns into a subselect with LATERAL and then reference the
212
+ -- - subselect. This subselect should always be the last one in the
213
+ -- - sequence, since it needs to reference "columns" created in the other
214
+ -- - subselects.
215
+ subselects := subselects
216
+ || format(' SELECT %s' , array_to_string(cols, ' , ' ));
217
+ column_expression := format(' %I' , ' sub/' || cardinality(subselects));
212
218
ELSE
213
219
column_expression := format(' %I' , tab);
214
220
END IF;
0 commit comments