From 9c096d456b185ce9ce8ec9861d78aa6a27a6997f Mon Sep 17 00:00:00 2001
From: Henson Choi <assam258@gmail.com>
Date: Fri, 2 Oct 2026 22:48:31 +0900
Subject: [PATCH v1 2/2] Fix alias lists of function RTEs whose composite type
 gained columns

expandRTE() reports as many columns of a function that returns a
composite type as the type had when the query was parsed, but a
reparsed query sees the columns added since, after the other columns
of their function, so in the middle of the columns of the RTE when it
has several functions or an ordinality column.  The column alias list
printed from the parse-time columns was therefore applied to the
wrong columns, or was too short.  Find out how many columns each
function has now, and put the names of the new ones in new_colnames[]
right after the last parse-time column of their function, or first
for leading functions that had no columns.

Backpatch-through: 15
---
 src/backend/utils/adt/ruleutils.c        | 166 ++++++++++++++++++-----
 src/test/regress/expected/rangefuncs.out |  79 +++++------
 src/test/regress/sql/rangefuncs.sql      |   7 +-
 3 files changed, 171 insertions(+), 81 deletions(-)

diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index e9c1c9db1b1..0a9589e1238 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -381,6 +381,10 @@ static void set_simple_column_names(deparse_namespace *dpns);
 static bool has_dangerous_join_using(deparse_namespace *dpns, Node *jtnode);
 static void set_using_names(deparse_namespace *dpns, Node *jtnode,
 							List *parentUsing);
+static void add_function_new_colnames(List *funcnewcols, List *funcendcols,
+									  int endcol, int *next_new_col,
+									  deparse_namespace *dpns,
+									  deparse_columns *colinfo);
 static void set_relation_column_names(deparse_namespace *dpns,
 									  RangeTblEntry *rte,
 									  deparse_columns *colinfo);
@@ -4372,6 +4376,45 @@ set_using_names(deparse_namespace *dpns, Node *jtnode, List *parentUsing)
 			 (int) nodeTag(jtnode));
 }
 
+/*
+ * add_function_new_colnames: append to new_colnames[] the columns that
+ * functions have gained since parse time, for the functions whose parse-time
+ * columns end at column number endcol of the RTE (0 for leading functions
+ * that had no columns).  Such columns have no varattno, so they appear only
+ * in new_colnames[].  *next_new_col is the next free slot there; it is
+ * advanced.
+ */
+static void
+add_function_new_colnames(List *funcnewcols, List *funcendcols, int endcol,
+						  int *next_new_col, deparse_namespace *dpns,
+						  deparse_columns *colinfo)
+{
+	ListCell   *lcn;
+	ListCell   *lce;
+
+	forboth(lcn, funcnewcols, lce, funcendcols)
+	{
+		if (lfirst_int(lce) != endcol)
+			continue;
+		foreach_ptr(char, newname, (List *) lfirst(lcn))
+		{
+			newname = make_colname_unique(newname, dpns, colinfo);
+			add_to_names_hash(colinfo, newname);
+			colinfo->new_colnames[*next_new_col] = newname;
+			colinfo->is_new_col[*next_new_col] = true;
+			(*next_new_col)++;
+
+			/*
+			 * Without a names hash, colname_is_unique finds a name that is
+			 * not in colnames[], such as this one, only by scanning
+			 * new_colnames[] up to num_new_cols.  The entries before
+			 * *next_new_col are all filled in.
+			 */
+			colinfo->num_new_cols = *next_new_col;
+		}
+	}
+}
+
 /*
  * set_relation_column_names: select column aliases for a non-join RTE
  *
@@ -4389,6 +4432,9 @@ set_relation_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
 	int			noldcolumns;
 	int			i;
 	int			j;
+	List	   *funcnewcols = NIL;	/* per function: new column names */
+	List	   *funcendcols = NIL;	/* per function: parse-time end column */
+	int			nfuncnew = 0;
 
 	/*
 	 * Construct an array of the current "real" column names of the RTE.
@@ -4441,9 +4487,49 @@ set_relation_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
 		 */
 		if (rte->rtekind == RTE_FUNCTION && rte->functions != NIL)
 		{
+			int			endcol = 0;
+
 			/* Since we're not creating Vars, rtindex etc. don't matter */
 			expandRTE(rte, 1, 0, VAR_RETURNING_DEFAULT, -1,
 					  true /* include dropped */ , &colnames, NULL);
+
+			/*
+			 * expandRTE() reports only as many columns of a function that
+			 * returns a composite type as there were at parse time, but a
+			 * reparsed query would see the columns added since, in the middle
+			 * of the RTE's columns if there are several functions or an
+			 * ordinality column.  Find out which functions got new columns,
+			 * and where they go.
+			 */
+			foreach(lc, rte->functions)
+			{
+				RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
+				TupleDesc	tupdesc;
+				TypeFuncClass functypclass;
+				List	   *newcols = NIL;
+
+				functypclass = get_expr_result_type(rtfunc->funcexpr, NULL,
+													&tupdesc);
+				if (functypclass == TYPEFUNC_COMPOSITE ||
+					functypclass == TYPEFUNC_COMPOSITE_DOMAIN)
+				{
+					Assert(tupdesc);
+					for (i = rtfunc->funccolcount; i < tupdesc->natts; i++)
+					{
+						Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
+
+						if (!attr->attisdropped)
+						{
+							newcols = lappend(newcols,
+											  pstrdup(NameStr(attr->attname)));
+							nfuncnew++;
+						}
+					}
+				}
+				endcol += rtfunc->funccolcount;
+				funcnewcols = lappend(funcnewcols, newcols);
+				funcendcols = lappend_int(funcendcols, endcol);
+			}
 		}
 		else
 			colnames = rte->eref->colnames;
@@ -4481,12 +4567,14 @@ set_relation_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
 	/*
 	 * Make sufficiently large new_colnames and is_new_col arrays, too.
 	 *
-	 * Note: because we leave colinfo->num_new_cols zero until after the loop,
-	 * colname_is_unique will not consult that array, which is fine because it
-	 * would only be duplicate effort.
+	 * Note: we leave colinfo->num_new_cols zero until after the loop, except
+	 * that add_function_new_colnames() advances it, because the names that
+	 * function adds are only in new_colnames[].  For the other columns,
+	 * colname_is_unique need not consult that array: their names are in
+	 * colnames[] as well.
 	 */
-	colinfo->new_colnames = palloc_array(char *, ncolumns);
-	colinfo->is_new_col = palloc_array(bool, ncolumns);
+	colinfo->new_colnames = palloc_array(char *, ncolumns + nfuncnew);
+	colinfo->is_new_col = palloc_array(bool, ncolumns + nfuncnew);
 
 	/* If the RTE is wide enough, use a hash table to avoid O(N^2) costs */
 	build_colinfo_names_hash(colinfo);
@@ -4496,11 +4584,17 @@ set_relation_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
 	 * colinfo->colnames and colinfo->new_colnames.  The former array has NULL
 	 * entries for dropped columns, the latter omits them.  Also mark
 	 * new_colnames entries as to whether they are new since parse time; this
-	 * is the case for entries beyond the length of rte->eref->colnames.
+	 * is the case for entries beyond the length of rte->eref->colnames, and
+	 * for the columns that a function has got since parse time (which
+	 * add_function_new_colnames() adds, possibly in the middle).
 	 */
 	noldcolumns = list_length(rte->eref->colnames);
 	changed_any = false;
 	j = 0;
+
+	/* New columns of leading functions that had no columns come first */
+	add_function_new_colnames(funcnewcols, funcendcols, 0, &j, dpns, colinfo);
+
 	for (i = 0; i < ncolumns; i++)
 	{
 		char	   *real_colname = real_colnames[i];
@@ -4510,34 +4604,42 @@ set_relation_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
 		if (real_colname == NULL)
 		{
 			Assert(colname == NULL);	/* colnames[i] is already NULL */
-			continue;
 		}
-
-		/* If alias already assigned, that's what to use */
-		if (colname == NULL)
+		else
 		{
-			/* If user wrote an alias, prefer that over real column name */
-			if (rte->alias && i < list_length(rte->alias->colnames))
-				colname = strVal(list_nth(rte->alias->colnames, i));
-			else
-				colname = real_colname;
+			/* If alias already assigned, that's what to use */
+			if (colname == NULL)
+			{
+				/* If user wrote an alias, prefer that over real column name */
+				if (rte->alias && i < list_length(rte->alias->colnames))
+					colname = strVal(list_nth(rte->alias->colnames, i));
+				else
+					colname = real_colname;
 
-			/* Unique-ify and insert into colinfo */
-			colname = make_colname_unique(colname, dpns, colinfo);
+				/* Unique-ify and insert into colinfo */
+				colname = make_colname_unique(colname, dpns, colinfo);
 
-			colinfo->colnames[i] = colname;
-			add_to_names_hash(colinfo, colname);
-		}
+				colinfo->colnames[i] = colname;
+				add_to_names_hash(colinfo, colname);
+			}
 
-		/* Put names of non-dropped columns in new_colnames[] too */
-		colinfo->new_colnames[j] = colname;
-		/* And mark them as new or not */
-		colinfo->is_new_col[j] = (i >= noldcolumns);
-		j++;
+			/* Put names of non-dropped columns in new_colnames[] too */
+			colinfo->new_colnames[j] = colname;
+			/* And mark them as new or not */
+			colinfo->is_new_col[j] = (i >= noldcolumns);
+			j++;
 
-		/* Remember if any assigned aliases differ from "real" name */
-		if (!changed_any && strcmp(colname, real_colname) != 0)
-			changed_any = true;
+			/* Remember if any assigned aliases differ from "real" name */
+			if (!changed_any && strcmp(colname, real_colname) != 0)
+				changed_any = true;
+		}
+
+		/*
+		 * If this is the last parse-time column of a function that has got
+		 * new columns, they come right after it.
+		 */
+		add_function_new_colnames(funcnewcols, funcendcols, i + 1, &j,
+								  dpns, colinfo);
 	}
 
 	/* We're now done needing the colinfo's names_hash */
@@ -4545,9 +4647,11 @@ set_relation_column_names(deparse_namespace *dpns, RangeTblEntry *rte,
 
 	/*
 	 * Set correct length for new_colnames[] array.  (Note: if columns have
-	 * been added, colinfo->num_cols includes them, which is not really quite
-	 * right but is harmless, since any new columns must be at the end where
-	 * they won't affect varattnos of pre-existing columns.)
+	 * been added to a relation, colinfo->num_cols includes them, which is not
+	 * really quite right but is harmless, since any new columns must be at
+	 * the end where they won't affect varattnos of pre-existing columns.  The
+	 * columns that a function has got since parse time are not counted in
+	 * num_cols; they have no varattno.)
 	 */
 	colinfo->num_new_cols = j;
 
diff --git a/src/test/regress/expected/rangefuncs.out b/src/test/regress/expected/rangefuncs.out
index f1a6642f6f5..79e0ed7dd1a 100644
--- a/src/test/regress/expected/rangefuncs.out
+++ b/src/test/regress/expected/rangefuncs.out
@@ -2507,7 +2507,7 @@ ERROR:  function return row and query-specified return row do not match
 DETAIL:  Returned row contains 1 attribute, but query expects 2.
 -- Columns added to the composite types that functions return show up in the
 -- middle of the columns of the RTE, so the column alias list has to make room
--- for them
+-- for them; leave the objects around for the pg_upgrade test
 create type rngfunc_t0 as (a int);
 create function rngfunc_f0() returns rngfunc_t0
   language sql as 'select null::rngfunc_t0';
@@ -2519,15 +2519,13 @@ select format('create view rngfunc_one_v2 as %s',
 \gexec
 create view rngfunc_one_v2 as  SELECT a,
     ordinality
-   FROM rngfunc_f0() WITH ORDINALITY rngfunc_f0(a, ordinality)
-ERROR:  column reference "ordinality" is ambiguous
-LINE 2:     ordinality
-            ^
+   FROM rngfunc_f0() WITH ORDINALITY rngfunc_f0(a, x, ordinality)
 select * from rngfunc_one_v2;
-ERROR:  relation "rngfunc_one_v2" does not exist
-LINE 1: select * from rngfunc_one_v2;
-                      ^
-drop view rngfunc_one_v;
+ a | ordinality 
+---+------------
+   |          1
+(1 row)
+
 -- The same for a function that returns a domain over a composite type
 create type rngfunc_t1 as (a int);
 create domain rngfunc_d1 as rngfunc_t1;
@@ -2541,15 +2539,13 @@ select format('create view rngfunc_dom_v2 as %s',
 \gexec
 create view rngfunc_dom_v2 as  SELECT a,
     ordinality
-   FROM rngfunc_f1() WITH ORDINALITY rngfunc_f1(a, ordinality)
-ERROR:  column reference "ordinality" is ambiguous
-LINE 2:     ordinality
-            ^
+   FROM rngfunc_f1() WITH ORDINALITY rngfunc_f1(a, x, ordinality)
 select * from rngfunc_dom_v2;
-ERROR:  relation "rngfunc_dom_v2" does not exist
-LINE 1: select * from rngfunc_dom_v2;
-                      ^
-drop view rngfunc_dom_v;
+ a | ordinality 
+---+------------
+   |          1
+(1 row)
+
 -- Without ordinality, the aliases after the new columns of a function shift
 create type rngfunc_t2 as (a int);
 create type rngfunc_t3 as (b int);
@@ -2573,14 +2569,13 @@ select format('create view rngfunc_alias_v2 as %s',
 \gexec
 create view rngfunc_alias_v2 as  SELECT m,
     n
-   FROM ROWS FROM(rngfunc_f2(), rngfunc_f3()) r(m, n)
+   FROM ROWS FROM(rngfunc_f2(), rngfunc_f3()) r(m, c, n)
 select * from rngfunc_alias_v2;
- m | n  
----+----
- 1 | 99
+ m | n 
+---+---
+ 1 | 2
 (1 row)
 
-drop view rngfunc_alias_v;
 -- With both, for a function that had no columns and a column named ordinality
 create type rngfunc_t4 as ();
 create type rngfunc_t5 as (a int);
@@ -2617,27 +2612,25 @@ select * from rows from (rngfunc_f4(), rngfunc_f5()) with ordinality;
 (1 row)
 
 select pg_get_viewdef('rngfunc_grown_v'::regclass);
-                                      pg_get_viewdef                                      
-------------------------------------------------------------------------------------------
-  SELECT a,                                                                              +
-     ordinality                                                                          +
-    FROM ROWS FROM(rngfunc_f4(), rngfunc_f5()) WITH ORDINALITY rngfunc_f4(a, ordinality);
+                                              pg_get_viewdef                                               
+-----------------------------------------------------------------------------------------------------------
+  SELECT a,                                                                                               +
+     ordinality_1 AS ordinality                                                                           +
+    FROM ROWS FROM(rngfunc_f4(), rngfunc_f5()) WITH ORDINALITY rngfunc_f4(x, a, ordinality, ordinality_1);
 (1 row)
 
 select format('create view rngfunc_grown_v2 as %s',
               rtrim(pg_get_viewdef('rngfunc_grown_v'::regclass), ';'))
 \gexec
 create view rngfunc_grown_v2 as  SELECT a,
-    ordinality
-   FROM ROWS FROM(rngfunc_f4(), rngfunc_f5()) WITH ORDINALITY rngfunc_f4(a, ordinality)
-ERROR:  column reference "ordinality" is ambiguous
-LINE 2:     ordinality
-            ^
+    ordinality_1 AS ordinality
+   FROM ROWS FROM(rngfunc_f4(), rngfunc_f5()) WITH ORDINALITY rngfunc_f4(x, a, ordinality, ordinality_1)
 select * from rngfunc_grown_v2;
-ERROR:  relation "rngfunc_grown_v2" does not exist
-LINE 1: select * from rngfunc_grown_v2;
-                      ^
-drop view rngfunc_grown_v;
+ a | ordinality 
+---+------------
+ 1 |          1
+(1 row)
+
 -- New columns after a dropped last column, renamed away from an earlier one
 create type rngfunc_t6 as (a int, b int);
 create type rngfunc_t7 as ();
@@ -2655,12 +2648,10 @@ select format('create view rngfunc_drop_v2 as %s',
 \gexec
 create view rngfunc_drop_v2 as  SELECT a,
     ordinality
-   FROM ROWS FROM(rngfunc_f6(), rngfunc_f7()) WITH ORDINALITY rngfunc_f6(a, ordinality)
-ERROR:  column reference "ordinality" is ambiguous
-LINE 2:     ordinality
-            ^
+   FROM ROWS FROM(rngfunc_f6(), rngfunc_f7()) WITH ORDINALITY rngfunc_f6(a, a_1, ordinality)
 select * from rngfunc_drop_v2;
-ERROR:  relation "rngfunc_drop_v2" does not exist
-LINE 1: select * from rngfunc_drop_v2;
-                      ^
-drop view rngfunc_drop_v;
+ a | ordinality 
+---+------------
+   |          1
+(1 row)
+
diff --git a/src/test/regress/sql/rangefuncs.sql b/src/test/regress/sql/rangefuncs.sql
index 3a64e135013..920c061e519 100644
--- a/src/test/regress/sql/rangefuncs.sql
+++ b/src/test/regress/sql/rangefuncs.sql
@@ -828,7 +828,7 @@ select * from int8_tbl, coalesce(row(1)) as (a int, b int);  -- fail
 
 -- Columns added to the composite types that functions return show up in the
 -- middle of the columns of the RTE, so the column alias list has to make room
--- for them
+-- for them; leave the objects around for the pg_upgrade test
 create type rngfunc_t0 as (a int);
 create function rngfunc_f0() returns rngfunc_t0
   language sql as 'select null::rngfunc_t0';
@@ -839,7 +839,6 @@ select format('create view rngfunc_one_v2 as %s',
               rtrim(pg_get_viewdef('rngfunc_one_v'::regclass), ';'))
 \gexec
 select * from rngfunc_one_v2;
-drop view rngfunc_one_v;
 
 -- The same for a function that returns a domain over a composite type
 create type rngfunc_t1 as (a int);
@@ -853,7 +852,6 @@ select format('create view rngfunc_dom_v2 as %s',
               rtrim(pg_get_viewdef('rngfunc_dom_v'::regclass), ';'))
 \gexec
 select * from rngfunc_dom_v2;
-drop view rngfunc_dom_v;
 
 -- Without ordinality, the aliases after the new columns of a function shift
 create type rngfunc_t2 as (a int);
@@ -872,7 +870,6 @@ select format('create view rngfunc_alias_v2 as %s',
               rtrim(pg_get_viewdef('rngfunc_alias_v'::regclass), ';'))
 \gexec
 select * from rngfunc_alias_v2;
-drop view rngfunc_alias_v;
 
 -- With both, for a function that had no columns and a column named ordinality
 create type rngfunc_t4 as ();
@@ -899,7 +896,6 @@ select format('create view rngfunc_grown_v2 as %s',
               rtrim(pg_get_viewdef('rngfunc_grown_v'::regclass), ';'))
 \gexec
 select * from rngfunc_grown_v2;
-drop view rngfunc_grown_v;
 
 -- New columns after a dropped last column, renamed away from an earlier one
 create type rngfunc_t6 as (a int, b int);
@@ -917,4 +913,3 @@ select format('create view rngfunc_drop_v2 as %s',
               rtrim(pg_get_viewdef('rngfunc_drop_v'::regclass), ';'))
 \gexec
 select * from rngfunc_drop_v2;
-drop view rngfunc_drop_v;
-- 
2.54.0 (Apple Git-157)

