int varno = ((RangeTblRef *) jtnode)->rtindex;
RangeTblEntry *rte = rt_fetch(varno, query->rtable);
char *refname = get_rtable_name(varno, context);
- bool gavealias = false;
+ bool printalias;
if (rte->lateral)
appendStringInfoString(buf, "LATERAL ");
+ /* Print the FROM item proper */
switch (rte->rtekind)
{
case RTE_RELATION:
break;
}
+ /* Print the relation alias, if needed */
+ printalias = false;
if (rte->alias != NULL)
{
/* Always print alias if user provided one */
- appendStringInfo(buf, " %s", quote_identifier(refname));
- gavealias = true;
+ printalias = true;
}
else if (rte->rtekind == RTE_RELATION)
{
* resolve a conflict).
*/
if (strcmp(refname, get_relation_name(rte->relid)) != 0)
- {
- appendStringInfo(buf, " %s", quote_identifier(refname));
- gavealias = true;
- }
+ printalias = true;
}
else if (rte->rtekind == RTE_FUNCTION)
{
* renaming of the function and/or instability of the
* FigureColname rules for things that aren't simple functions.
*/
- appendStringInfo(buf, " %s", quote_identifier(refname));
- gavealias = true;
+ printalias = true;
+ }
+ else if (rte->rtekind == RTE_CTE)
+ {
+ /*
+ * No need to print alias if it's same as CTE name (this would
+ * normally be the case, but not if set_rtable_names had to
+ * resolve a conflict).
+ */
+ if (strcmp(refname, rte->ctename) != 0)
+ printalias = true;
}
+ if (printalias)
+ appendStringInfo(buf, " %s", quote_identifier(refname));
+ /* Print the column definitions or aliases, if needed */
if (rte->rtekind == RTE_FUNCTION)
{
if (rte->funccoltypes != NIL)
{
/* Function returning RECORD, reconstruct the columndefs */
- if (!gavealias)
+ if (!printalias)
appendStringInfo(buf, " AS ");
get_from_clause_coldeflist(rte->eref->colnames,
rte->funccoltypes,
FROM subdepartment;
(1 row)
+-- Another reverse-listing example
+CREATE VIEW sums_1_100 AS
+WITH RECURSIVE t(n) AS (
+ VALUES (1)
+UNION ALL
+ SELECT n+1 FROM t WHERE n < 100
+)
+SELECT sum(n) FROM t;
+\d+ sums_1_100
+ View "public.sums_1_100"
+ Column | Type | Modifiers | Storage | Description
+--------+--------+-----------+---------+-------------
+ sum | bigint | | plain |
+View definition:
+ WITH RECURSIVE t(n) AS (
+ VALUES (1)
+ UNION ALL
+ SELECT t_1.n + 1
+ FROM t t_1
+ WHERE t_1.n < 100
+ )
+ SELECT sum(t.n) AS sum
+ FROM t;
+
-- corner case in which sub-WITH gets initialized first
with recursive q as (
select * from department
SELECT pg_get_viewdef('vsubdepartment'::regclass);
SELECT pg_get_viewdef('vsubdepartment'::regclass, true);
+-- Another reverse-listing example
+CREATE VIEW sums_1_100 AS
+WITH RECURSIVE t(n) AS (
+ VALUES (1)
+UNION ALL
+ SELECT n+1 FROM t WHERE n < 100
+)
+SELECT sum(n) FROM t;
+
+\d+ sums_1_100
+
-- corner case in which sub-WITH gets initialized first
with recursive q as (
select * from department