PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
parse_clause.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * parse_clause.c
4  * handle clauses in parser
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/parser/parse_clause.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 
16 #include "postgres.h"
17 
18 #include "miscadmin.h"
19 
20 #include "access/heapam.h"
21 #include "access/tsmapi.h"
22 #include "catalog/catalog.h"
23 #include "catalog/heap.h"
24 #include "catalog/pg_am.h"
25 #include "catalog/pg_collation.h"
27 #include "catalog/pg_type.h"
28 #include "commands/defrem.h"
29 #include "nodes/makefuncs.h"
30 #include "nodes/nodeFuncs.h"
31 #include "optimizer/tlist.h"
32 #include "optimizer/var.h"
33 #include "parser/analyze.h"
34 #include "parser/parsetree.h"
35 #include "parser/parser.h"
36 #include "parser/parse_clause.h"
37 #include "parser/parse_coerce.h"
38 #include "parser/parse_collate.h"
39 #include "parser/parse_expr.h"
40 #include "parser/parse_func.h"
41 #include "parser/parse_oper.h"
42 #include "parser/parse_relation.h"
43 #include "parser/parse_target.h"
44 #include "parser/parse_type.h"
45 #include "rewrite/rewriteManip.h"
46 #include "utils/guc.h"
47 #include "utils/lsyscache.h"
48 #include "utils/rel.h"
49 
50 
51 /* Convenience macro for the most common makeNamespaceItem() case */
52 #define makeDefaultNSItem(rte) makeNamespaceItem(rte, true, true, false, true)
53 
54 static void extractRemainingColumns(List *common_colnames,
55  List *src_colnames, List *src_colvars,
56  List **res_colnames, List **res_colvars);
58  RangeTblEntry *leftRTE, RangeTblEntry *rightRTE,
59  List *leftVars, List *rightVars);
60 static Node *transformJoinOnClause(ParseState *pstate, JoinExpr *j,
61  List *namespace);
64  CommonTableExpr *cte, Index levelsup);
66  RangeSubselect *r);
68  RangeFunction *r);
70  RangeTableFunc *t);
72  RangeTableSample *rts);
73 static Node *transformFromClauseItem(ParseState *pstate, Node *n,
74  RangeTblEntry **top_rte, int *top_rti,
75  List **namespace);
76 static Node *buildMergedJoinVar(ParseState *pstate, JoinType jointype,
77  Var *l_colvar, Var *r_colvar);
79  bool rel_visible, bool cols_visible,
80  bool lateral_only, bool lateral_ok);
81 static void setNamespaceColumnVisibility(List *namespace, bool cols_visible);
82 static void setNamespaceLateralState(List *namespace,
83  bool lateral_only, bool lateral_ok);
84 static void checkExprIsVarFree(ParseState *pstate, Node *n,
85  const char *constructName);
87  List **tlist, ParseExprKind exprKind);
89  List **tlist, ParseExprKind exprKind);
90 static int get_matching_location(int sortgroupref,
91  List *sortgrouprefs, List *exprs);
93  Relation heapRel);
94 static List *addTargetToGroupList(ParseState *pstate, TargetEntry *tle,
95  List *grouplist, List *targetlist, int location);
96 static WindowClause *findWindowClause(List *wclist, const char *name);
97 static Node *transformFrameOffset(ParseState *pstate, int frameOptions,
98  Node *clause);
99 
100 
101 /*
102  * transformFromClause -
103  * Process the FROM clause and add items to the query's range table,
104  * joinlist, and namespace.
105  *
106  * Note: we assume that the pstate's p_rtable, p_joinlist, and p_namespace
107  * lists were initialized to NIL when the pstate was created.
108  * We will add onto any entries already present --- this is needed for rule
109  * processing, as well as for UPDATE and DELETE.
110  */
111 void
113 {
114  ListCell *fl;
115 
116  /*
117  * The grammar will have produced a list of RangeVars, RangeSubselects,
118  * RangeFunctions, and/or JoinExprs. Transform each one (possibly adding
119  * entries to the rtable), check for duplicate refnames, and then add it
120  * to the joinlist and namespace.
121  *
122  * Note we must process the items left-to-right for proper handling of
123  * LATERAL references.
124  */
125  foreach(fl, frmList)
126  {
127  Node *n = lfirst(fl);
128  RangeTblEntry *rte;
129  int rtindex;
130  List *namespace;
131 
132  n = transformFromClauseItem(pstate, n,
133  &rte,
134  &rtindex,
135  &namespace);
136 
137  checkNameSpaceConflicts(pstate, pstate->p_namespace, namespace);
138 
139  /* Mark the new namespace items as visible only to LATERAL */
140  setNamespaceLateralState(namespace, true, true);
141 
142  pstate->p_joinlist = lappend(pstate->p_joinlist, n);
143  pstate->p_namespace = list_concat(pstate->p_namespace, namespace);
144  }
145 
146  /*
147  * We're done parsing the FROM list, so make all namespace items
148  * unconditionally visible. Note that this will also reset lateral_only
149  * for any namespace items that were already present when we were called;
150  * but those should have been that way already.
151  */
152  setNamespaceLateralState(pstate->p_namespace, false, true);
153 }
154 
155 /*
156  * setTargetTable
157  * Add the target relation of INSERT/UPDATE/DELETE to the range table,
158  * and make the special links to it in the ParseState.
159  *
160  * We also open the target relation and acquire a write lock on it.
161  * This must be done before processing the FROM list, in case the target
162  * is also mentioned as a source relation --- we want to be sure to grab
163  * the write lock before any read lock.
164  *
165  * If alsoSource is true, add the target to the query's joinlist and
166  * namespace. For INSERT, we don't want the target to be joined to;
167  * it's a destination of tuples, not a source. For UPDATE/DELETE,
168  * we do need to scan or join the target. (NOTE: we do not bother
169  * to check for namespace conflict; we assume that the namespace was
170  * initially empty in these cases.)
171  *
172  * Finally, we mark the relation as requiring the permissions specified
173  * by requiredPerms.
174  *
175  * Returns the rangetable index of the target relation.
176  */
177 int
178 setTargetTable(ParseState *pstate, RangeVar *relation,
179  bool inh, bool alsoSource, AclMode requiredPerms)
180 {
181  RangeTblEntry *rte;
182  int rtindex;
183 
184  /* Close old target; this could only happen for multi-action rules */
185  if (pstate->p_target_relation != NULL)
187 
188  /*
189  * Open target rel and grab suitable lock (which we will hold till end of
190  * transaction).
191  *
192  * free_parsestate() will eventually do the corresponding heap_close(),
193  * but *not* release the lock.
194  */
195  pstate->p_target_relation = parserOpenTable(pstate, relation,
197 
198  /*
199  * Now build an RTE.
200  */
201  rte = addRangeTableEntryForRelation(pstate, pstate->p_target_relation,
202  relation->alias, inh, false);
203  pstate->p_target_rangetblentry = rte;
204 
205  /* assume new rte is at end */
206  rtindex = list_length(pstate->p_rtable);
207  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
208 
209  /*
210  * Override addRangeTableEntry's default ACL_SELECT permissions check, and
211  * instead mark target table as requiring exactly the specified
212  * permissions.
213  *
214  * If we find an explicit reference to the rel later during parse
215  * analysis, we will add the ACL_SELECT bit back again; see
216  * markVarForSelectPriv and its callers.
217  */
218  rte->requiredPerms = requiredPerms;
219 
220  /*
221  * If UPDATE/DELETE, add table to joinlist and namespace.
222  *
223  * Note: some callers know that they can find the new ParseNamespaceItem
224  * at the end of the pstate->p_namespace list. This is a bit ugly but not
225  * worth complicating this function's signature for.
226  */
227  if (alsoSource)
228  addRTEtoQuery(pstate, rte, true, true, true);
229 
230  return rtindex;
231 }
232 
233 /*
234  * Given a relation-options list (of DefElems), return true iff the specified
235  * table/result set should be created with OIDs. This needs to be done after
236  * parsing the query string because the return value can depend upon the
237  * default_with_oids GUC var.
238  *
239  * In some situations, we want to reject an OIDS option even if it's present.
240  * That's (rather messily) handled here rather than reloptions.c, because that
241  * code explicitly punts checking for oids to here.
242  */
243 bool
244 interpretOidsOption(List *defList, bool allowOids)
245 {
246  ListCell *cell;
247 
248  /* Scan list to see if OIDS was included */
249  foreach(cell, defList)
250  {
251  DefElem *def = (DefElem *) lfirst(cell);
252 
253  if (def->defnamespace == NULL &&
254  pg_strcasecmp(def->defname, "oids") == 0)
255  {
256  if (!allowOids)
257  ereport(ERROR,
258  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
259  errmsg("unrecognized parameter \"%s\"",
260  def->defname)));
261  return defGetBoolean(def);
262  }
263  }
264 
265  /* Force no-OIDS result if caller disallows OIDS. */
266  if (!allowOids)
267  return false;
268 
269  /* OIDS option was not specified, so use default. */
270  return default_with_oids;
271 }
272 
273 /*
274  * Extract all not-in-common columns from column lists of a source table
275  */
276 static void
277 extractRemainingColumns(List *common_colnames,
278  List *src_colnames, List *src_colvars,
279  List **res_colnames, List **res_colvars)
280 {
281  List *new_colnames = NIL;
282  List *new_colvars = NIL;
283  ListCell *lnames,
284  *lvars;
285 
286  Assert(list_length(src_colnames) == list_length(src_colvars));
287 
288  forboth(lnames, src_colnames, lvars, src_colvars)
289  {
290  char *colname = strVal(lfirst(lnames));
291  bool match = false;
292  ListCell *cnames;
293 
294  foreach(cnames, common_colnames)
295  {
296  char *ccolname = strVal(lfirst(cnames));
297 
298  if (strcmp(colname, ccolname) == 0)
299  {
300  match = true;
301  break;
302  }
303  }
304 
305  if (!match)
306  {
307  new_colnames = lappend(new_colnames, lfirst(lnames));
308  new_colvars = lappend(new_colvars, lfirst(lvars));
309  }
310  }
311 
312  *res_colnames = new_colnames;
313  *res_colvars = new_colvars;
314 }
315 
316 /* transformJoinUsingClause()
317  * Build a complete ON clause from a partially-transformed USING list.
318  * We are given lists of nodes representing left and right match columns.
319  * Result is a transformed qualification expression.
320  */
321 static Node *
323  RangeTblEntry *leftRTE, RangeTblEntry *rightRTE,
324  List *leftVars, List *rightVars)
325 {
326  Node *result;
327  List *andargs = NIL;
328  ListCell *lvars,
329  *rvars;
330 
331  /*
332  * We cheat a little bit here by building an untransformed operator tree
333  * whose leaves are the already-transformed Vars. This requires collusion
334  * from transformExpr(), which normally could be expected to complain
335  * about already-transformed subnodes. However, this does mean that we
336  * have to mark the columns as requiring SELECT privilege for ourselves;
337  * transformExpr() won't do it.
338  */
339  forboth(lvars, leftVars, rvars, rightVars)
340  {
341  Var *lvar = (Var *) lfirst(lvars);
342  Var *rvar = (Var *) lfirst(rvars);
343  A_Expr *e;
344 
345  /* Require read access to the join variables */
346  markVarForSelectPriv(pstate, lvar, leftRTE);
347  markVarForSelectPriv(pstate, rvar, rightRTE);
348 
349  /* Now create the lvar = rvar join condition */
350  e = makeSimpleA_Expr(AEXPR_OP, "=",
351  (Node *) copyObject(lvar), (Node *) copyObject(rvar),
352  -1);
353 
354  /* Prepare to combine into an AND clause, if multiple join columns */
355  andargs = lappend(andargs, e);
356  }
357 
358  /* Only need an AND if there's more than one join column */
359  if (list_length(andargs) == 1)
360  result = (Node *) linitial(andargs);
361  else
362  result = (Node *) makeBoolExpr(AND_EXPR, andargs, -1);
363 
364  /*
365  * Since the references are already Vars, and are certainly from the input
366  * relations, we don't have to go through the same pushups that
367  * transformJoinOnClause() does. Just invoke transformExpr() to fix up
368  * the operators, and we're done.
369  */
370  result = transformExpr(pstate, result, EXPR_KIND_JOIN_USING);
371 
372  result = coerce_to_boolean(pstate, result, "JOIN/USING");
373 
374  return result;
375 }
376 
377 /* transformJoinOnClause()
378  * Transform the qual conditions for JOIN/ON.
379  * Result is a transformed qualification expression.
380  */
381 static Node *
383 {
384  Node *result;
385  List *save_namespace;
386 
387  /*
388  * The namespace that the join expression should see is just the two
389  * subtrees of the JOIN plus any outer references from upper pstate
390  * levels. Temporarily set this pstate's namespace accordingly. (We need
391  * not check for refname conflicts, because transformFromClauseItem()
392  * already did.) All namespace items are marked visible regardless of
393  * LATERAL state.
394  */
395  setNamespaceLateralState(namespace, false, true);
396 
397  save_namespace = pstate->p_namespace;
398  pstate->p_namespace = namespace;
399 
400  result = transformWhereClause(pstate, j->quals,
401  EXPR_KIND_JOIN_ON, "JOIN/ON");
402 
403  pstate->p_namespace = save_namespace;
404 
405  return result;
406 }
407 
408 /*
409  * transformTableEntry --- transform a RangeVar (simple relation reference)
410  */
411 static RangeTblEntry *
413 {
414  RangeTblEntry *rte;
415 
416  /* We need only build a range table entry */
417  rte = addRangeTableEntry(pstate, r, r->alias, r->inh, true);
418 
419  return rte;
420 }
421 
422 /*
423  * transformCTEReference --- transform a RangeVar that references a common
424  * table expression (ie, a sub-SELECT defined in a WITH clause)
425  */
426 static RangeTblEntry *
428  CommonTableExpr *cte, Index levelsup)
429 {
430  RangeTblEntry *rte;
431 
432  rte = addRangeTableEntryForCTE(pstate, cte, levelsup, r, true);
433 
434  return rte;
435 }
436 
437 /*
438  * transformRangeSubselect --- transform a sub-SELECT appearing in FROM
439  */
440 static RangeTblEntry *
442 {
443  Query *query;
444  RangeTblEntry *rte;
445 
446  /*
447  * We require user to supply an alias for a subselect, per SQL92. To relax
448  * this, we'd have to be prepared to gin up a unique alias for an
449  * unlabeled subselect. (This is just elog, not ereport, because the
450  * grammar should have enforced it already. It'd probably be better to
451  * report the error here, but we don't have a good error location here.)
452  */
453  if (r->alias == NULL)
454  elog(ERROR, "subquery in FROM must have an alias");
455 
456  /*
457  * Set p_expr_kind to show this parse level is recursing to a subselect.
458  * We can't be nested within any expression, so don't need save-restore
459  * logic here.
460  */
461  Assert(pstate->p_expr_kind == EXPR_KIND_NONE);
463 
464  /*
465  * If the subselect is LATERAL, make lateral_only names of this level
466  * visible to it. (LATERAL can't nest within a single pstate level, so we
467  * don't need save/restore logic here.)
468  */
469  Assert(!pstate->p_lateral_active);
470  pstate->p_lateral_active = r->lateral;
471 
472  /*
473  * Analyze and transform the subquery.
474  */
475  query = parse_sub_analyze(r->subquery, pstate, NULL,
476  isLockedRefname(pstate, r->alias->aliasname),
477  true);
478 
479  /* Restore state */
480  pstate->p_lateral_active = false;
481  pstate->p_expr_kind = EXPR_KIND_NONE;
482 
483  /*
484  * Check that we got a SELECT. Anything else should be impossible given
485  * restrictions of the grammar, but check anyway.
486  */
487  if (!IsA(query, Query) ||
488  query->commandType != CMD_SELECT)
489  elog(ERROR, "unexpected non-SELECT command in subquery in FROM");
490 
491  /*
492  * OK, build an RTE for the subquery.
493  */
494  rte = addRangeTableEntryForSubquery(pstate,
495  query,
496  r->alias,
497  r->lateral,
498  true);
499 
500  return rte;
501 }
502 
503 
504 /*
505  * transformRangeFunction --- transform a function call appearing in FROM
506  */
507 static RangeTblEntry *
509 {
510  List *funcexprs = NIL;
511  List *funcnames = NIL;
512  List *coldeflists = NIL;
513  bool is_lateral;
514  RangeTblEntry *rte;
515  ListCell *lc;
516 
517  /*
518  * We make lateral_only names of this level visible, whether or not the
519  * RangeFunction is explicitly marked LATERAL. This is needed for SQL
520  * spec compliance in the case of UNNEST(), and seems useful on
521  * convenience grounds for all functions in FROM.
522  *
523  * (LATERAL can't nest within a single pstate level, so we don't need
524  * save/restore logic here.)
525  */
526  Assert(!pstate->p_lateral_active);
527  pstate->p_lateral_active = true;
528 
529  /*
530  * Transform the raw expressions.
531  *
532  * While transforming, also save function names for possible use as alias
533  * and column names. We use the same transformation rules as for a SELECT
534  * output expression. For a FuncCall node, the result will be the
535  * function name, but it is possible for the grammar to hand back other
536  * node types.
537  *
538  * We have to get this info now, because FigureColname only works on raw
539  * parsetrees. Actually deciding what to do with the names is left up to
540  * addRangeTableEntryForFunction.
541  *
542  * Likewise, collect column definition lists if there were any. But
543  * complain if we find one here and the RangeFunction has one too.
544  */
545  foreach(lc, r->functions)
546  {
547  List *pair = (List *) lfirst(lc);
548  Node *fexpr;
549  List *coldeflist;
550 
551  /* Disassemble the function-call/column-def-list pairs */
552  Assert(list_length(pair) == 2);
553  fexpr = (Node *) linitial(pair);
554  coldeflist = (List *) lsecond(pair);
555 
556  /*
557  * If we find a function call unnest() with more than one argument and
558  * no special decoration, transform it into separate unnest() calls on
559  * each argument. This is a kluge, for sure, but it's less nasty than
560  * other ways of implementing the SQL-standard UNNEST() syntax.
561  *
562  * If there is any decoration (including a coldeflist), we don't
563  * transform, which probably means a no-such-function error later. We
564  * could alternatively throw an error right now, but that doesn't seem
565  * tremendously helpful. If someone is using any such decoration,
566  * then they're not using the SQL-standard syntax, and they're more
567  * likely expecting an un-tweaked function call.
568  *
569  * Note: the transformation changes a non-schema-qualified unnest()
570  * function name into schema-qualified pg_catalog.unnest(). This
571  * choice is also a bit debatable, but it seems reasonable to force
572  * use of built-in unnest() when we make this transformation.
573  */
574  if (IsA(fexpr, FuncCall))
575  {
576  FuncCall *fc = (FuncCall *) fexpr;
577 
578  if (list_length(fc->funcname) == 1 &&
579  strcmp(strVal(linitial(fc->funcname)), "unnest") == 0 &&
580  list_length(fc->args) > 1 &&
581  fc->agg_order == NIL &&
582  fc->agg_filter == NULL &&
583  !fc->agg_star &&
584  !fc->agg_distinct &&
585  !fc->func_variadic &&
586  fc->over == NULL &&
587  coldeflist == NIL)
588  {
589  ListCell *lc;
590 
591  foreach(lc, fc->args)
592  {
593  Node *arg = (Node *) lfirst(lc);
594  FuncCall *newfc;
595 
596  newfc = makeFuncCall(SystemFuncName("unnest"),
597  list_make1(arg),
598  fc->location);
599 
600  funcexprs = lappend(funcexprs,
601  transformExpr(pstate, (Node *) newfc,
603 
604  funcnames = lappend(funcnames,
605  FigureColname((Node *) newfc));
606 
607  /* coldeflist is empty, so no error is possible */
608 
609  coldeflists = lappend(coldeflists, coldeflist);
610  }
611  continue; /* done with this function item */
612  }
613  }
614 
615  /* normal case ... */
616  funcexprs = lappend(funcexprs,
617  transformExpr(pstate, fexpr,
619 
620  funcnames = lappend(funcnames,
621  FigureColname(fexpr));
622 
623  if (coldeflist && r->coldeflist)
624  ereport(ERROR,
625  (errcode(ERRCODE_SYNTAX_ERROR),
626  errmsg("multiple column definition lists are not allowed for the same function"),
627  parser_errposition(pstate,
628  exprLocation((Node *) r->coldeflist))));
629 
630  coldeflists = lappend(coldeflists, coldeflist);
631  }
632 
633  pstate->p_lateral_active = false;
634 
635  /*
636  * We must assign collations now so that the RTE exposes correct collation
637  * info for Vars created from it.
638  */
639  assign_list_collations(pstate, funcexprs);
640 
641  /*
642  * Install the top-level coldeflist if there was one (we already checked
643  * that there was no conflicting per-function coldeflist).
644  *
645  * We only allow this when there's a single function (even after UNNEST
646  * expansion) and no WITH ORDINALITY. The reason for the latter
647  * restriction is that it's not real clear whether the ordinality column
648  * should be in the coldeflist, and users are too likely to make mistakes
649  * in one direction or the other. Putting the coldeflist inside ROWS
650  * FROM() is much clearer in this case.
651  */
652  if (r->coldeflist)
653  {
654  if (list_length(funcexprs) != 1)
655  {
656  if (r->is_rowsfrom)
657  ereport(ERROR,
658  (errcode(ERRCODE_SYNTAX_ERROR),
659  errmsg("ROWS FROM() with multiple functions cannot have a column definition list"),
660  errhint("Put a separate column definition list for each function inside ROWS FROM()."),
661  parser_errposition(pstate,
662  exprLocation((Node *) r->coldeflist))));
663  else
664  ereport(ERROR,
665  (errcode(ERRCODE_SYNTAX_ERROR),
666  errmsg("UNNEST() with multiple arguments cannot have a column definition list"),
667  errhint("Use separate UNNEST() calls inside ROWS FROM(), and attach a column definition list to each one."),
668  parser_errposition(pstate,
669  exprLocation((Node *) r->coldeflist))));
670  }
671  if (r->ordinality)
672  ereport(ERROR,
673  (errcode(ERRCODE_SYNTAX_ERROR),
674  errmsg("WITH ORDINALITY cannot be used with a column definition list"),
675  errhint("Put the column definition list inside ROWS FROM()."),
676  parser_errposition(pstate,
677  exprLocation((Node *) r->coldeflist))));
678 
679  coldeflists = list_make1(r->coldeflist);
680  }
681 
682  /*
683  * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
684  * there are any lateral cross-references in it.
685  */
686  is_lateral = r->lateral || contain_vars_of_level((Node *) funcexprs, 0);
687 
688  /*
689  * OK, build an RTE for the function.
690  */
691  rte = addRangeTableEntryForFunction(pstate,
692  funcnames, funcexprs, coldeflists,
693  r, is_lateral, true);
694 
695  return rte;
696 }
697 
698 /*
699  * transformRangeTableFunc -
700  * Transform a raw RangeTableFunc into TableFunc.
701  *
702  * Transform the namespace clauses, the document-generating expression, the
703  * row-generating expression, the column-generating expressions, and the
704  * default value expressions.
705  */
706 static RangeTblEntry *
708 {
710  const char *constructName;
711  Oid docType;
712  RangeTblEntry *rte;
713  bool is_lateral;
714  ListCell *col;
715  char **names;
716  int colno;
717 
718  /* Currently only XMLTABLE is supported */
719  constructName = "XMLTABLE";
720  docType = XMLOID;
721 
722  /*
723  * We make lateral_only names of this level visible, whether or not the
724  * RangeTableFunc is explicitly marked LATERAL. This is needed for SQL
725  * spec compliance and seems useful on convenience grounds for all
726  * functions in FROM.
727  *
728  * (LATERAL can't nest within a single pstate level, so we don't need
729  * save/restore logic here.)
730  */
731  Assert(!pstate->p_lateral_active);
732  pstate->p_lateral_active = true;
733 
734  /* Transform and apply typecast to the row-generating expression ... */
735  Assert(rtf->rowexpr != NULL);
736  tf->rowexpr = coerce_to_specific_type(pstate,
738  TEXTOID,
739  constructName);
740  assign_expr_collations(pstate, tf->rowexpr);
741 
742  /* ... and to the document itself */
743  Assert(rtf->docexpr != NULL);
744  tf->docexpr = coerce_to_specific_type(pstate,
746  docType,
747  constructName);
748  assign_expr_collations(pstate, tf->docexpr);
749 
750  /* undef ordinality column number */
751  tf->ordinalitycol = -1;
752 
753 
754  names = palloc(sizeof(char *) * list_length(rtf->columns));
755 
756  colno = 0;
757  foreach(col, rtf->columns)
758  {
759  RangeTableFuncCol *rawc = (RangeTableFuncCol *) lfirst(col);
760  Oid typid;
761  int32 typmod;
762  Node *colexpr;
763  Node *coldefexpr;
764  int j;
765 
766  tf->colnames = lappend(tf->colnames,
767  makeString(pstrdup(rawc->colname)));
768 
769  /*
770  * Determine the type and typmod for the new column. FOR
771  * ORDINALITY columns are INTEGER per spec; the others are
772  * user-specified.
773  */
774  if (rawc->for_ordinality)
775  {
776  if (tf->ordinalitycol != -1)
777  ereport(ERROR,
778  (errcode(ERRCODE_SYNTAX_ERROR),
779  errmsg("only one FOR ORDINALITY column is allowed"),
780  parser_errposition(pstate, rawc->location)));
781 
782  typid = INT4OID;
783  typmod = -1;
784  tf->ordinalitycol = colno;
785  }
786  else
787  {
788  if (rawc->typeName->setof)
789  ereport(ERROR,
790  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
791  errmsg("column \"%s\" cannot be declared SETOF",
792  rawc->colname),
793  parser_errposition(pstate, rawc->location)));
794 
795  typenameTypeIdAndMod(pstate, rawc->typeName,
796  &typid, &typmod);
797  }
798 
799  tf->coltypes = lappend_oid(tf->coltypes, typid);
800  tf->coltypmods = lappend_int(tf->coltypmods, typmod);
803 
804  /* Transform the PATH and DEFAULT expressions */
805  if (rawc->colexpr)
806  {
807  colexpr = coerce_to_specific_type(pstate,
808  transformExpr(pstate, rawc->colexpr,
810  TEXTOID,
811  constructName);
812  assign_expr_collations(pstate, colexpr);
813  }
814  else
815  colexpr = NULL;
816 
817  if (rawc->coldefexpr)
818  {
819  coldefexpr = coerce_to_specific_type_typmod(pstate,
820  transformExpr(pstate, rawc->coldefexpr,
822  typid, typmod,
823  constructName);
824  assign_expr_collations(pstate, coldefexpr);
825  }
826  else
827  coldefexpr = NULL;
828 
829  tf->colexprs = lappend(tf->colexprs, colexpr);
830  tf->coldefexprs = lappend(tf->coldefexprs, coldefexpr);
831 
832  if (rawc->is_not_null)
833  tf->notnulls = bms_add_member(tf->notnulls, colno);
834 
835  /* make sure column names are unique */
836  for (j = 0; j < colno; j++)
837  if (strcmp(names[j], rawc->colname) == 0)
838  ereport(ERROR,
839  (errcode(ERRCODE_SYNTAX_ERROR),
840  errmsg("column name \"%s\" is not unique",
841  rawc->colname),
842  parser_errposition(pstate, rawc->location)));
843  names[colno] = rawc->colname;
844 
845  colno++;
846  }
847  pfree(names);
848 
849  /* Namespaces, if any, also need to be transformed */
850  if (rtf->namespaces != NIL)
851  {
852  ListCell *ns;
853  ListCell *lc2;
854  List *ns_uris = NIL;
855  List *ns_names = NIL;
856  bool default_ns_seen = false;
857 
858  foreach(ns, rtf->namespaces)
859  {
860  ResTarget *r = (ResTarget *) lfirst(ns);
861  Node *ns_uri;
862 
863  Assert(IsA(r, ResTarget));
864  ns_uri = transformExpr(pstate, r->val, EXPR_KIND_FROM_FUNCTION);
865  ns_uri = coerce_to_specific_type(pstate, ns_uri,
866  TEXTOID, constructName);
867  assign_expr_collations(pstate, ns_uri);
868  ns_uris = lappend(ns_uris, ns_uri);
869 
870  /* Verify consistency of name list: no dupes, only one DEFAULT */
871  if (r->name != NULL)
872  {
873  foreach(lc2, ns_names)
874  {
875  char *name = strVal(lfirst(lc2));
876 
877  if (name == NULL)
878  continue;
879  if (strcmp(name, r->name) == 0)
880  ereport(ERROR,
881  (errcode(ERRCODE_SYNTAX_ERROR),
882  errmsg("namespace name \"%s\" is not unique",
883  name),
884  parser_errposition(pstate, r->location)));
885  }
886  }
887  else
888  {
889  if (default_ns_seen)
890  ereport(ERROR,
891  (errcode(ERRCODE_SYNTAX_ERROR),
892  errmsg("only one default namespace is allowed"),
893  parser_errposition(pstate, r->location)));
894  default_ns_seen = true;
895  }
896 
897  /* Note the string may be NULL */
898  ns_names = lappend(ns_names, makeString(r->name));
899  }
900 
901  tf->ns_uris = ns_uris;
902  tf->ns_names = ns_names;
903  }
904 
905  tf->location = rtf->location;
906 
907  pstate->p_lateral_active = false;
908 
909  /*
910  * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
911  * there are any lateral cross-references in it.
912  */
913  is_lateral = rtf->lateral || contain_vars_of_level((Node *) tf, 0);
914 
915  rte = addRangeTableEntryForTableFunc(pstate,
916  tf, rtf->alias, is_lateral, true);
917 
918  return rte;
919 }
920 
921 /*
922  * transformRangeTableSample --- transform a TABLESAMPLE clause
923  *
924  * Caller has already transformed rts->relation, we just have to validate
925  * the remaining fields and create a TableSampleClause node.
926  */
927 static TableSampleClause *
929 {
930  TableSampleClause *tablesample;
931  Oid handlerOid;
932  Oid funcargtypes[1];
933  TsmRoutine *tsm;
934  List *fargs;
935  ListCell *larg,
936  *ltyp;
937 
938  /*
939  * To validate the sample method name, look up the handler function, which
940  * has the same name, one dummy INTERNAL argument, and a result type of
941  * tsm_handler. (Note: tablesample method names are not schema-qualified
942  * in the SQL standard; but since they are just functions to us, we allow
943  * schema qualification to resolve any potential ambiguity.)
944  */
945  funcargtypes[0] = INTERNALOID;
946 
947  handlerOid = LookupFuncName(rts->method, 1, funcargtypes, true);
948 
949  /* we want error to complain about no-such-method, not no-such-function */
950  if (!OidIsValid(handlerOid))
951  ereport(ERROR,
952  (errcode(ERRCODE_UNDEFINED_OBJECT),
953  errmsg("tablesample method %s does not exist",
954  NameListToString(rts->method)),
955  parser_errposition(pstate, rts->location)));
956 
957  /* check that handler has correct return type */
958  if (get_func_rettype(handlerOid) != TSM_HANDLEROID)
959  ereport(ERROR,
960  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
961  errmsg("function %s must return type %s",
962  NameListToString(rts->method), "tsm_handler"),
963  parser_errposition(pstate, rts->location)));
964 
965  /* OK, run the handler to get TsmRoutine, for argument type info */
966  tsm = GetTsmRoutine(handlerOid);
967 
968  tablesample = makeNode(TableSampleClause);
969  tablesample->tsmhandler = handlerOid;
970 
971  /* check user provided the expected number of arguments */
972  if (list_length(rts->args) != list_length(tsm->parameterTypes))
973  ereport(ERROR,
974  (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT),
975  errmsg_plural("tablesample method %s requires %d argument, not %d",
976  "tablesample method %s requires %d arguments, not %d",
978  NameListToString(rts->method),
980  list_length(rts->args)),
981  parser_errposition(pstate, rts->location)));
982 
983  /*
984  * Transform the arguments, typecasting them as needed. Note we must also
985  * assign collations now, because assign_query_collations() doesn't
986  * examine any substructure of RTEs.
987  */
988  fargs = NIL;
989  forboth(larg, rts->args, ltyp, tsm->parameterTypes)
990  {
991  Node *arg = (Node *) lfirst(larg);
992  Oid argtype = lfirst_oid(ltyp);
993 
994  arg = transformExpr(pstate, arg, EXPR_KIND_FROM_FUNCTION);
995  arg = coerce_to_specific_type(pstate, arg, argtype, "TABLESAMPLE");
996  assign_expr_collations(pstate, arg);
997  fargs = lappend(fargs, arg);
998  }
999  tablesample->args = fargs;
1000 
1001  /* Process REPEATABLE (seed) */
1002  if (rts->repeatable != NULL)
1003  {
1004  Node *arg;
1005 
1006  if (!tsm->repeatable_across_queries)
1007  ereport(ERROR,
1008  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1009  errmsg("tablesample method %s does not support REPEATABLE",
1010  NameListToString(rts->method)),
1011  parser_errposition(pstate, rts->location)));
1012 
1013  arg = transformExpr(pstate, rts->repeatable, EXPR_KIND_FROM_FUNCTION);
1014  arg = coerce_to_specific_type(pstate, arg, FLOAT8OID, "REPEATABLE");
1015  assign_expr_collations(pstate, arg);
1016  tablesample->repeatable = (Expr *) arg;
1017  }
1018  else
1019  tablesample->repeatable = NULL;
1020 
1021  return tablesample;
1022 }
1023 
1024 /*
1025  * transformFromClauseItem -
1026  * Transform a FROM-clause item, adding any required entries to the
1027  * range table list being built in the ParseState, and return the
1028  * transformed item ready to include in the joinlist. Also build a
1029  * ParseNamespaceItem list describing the names exposed by this item.
1030  * This routine can recurse to handle SQL92 JOIN expressions.
1031  *
1032  * The function return value is the node to add to the jointree (a
1033  * RangeTblRef or JoinExpr). Additional output parameters are:
1034  *
1035  * *top_rte: receives the RTE corresponding to the jointree item.
1036  * (We could extract this from the function return node, but it saves cycles
1037  * to pass it back separately.)
1038  *
1039  * *top_rti: receives the rangetable index of top_rte. (Ditto.)
1040  *
1041  * *namespace: receives a List of ParseNamespaceItems for the RTEs exposed
1042  * as table/column names by this item. (The lateral_only flags in these items
1043  * are indeterminate and should be explicitly set by the caller before use.)
1044  */
1045 static Node *
1047  RangeTblEntry **top_rte, int *top_rti,
1048  List **namespace)
1049 {
1050  if (IsA(n, RangeVar))
1051  {
1052  /* Plain relation reference, or perhaps a CTE reference */
1053  RangeVar *rv = (RangeVar *) n;
1054  RangeTblRef *rtr;
1055  RangeTblEntry *rte = NULL;
1056  int rtindex;
1057 
1058  /* if it is an unqualified name, it might be a CTE reference */
1059  if (!rv->schemaname)
1060  {
1061  CommonTableExpr *cte;
1062  Index levelsup;
1063 
1064  cte = scanNameSpaceForCTE(pstate, rv->relname, &levelsup);
1065  if (cte)
1066  rte = transformCTEReference(pstate, rv, cte, levelsup);
1067  }
1068 
1069  /* if not found as a CTE, must be a table reference */
1070  if (!rte)
1071  rte = transformTableEntry(pstate, rv);
1072 
1073  /* assume new rte is at end */
1074  rtindex = list_length(pstate->p_rtable);
1075  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
1076  *top_rte = rte;
1077  *top_rti = rtindex;
1078  *namespace = list_make1(makeDefaultNSItem(rte));
1079  rtr = makeNode(RangeTblRef);
1080  rtr->rtindex = rtindex;
1081  return (Node *) rtr;
1082  }
1083  else if (IsA(n, RangeSubselect))
1084  {
1085  /* sub-SELECT is like a plain relation */
1086  RangeTblRef *rtr;
1087  RangeTblEntry *rte;
1088  int rtindex;
1089 
1090  rte = transformRangeSubselect(pstate, (RangeSubselect *) n);
1091  /* assume new rte is at end */
1092  rtindex = list_length(pstate->p_rtable);
1093  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
1094  *top_rte = rte;
1095  *top_rti = rtindex;
1096  *namespace = list_make1(makeDefaultNSItem(rte));
1097  rtr = makeNode(RangeTblRef);
1098  rtr->rtindex = rtindex;
1099  return (Node *) rtr;
1100  }
1101  else if (IsA(n, RangeFunction))
1102  {
1103  /* function is like a plain relation */
1104  RangeTblRef *rtr;
1105  RangeTblEntry *rte;
1106  int rtindex;
1107 
1108  rte = transformRangeFunction(pstate, (RangeFunction *) n);
1109  /* assume new rte is at end */
1110  rtindex = list_length(pstate->p_rtable);
1111  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
1112  *top_rte = rte;
1113  *top_rti = rtindex;
1114  *namespace = list_make1(makeDefaultNSItem(rte));
1115  rtr = makeNode(RangeTblRef);
1116  rtr->rtindex = rtindex;
1117  return (Node *) rtr;
1118  }
1119  else if (IsA(n, RangeTableFunc))
1120  {
1121  /* table function is like a plain relation */
1122  RangeTblRef *rtr;
1123  RangeTblEntry *rte;
1124  int rtindex;
1125 
1126  rte = transformRangeTableFunc(pstate, (RangeTableFunc *) n);
1127  /* assume new rte is at end */
1128  rtindex = list_length(pstate->p_rtable);
1129  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
1130  *top_rte = rte;
1131  *top_rti = rtindex;
1132  *namespace = list_make1(makeDefaultNSItem(rte));
1133  rtr = makeNode(RangeTblRef);
1134  rtr->rtindex = rtindex;
1135  return (Node *) rtr;
1136  }
1137  else if (IsA(n, RangeTableSample))
1138  {
1139  /* TABLESAMPLE clause (wrapping some other valid FROM node) */
1140  RangeTableSample *rts = (RangeTableSample *) n;
1141  Node *rel;
1142  RangeTblRef *rtr;
1143  RangeTblEntry *rte;
1144 
1145  /* Recursively transform the contained relation */
1146  rel = transformFromClauseItem(pstate, rts->relation,
1147  top_rte, top_rti, namespace);
1148  /* Currently, grammar could only return a RangeVar as contained rel */
1149  rtr = castNode(RangeTblRef, rel);
1150  rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
1151  /* We only support this on plain relations and matviews */
1152  if (rte->relkind != RELKIND_RELATION &&
1153  rte->relkind != RELKIND_MATVIEW &&
1155  ereport(ERROR,
1156  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1157  errmsg("TABLESAMPLE clause can only be applied to tables and materialized views"),
1158  parser_errposition(pstate, exprLocation(rts->relation))));
1159 
1160  /* Transform TABLESAMPLE details and attach to the RTE */
1161  rte->tablesample = transformRangeTableSample(pstate, rts);
1162  return (Node *) rtr;
1163  }
1164  else if (IsA(n, JoinExpr))
1165  {
1166  /* A newfangled join expression */
1167  JoinExpr *j = (JoinExpr *) n;
1168  RangeTblEntry *l_rte;
1169  RangeTblEntry *r_rte;
1170  int l_rtindex;
1171  int r_rtindex;
1172  List *l_namespace,
1173  *r_namespace,
1174  *my_namespace,
1175  *l_colnames,
1176  *r_colnames,
1177  *res_colnames,
1178  *l_colvars,
1179  *r_colvars,
1180  *res_colvars;
1181  bool lateral_ok;
1182  int sv_namespace_length;
1183  RangeTblEntry *rte;
1184  int k;
1185 
1186  /*
1187  * Recursively process the left subtree, then the right. We must do
1188  * it in this order for correct visibility of LATERAL references.
1189  */
1190  j->larg = transformFromClauseItem(pstate, j->larg,
1191  &l_rte,
1192  &l_rtindex,
1193  &l_namespace);
1194 
1195  /*
1196  * Make the left-side RTEs available for LATERAL access within the
1197  * right side, by temporarily adding them to the pstate's namespace
1198  * list. Per SQL:2008, if the join type is not INNER or LEFT then the
1199  * left-side names must still be exposed, but it's an error to
1200  * reference them. (Stupid design, but that's what it says.) Hence,
1201  * we always push them into the namespace, but mark them as not
1202  * lateral_ok if the jointype is wrong.
1203  *
1204  * Notice that we don't require the merged namespace list to be
1205  * conflict-free. See the comments for scanNameSpaceForRefname().
1206  *
1207  * NB: this coding relies on the fact that list_concat is not
1208  * destructive to its second argument.
1209  */
1210  lateral_ok = (j->jointype == JOIN_INNER || j->jointype == JOIN_LEFT);
1211  setNamespaceLateralState(l_namespace, true, lateral_ok);
1212 
1213  sv_namespace_length = list_length(pstate->p_namespace);
1214  pstate->p_namespace = list_concat(pstate->p_namespace, l_namespace);
1215 
1216  /* And now we can process the RHS */
1217  j->rarg = transformFromClauseItem(pstate, j->rarg,
1218  &r_rte,
1219  &r_rtindex,
1220  &r_namespace);
1221 
1222  /* Remove the left-side RTEs from the namespace list again */
1223  pstate->p_namespace = list_truncate(pstate->p_namespace,
1224  sv_namespace_length);
1225 
1226  /*
1227  * Check for conflicting refnames in left and right subtrees. Must do
1228  * this because higher levels will assume I hand back a self-
1229  * consistent namespace list.
1230  */
1231  checkNameSpaceConflicts(pstate, l_namespace, r_namespace);
1232 
1233  /*
1234  * Generate combined namespace info for possible use below.
1235  */
1236  my_namespace = list_concat(l_namespace, r_namespace);
1237 
1238  /*
1239  * Extract column name and var lists from both subtrees
1240  *
1241  * Note: expandRTE returns new lists, safe for me to modify
1242  */
1243  expandRTE(l_rte, l_rtindex, 0, -1, false,
1244  &l_colnames, &l_colvars);
1245  expandRTE(r_rte, r_rtindex, 0, -1, false,
1246  &r_colnames, &r_colvars);
1247 
1248  /*
1249  * Natural join does not explicitly specify columns; must generate
1250  * columns to join. Need to run through the list of columns from each
1251  * table or join result and match up the column names. Use the first
1252  * table, and check every column in the second table for a match.
1253  * (We'll check that the matches were unique later on.) The result of
1254  * this step is a list of column names just like an explicitly-written
1255  * USING list.
1256  */
1257  if (j->isNatural)
1258  {
1259  List *rlist = NIL;
1260  ListCell *lx,
1261  *rx;
1262 
1263  Assert(j->usingClause == NIL); /* shouldn't have USING() too */
1264 
1265  foreach(lx, l_colnames)
1266  {
1267  char *l_colname = strVal(lfirst(lx));
1268  Value *m_name = NULL;
1269 
1270  foreach(rx, r_colnames)
1271  {
1272  char *r_colname = strVal(lfirst(rx));
1273 
1274  if (strcmp(l_colname, r_colname) == 0)
1275  {
1276  m_name = makeString(l_colname);
1277  break;
1278  }
1279  }
1280 
1281  /* matched a right column? then keep as join column... */
1282  if (m_name != NULL)
1283  rlist = lappend(rlist, m_name);
1284  }
1285 
1286  j->usingClause = rlist;
1287  }
1288 
1289  /*
1290  * Now transform the join qualifications, if any.
1291  */
1292  res_colnames = NIL;
1293  res_colvars = NIL;
1294 
1295  if (j->usingClause)
1296  {
1297  /*
1298  * JOIN/USING (or NATURAL JOIN, as transformed above). Transform
1299  * the list into an explicit ON-condition, and generate a list of
1300  * merged result columns.
1301  */
1302  List *ucols = j->usingClause;
1303  List *l_usingvars = NIL;
1304  List *r_usingvars = NIL;
1305  ListCell *ucol;
1306 
1307  Assert(j->quals == NULL); /* shouldn't have ON() too */
1308 
1309  foreach(ucol, ucols)
1310  {
1311  char *u_colname = strVal(lfirst(ucol));
1312  ListCell *col;
1313  int ndx;
1314  int l_index = -1;
1315  int r_index = -1;
1316  Var *l_colvar,
1317  *r_colvar;
1318 
1319  /* Check for USING(foo,foo) */
1320  foreach(col, res_colnames)
1321  {
1322  char *res_colname = strVal(lfirst(col));
1323 
1324  if (strcmp(res_colname, u_colname) == 0)
1325  ereport(ERROR,
1326  (errcode(ERRCODE_DUPLICATE_COLUMN),
1327  errmsg("column name \"%s\" appears more than once in USING clause",
1328  u_colname)));
1329  }
1330 
1331  /* Find it in left input */
1332  ndx = 0;
1333  foreach(col, l_colnames)
1334  {
1335  char *l_colname = strVal(lfirst(col));
1336 
1337  if (strcmp(l_colname, u_colname) == 0)
1338  {
1339  if (l_index >= 0)
1340  ereport(ERROR,
1341  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1342  errmsg("common column name \"%s\" appears more than once in left table",
1343  u_colname)));
1344  l_index = ndx;
1345  }
1346  ndx++;
1347  }
1348  if (l_index < 0)
1349  ereport(ERROR,
1350  (errcode(ERRCODE_UNDEFINED_COLUMN),
1351  errmsg("column \"%s\" specified in USING clause does not exist in left table",
1352  u_colname)));
1353 
1354  /* Find it in right input */
1355  ndx = 0;
1356  foreach(col, r_colnames)
1357  {
1358  char *r_colname = strVal(lfirst(col));
1359 
1360  if (strcmp(r_colname, u_colname) == 0)
1361  {
1362  if (r_index >= 0)
1363  ereport(ERROR,
1364  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1365  errmsg("common column name \"%s\" appears more than once in right table",
1366  u_colname)));
1367  r_index = ndx;
1368  }
1369  ndx++;
1370  }
1371  if (r_index < 0)
1372  ereport(ERROR,
1373  (errcode(ERRCODE_UNDEFINED_COLUMN),
1374  errmsg("column \"%s\" specified in USING clause does not exist in right table",
1375  u_colname)));
1376 
1377  l_colvar = list_nth(l_colvars, l_index);
1378  l_usingvars = lappend(l_usingvars, l_colvar);
1379  r_colvar = list_nth(r_colvars, r_index);
1380  r_usingvars = lappend(r_usingvars, r_colvar);
1381 
1382  res_colnames = lappend(res_colnames, lfirst(ucol));
1383  res_colvars = lappend(res_colvars,
1384  buildMergedJoinVar(pstate,
1385  j->jointype,
1386  l_colvar,
1387  r_colvar));
1388  }
1389 
1390  j->quals = transformJoinUsingClause(pstate,
1391  l_rte,
1392  r_rte,
1393  l_usingvars,
1394  r_usingvars);
1395  }
1396  else if (j->quals)
1397  {
1398  /* User-written ON-condition; transform it */
1399  j->quals = transformJoinOnClause(pstate, j, my_namespace);
1400  }
1401  else
1402  {
1403  /* CROSS JOIN: no quals */
1404  }
1405 
1406  /* Add remaining columns from each side to the output columns */
1407  extractRemainingColumns(res_colnames,
1408  l_colnames, l_colvars,
1409  &l_colnames, &l_colvars);
1410  extractRemainingColumns(res_colnames,
1411  r_colnames, r_colvars,
1412  &r_colnames, &r_colvars);
1413  res_colnames = list_concat(res_colnames, l_colnames);
1414  res_colvars = list_concat(res_colvars, l_colvars);
1415  res_colnames = list_concat(res_colnames, r_colnames);
1416  res_colvars = list_concat(res_colvars, r_colvars);
1417 
1418  /*
1419  * Check alias (AS clause), if any.
1420  */
1421  if (j->alias)
1422  {
1423  if (j->alias->colnames != NIL)
1424  {
1425  if (list_length(j->alias->colnames) > list_length(res_colnames))
1426  ereport(ERROR,
1427  (errcode(ERRCODE_SYNTAX_ERROR),
1428  errmsg("column alias list for \"%s\" has too many entries",
1429  j->alias->aliasname)));
1430  }
1431  }
1432 
1433  /*
1434  * Now build an RTE for the result of the join
1435  */
1436  rte = addRangeTableEntryForJoin(pstate,
1437  res_colnames,
1438  j->jointype,
1439  res_colvars,
1440  j->alias,
1441  true);
1442 
1443  /* assume new rte is at end */
1444  j->rtindex = list_length(pstate->p_rtable);
1445  Assert(rte == rt_fetch(j->rtindex, pstate->p_rtable));
1446 
1447  *top_rte = rte;
1448  *top_rti = j->rtindex;
1449 
1450  /* make a matching link to the JoinExpr for later use */
1451  for (k = list_length(pstate->p_joinexprs) + 1; k < j->rtindex; k++)
1452  pstate->p_joinexprs = lappend(pstate->p_joinexprs, NULL);
1453  pstate->p_joinexprs = lappend(pstate->p_joinexprs, j);
1454  Assert(list_length(pstate->p_joinexprs) == j->rtindex);
1455 
1456  /*
1457  * Prepare returned namespace list. If the JOIN has an alias then it
1458  * hides the contained RTEs completely; otherwise, the contained RTEs
1459  * are still visible as table names, but are not visible for
1460  * unqualified column-name access.
1461  *
1462  * Note: if there are nested alias-less JOINs, the lower-level ones
1463  * will remain in the list although they have neither p_rel_visible
1464  * nor p_cols_visible set. We could delete such list items, but it's
1465  * unclear that it's worth expending cycles to do so.
1466  */
1467  if (j->alias != NULL)
1468  my_namespace = NIL;
1469  else
1470  setNamespaceColumnVisibility(my_namespace, false);
1471 
1472  /*
1473  * The join RTE itself is always made visible for unqualified column
1474  * names. It's visible as a relation name only if it has an alias.
1475  */
1476  *namespace = lappend(my_namespace,
1477  makeNamespaceItem(rte,
1478  (j->alias != NULL),
1479  true,
1480  false,
1481  true));
1482 
1483  return (Node *) j;
1484  }
1485  else
1486  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(n));
1487  return NULL; /* can't get here, keep compiler quiet */
1488 }
1489 
1490 /*
1491  * buildMergedJoinVar -
1492  * generate a suitable replacement expression for a merged join column
1493  */
1494 static Node *
1496  Var *l_colvar, Var *r_colvar)
1497 {
1498  Oid outcoltype;
1499  int32 outcoltypmod;
1500  Node *l_node,
1501  *r_node,
1502  *res_node;
1503 
1504  /*
1505  * Choose output type if input types are dissimilar.
1506  */
1507  outcoltype = l_colvar->vartype;
1508  outcoltypmod = l_colvar->vartypmod;
1509  if (outcoltype != r_colvar->vartype)
1510  {
1511  outcoltype = select_common_type(pstate,
1512  list_make2(l_colvar, r_colvar),
1513  "JOIN/USING",
1514  NULL);
1515  outcoltypmod = -1; /* ie, unknown */
1516  }
1517  else if (outcoltypmod != r_colvar->vartypmod)
1518  {
1519  /* same type, but not same typmod */
1520  outcoltypmod = -1; /* ie, unknown */
1521  }
1522 
1523  /*
1524  * Insert coercion functions if needed. Note that a difference in typmod
1525  * can only happen if input has typmod but outcoltypmod is -1. In that
1526  * case we insert a RelabelType to clearly mark that result's typmod is
1527  * not same as input. We never need coerce_type_typmod.
1528  */
1529  if (l_colvar->vartype != outcoltype)
1530  l_node = coerce_type(pstate, (Node *) l_colvar, l_colvar->vartype,
1531  outcoltype, outcoltypmod,
1533  else if (l_colvar->vartypmod != outcoltypmod)
1534  l_node = (Node *) makeRelabelType((Expr *) l_colvar,
1535  outcoltype, outcoltypmod,
1536  InvalidOid, /* fixed below */
1538  else
1539  l_node = (Node *) l_colvar;
1540 
1541  if (r_colvar->vartype != outcoltype)
1542  r_node = coerce_type(pstate, (Node *) r_colvar, r_colvar->vartype,
1543  outcoltype, outcoltypmod,
1545  else if (r_colvar->vartypmod != outcoltypmod)
1546  r_node = (Node *) makeRelabelType((Expr *) r_colvar,
1547  outcoltype, outcoltypmod,
1548  InvalidOid, /* fixed below */
1550  else
1551  r_node = (Node *) r_colvar;
1552 
1553  /*
1554  * Choose what to emit
1555  */
1556  switch (jointype)
1557  {
1558  case JOIN_INNER:
1559 
1560  /*
1561  * We can use either var; prefer non-coerced one if available.
1562  */
1563  if (IsA(l_node, Var))
1564  res_node = l_node;
1565  else if (IsA(r_node, Var))
1566  res_node = r_node;
1567  else
1568  res_node = l_node;
1569  break;
1570  case JOIN_LEFT:
1571  /* Always use left var */
1572  res_node = l_node;
1573  break;
1574  case JOIN_RIGHT:
1575  /* Always use right var */
1576  res_node = r_node;
1577  break;
1578  case JOIN_FULL:
1579  {
1580  /*
1581  * Here we must build a COALESCE expression to ensure that the
1582  * join output is non-null if either input is.
1583  */
1585 
1586  c->coalescetype = outcoltype;
1587  /* coalescecollid will get set below */
1588  c->args = list_make2(l_node, r_node);
1589  c->location = -1;
1590  res_node = (Node *) c;
1591  break;
1592  }
1593  default:
1594  elog(ERROR, "unrecognized join type: %d", (int) jointype);
1595  res_node = NULL; /* keep compiler quiet */
1596  break;
1597  }
1598 
1599  /*
1600  * Apply assign_expr_collations to fix up the collation info in the
1601  * coercion and CoalesceExpr nodes, if we made any. This must be done now
1602  * so that the join node's alias vars show correct collation info.
1603  */
1604  assign_expr_collations(pstate, res_node);
1605 
1606  return res_node;
1607 }
1608 
1609 /*
1610  * makeNamespaceItem -
1611  * Convenience subroutine to construct a ParseNamespaceItem.
1612  */
1613 static ParseNamespaceItem *
1614 makeNamespaceItem(RangeTblEntry *rte, bool rel_visible, bool cols_visible,
1615  bool lateral_only, bool lateral_ok)
1616 {
1617  ParseNamespaceItem *nsitem;
1618 
1619  nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
1620  nsitem->p_rte = rte;
1621  nsitem->p_rel_visible = rel_visible;
1622  nsitem->p_cols_visible = cols_visible;
1623  nsitem->p_lateral_only = lateral_only;
1624  nsitem->p_lateral_ok = lateral_ok;
1625  return nsitem;
1626 }
1627 
1628 /*
1629  * setNamespaceColumnVisibility -
1630  * Convenience subroutine to update cols_visible flags in a namespace list.
1631  */
1632 static void
1633 setNamespaceColumnVisibility(List *namespace, bool cols_visible)
1634 {
1635  ListCell *lc;
1636 
1637  foreach(lc, namespace)
1638  {
1639  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1640 
1641  nsitem->p_cols_visible = cols_visible;
1642  }
1643 }
1644 
1645 /*
1646  * setNamespaceLateralState -
1647  * Convenience subroutine to update LATERAL flags in a namespace list.
1648  */
1649 static void
1650 setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
1651 {
1652  ListCell *lc;
1653 
1654  foreach(lc, namespace)
1655  {
1656  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1657 
1658  nsitem->p_lateral_only = lateral_only;
1659  nsitem->p_lateral_ok = lateral_ok;
1660  }
1661 }
1662 
1663 
1664 /*
1665  * transformWhereClause -
1666  * Transform the qualification and make sure it is of type boolean.
1667  * Used for WHERE and allied clauses.
1668  *
1669  * constructName does not affect the semantics, but is used in error messages
1670  */
1671 Node *
1673  ParseExprKind exprKind, const char *constructName)
1674 {
1675  Node *qual;
1676 
1677  if (clause == NULL)
1678  return NULL;
1679 
1680  qual = transformExpr(pstate, clause, exprKind);
1681 
1682  qual = coerce_to_boolean(pstate, qual, constructName);
1683 
1684  return qual;
1685 }
1686 
1687 
1688 /*
1689  * transformLimitClause -
1690  * Transform the expression and make sure it is of type bigint.
1691  * Used for LIMIT and allied clauses.
1692  *
1693  * Note: as of Postgres 8.2, LIMIT expressions are expected to yield int8,
1694  * rather than int4 as before.
1695  *
1696  * constructName does not affect the semantics, but is used in error messages
1697  */
1698 Node *
1700  ParseExprKind exprKind, const char *constructName)
1701 {
1702  Node *qual;
1703 
1704  if (clause == NULL)
1705  return NULL;
1706 
1707  qual = transformExpr(pstate, clause, exprKind);
1708 
1709  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1710 
1711  /* LIMIT can't refer to any variables of the current query */
1712  checkExprIsVarFree(pstate, qual, constructName);
1713 
1714  return qual;
1715 }
1716 
1717 /*
1718  * checkExprIsVarFree
1719  * Check that given expr has no Vars of the current query level
1720  * (aggregates and window functions should have been rejected already).
1721  *
1722  * This is used to check expressions that have to have a consistent value
1723  * across all rows of the query, such as a LIMIT. Arguably it should reject
1724  * volatile functions, too, but we don't do that --- whatever value the
1725  * function gives on first execution is what you get.
1726  *
1727  * constructName does not affect the semantics, but is used in error messages
1728  */
1729 static void
1730 checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
1731 {
1732  if (contain_vars_of_level(n, 0))
1733  {
1734  ereport(ERROR,
1735  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1736  /* translator: %s is name of a SQL construct, eg LIMIT */
1737  errmsg("argument of %s must not contain variables",
1738  constructName),
1739  parser_errposition(pstate,
1740  locate_var_of_level(n, 0))));
1741  }
1742 }
1743 
1744 
1745 /*
1746  * checkTargetlistEntrySQL92 -
1747  * Validate a targetlist entry found by findTargetlistEntrySQL92
1748  *
1749  * When we select a pre-existing tlist entry as a result of syntax such
1750  * as "GROUP BY 1", we have to make sure it is acceptable for use in the
1751  * indicated clause type; transformExpr() will have treated it as a regular
1752  * targetlist item.
1753  */
1754 static void
1756  ParseExprKind exprKind)
1757 {
1758  switch (exprKind)
1759  {
1760  case EXPR_KIND_GROUP_BY:
1761  /* reject aggregates and window functions */
1762  if (pstate->p_hasAggs &&
1763  contain_aggs_of_level((Node *) tle->expr, 0))
1764  ereport(ERROR,
1765  (errcode(ERRCODE_GROUPING_ERROR),
1766  /* translator: %s is name of a SQL construct, eg GROUP BY */
1767  errmsg("aggregate functions are not allowed in %s",
1768  ParseExprKindName(exprKind)),
1769  parser_errposition(pstate,
1770  locate_agg_of_level((Node *) tle->expr, 0))));
1771  if (pstate->p_hasWindowFuncs &&
1772  contain_windowfuncs((Node *) tle->expr))
1773  ereport(ERROR,
1774  (errcode(ERRCODE_WINDOWING_ERROR),
1775  /* translator: %s is name of a SQL construct, eg GROUP BY */
1776  errmsg("window functions are not allowed in %s",
1777  ParseExprKindName(exprKind)),
1778  parser_errposition(pstate,
1779  locate_windowfunc((Node *) tle->expr))));
1780  break;
1781  case EXPR_KIND_ORDER_BY:
1782  /* no extra checks needed */
1783  break;
1784  case EXPR_KIND_DISTINCT_ON:
1785  /* no extra checks needed */
1786  break;
1787  default:
1788  elog(ERROR, "unexpected exprKind in checkTargetlistEntrySQL92");
1789  break;
1790  }
1791 }
1792 
1793 /*
1794  * findTargetlistEntrySQL92 -
1795  * Returns the targetlist entry matching the given (untransformed) node.
1796  * If no matching entry exists, one is created and appended to the target
1797  * list as a "resjunk" node.
1798  *
1799  * This function supports the old SQL92 ORDER BY interpretation, where the
1800  * expression is an output column name or number. If we fail to find a
1801  * match of that sort, we fall through to the SQL99 rules. For historical
1802  * reasons, Postgres also allows this interpretation for GROUP BY, though
1803  * the standard never did. However, for GROUP BY we prefer a SQL99 match.
1804  * This function is *not* used for WINDOW definitions.
1805  *
1806  * node the ORDER BY, GROUP BY, or DISTINCT ON expression to be matched
1807  * tlist the target list (passed by reference so we can append to it)
1808  * exprKind identifies clause type being processed
1809  */
1810 static TargetEntry *
1812  ParseExprKind exprKind)
1813 {
1814  ListCell *tl;
1815 
1816  /*----------
1817  * Handle two special cases as mandated by the SQL92 spec:
1818  *
1819  * 1. Bare ColumnName (no qualifier or subscripts)
1820  * For a bare identifier, we search for a matching column name
1821  * in the existing target list. Multiple matches are an error
1822  * unless they refer to identical values; for example,
1823  * we allow SELECT a, a FROM table ORDER BY a
1824  * but not SELECT a AS b, b FROM table ORDER BY b
1825  * If no match is found, we fall through and treat the identifier
1826  * as an expression.
1827  * For GROUP BY, it is incorrect to match the grouping item against
1828  * targetlist entries: according to SQL92, an identifier in GROUP BY
1829  * is a reference to a column name exposed by FROM, not to a target
1830  * list column. However, many implementations (including pre-7.0
1831  * PostgreSQL) accept this anyway. So for GROUP BY, we look first
1832  * to see if the identifier matches any FROM column name, and only
1833  * try for a targetlist name if it doesn't. This ensures that we
1834  * adhere to the spec in the case where the name could be both.
1835  * DISTINCT ON isn't in the standard, so we can do what we like there;
1836  * we choose to make it work like ORDER BY, on the rather flimsy
1837  * grounds that ordinary DISTINCT works on targetlist entries.
1838  *
1839  * 2. IntegerConstant
1840  * This means to use the n'th item in the existing target list.
1841  * Note that it would make no sense to order/group/distinct by an
1842  * actual constant, so this does not create a conflict with SQL99.
1843  * GROUP BY column-number is not allowed by SQL92, but since
1844  * the standard has no other behavior defined for this syntax,
1845  * we may as well accept this common extension.
1846  *
1847  * Note that pre-existing resjunk targets must not be used in either case,
1848  * since the user didn't write them in his SELECT list.
1849  *
1850  * If neither special case applies, fall through to treat the item as
1851  * an expression per SQL99.
1852  *----------
1853  */
1854  if (IsA(node, ColumnRef) &&
1855  list_length(((ColumnRef *) node)->fields) == 1 &&
1856  IsA(linitial(((ColumnRef *) node)->fields), String))
1857  {
1858  char *name = strVal(linitial(((ColumnRef *) node)->fields));
1859  int location = ((ColumnRef *) node)->location;
1860 
1861  if (exprKind == EXPR_KIND_GROUP_BY)
1862  {
1863  /*
1864  * In GROUP BY, we must prefer a match against a FROM-clause
1865  * column to one against the targetlist. Look to see if there is
1866  * a matching column. If so, fall through to use SQL99 rules.
1867  * NOTE: if name could refer ambiguously to more than one column
1868  * name exposed by FROM, colNameToVar will ereport(ERROR). That's
1869  * just what we want here.
1870  *
1871  * Small tweak for 7.4.3: ignore matches in upper query levels.
1872  * This effectively changes the search order for bare names to (1)
1873  * local FROM variables, (2) local targetlist aliases, (3) outer
1874  * FROM variables, whereas before it was (1) (3) (2). SQL92 and
1875  * SQL99 do not allow GROUPing BY an outer reference, so this
1876  * breaks no cases that are legal per spec, and it seems a more
1877  * self-consistent behavior.
1878  */
1879  if (colNameToVar(pstate, name, true, location) != NULL)
1880  name = NULL;
1881  }
1882 
1883  if (name != NULL)
1884  {
1885  TargetEntry *target_result = NULL;
1886 
1887  foreach(tl, *tlist)
1888  {
1889  TargetEntry *tle = (TargetEntry *) lfirst(tl);
1890 
1891  if (!tle->resjunk &&
1892  strcmp(tle->resname, name) == 0)
1893  {
1894  if (target_result != NULL)
1895  {
1896  if (!equal(target_result->expr, tle->expr))
1897  ereport(ERROR,
1898  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1899 
1900  /*------
1901  translator: first %s is name of a SQL construct, eg ORDER BY */
1902  errmsg("%s \"%s\" is ambiguous",
1903  ParseExprKindName(exprKind),
1904  name),
1905  parser_errposition(pstate, location)));
1906  }
1907  else
1908  target_result = tle;
1909  /* Stay in loop to check for ambiguity */
1910  }
1911  }
1912  if (target_result != NULL)
1913  {
1914  /* return the first match, after suitable validation */
1915  checkTargetlistEntrySQL92(pstate, target_result, exprKind);
1916  return target_result;
1917  }
1918  }
1919  }
1920  if (IsA(node, A_Const))
1921  {
1922  Value *val = &((A_Const *) node)->val;
1923  int location = ((A_Const *) node)->location;
1924  int targetlist_pos = 0;
1925  int target_pos;
1926 
1927  if (!IsA(val, Integer))
1928  ereport(ERROR,
1929  (errcode(ERRCODE_SYNTAX_ERROR),
1930  /* translator: %s is name of a SQL construct, eg ORDER BY */
1931  errmsg("non-integer constant in %s",
1932  ParseExprKindName(exprKind)),
1933  parser_errposition(pstate, location)));
1934 
1935  target_pos = intVal(val);
1936  foreach(tl, *tlist)
1937  {
1938  TargetEntry *tle = (TargetEntry *) lfirst(tl);
1939 
1940  if (!tle->resjunk)
1941  {
1942  if (++targetlist_pos == target_pos)
1943  {
1944  /* return the unique match, after suitable validation */
1945  checkTargetlistEntrySQL92(pstate, tle, exprKind);
1946  return tle;
1947  }
1948  }
1949  }
1950  ereport(ERROR,
1951  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1952  /* translator: %s is name of a SQL construct, eg ORDER BY */
1953  errmsg("%s position %d is not in select list",
1954  ParseExprKindName(exprKind), target_pos),
1955  parser_errposition(pstate, location)));
1956  }
1957 
1958  /*
1959  * Otherwise, we have an expression, so process it per SQL99 rules.
1960  */
1961  return findTargetlistEntrySQL99(pstate, node, tlist, exprKind);
1962 }
1963 
1964 /*
1965  * findTargetlistEntrySQL99 -
1966  * Returns the targetlist entry matching the given (untransformed) node.
1967  * If no matching entry exists, one is created and appended to the target
1968  * list as a "resjunk" node.
1969  *
1970  * This function supports the SQL99 interpretation, wherein the expression
1971  * is just an ordinary expression referencing input column names.
1972  *
1973  * node the ORDER BY, GROUP BY, etc expression to be matched
1974  * tlist the target list (passed by reference so we can append to it)
1975  * exprKind identifies clause type being processed
1976  */
1977 static TargetEntry *
1979  ParseExprKind exprKind)
1980 {
1981  TargetEntry *target_result;
1982  ListCell *tl;
1983  Node *expr;
1984 
1985  /*
1986  * Convert the untransformed node to a transformed expression, and search
1987  * for a match in the tlist. NOTE: it doesn't really matter whether there
1988  * is more than one match. Also, we are willing to match an existing
1989  * resjunk target here, though the SQL92 cases above must ignore resjunk
1990  * targets.
1991  */
1992  expr = transformExpr(pstate, node, exprKind);
1993 
1994  foreach(tl, *tlist)
1995  {
1996  TargetEntry *tle = (TargetEntry *) lfirst(tl);
1997  Node *texpr;
1998 
1999  /*
2000  * Ignore any implicit cast on the existing tlist expression.
2001  *
2002  * This essentially allows the ORDER/GROUP/etc item to adopt the same
2003  * datatype previously selected for a textually-equivalent tlist item.
2004  * There can't be any implicit cast at top level in an ordinary SELECT
2005  * tlist at this stage, but the case does arise with ORDER BY in an
2006  * aggregate function.
2007  */
2008  texpr = strip_implicit_coercions((Node *) tle->expr);
2009 
2010  if (equal(expr, texpr))
2011  return tle;
2012  }
2013 
2014  /*
2015  * If no matches, construct a new target entry which is appended to the
2016  * end of the target list. This target is given resjunk = TRUE so that it
2017  * will not be projected into the final tuple.
2018  */
2019  target_result = transformTargetEntry(pstate, node, expr, exprKind,
2020  NULL, true);
2021 
2022  *tlist = lappend(*tlist, target_result);
2023 
2024  return target_result;
2025 }
2026 
2027 /*-------------------------------------------------------------------------
2028  * Flatten out parenthesized sublists in grouping lists, and some cases
2029  * of nested grouping sets.
2030  *
2031  * Inside a grouping set (ROLLUP, CUBE, or GROUPING SETS), we expect the
2032  * content to be nested no more than 2 deep: i.e. ROLLUP((a,b),(c,d)) is
2033  * ok, but ROLLUP((a,(b,c)),d) is flattened to ((a,b,c),d), which we then
2034  * (later) normalize to ((a,b,c),(d)).
2035  *
2036  * CUBE or ROLLUP can be nested inside GROUPING SETS (but not the reverse),
2037  * and we leave that alone if we find it. But if we see GROUPING SETS inside
2038  * GROUPING SETS, we can flatten and normalize as follows:
2039  * GROUPING SETS (a, (b,c), GROUPING SETS ((c,d),(e)), (f,g))
2040  * becomes
2041  * GROUPING SETS ((a), (b,c), (c,d), (e), (f,g))
2042  *
2043  * This is per the spec's syntax transformations, but these are the only such
2044  * transformations we do in parse analysis, so that queries retain the
2045  * originally specified grouping set syntax for CUBE and ROLLUP as much as
2046  * possible when deparsed. (Full expansion of the result into a list of
2047  * grouping sets is left to the planner.)
2048  *
2049  * When we're done, the resulting list should contain only these possible
2050  * elements:
2051  * - an expression
2052  * - a CUBE or ROLLUP with a list of expressions nested 2 deep
2053  * - a GROUPING SET containing any of:
2054  * - expression lists
2055  * - empty grouping sets
2056  * - CUBE or ROLLUP nodes with lists nested 2 deep
2057  * The return is a new list, but doesn't deep-copy the old nodes except for
2058  * GroupingSet nodes.
2059  *
2060  * As a side effect, flag whether the list has any GroupingSet nodes.
2061  *-------------------------------------------------------------------------
2062  */
2063 static Node *
2064 flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
2065 {
2066  /* just in case of pathological input */
2068 
2069  if (expr == (Node *) NIL)
2070  return (Node *) NIL;
2071 
2072  switch (expr->type)
2073  {
2074  case T_RowExpr:
2075  {
2076  RowExpr *r = (RowExpr *) expr;
2077 
2078  if (r->row_format == COERCE_IMPLICIT_CAST)
2079  return flatten_grouping_sets((Node *) r->args,
2080  false, NULL);
2081  }
2082  break;
2083  case T_GroupingSet:
2084  {
2085  GroupingSet *gset = (GroupingSet *) expr;
2086  ListCell *l2;
2087  List *result_set = NIL;
2088 
2089  if (hasGroupingSets)
2090  *hasGroupingSets = true;
2091 
2092  /*
2093  * at the top level, we skip over all empty grouping sets; the
2094  * caller can supply the canonical GROUP BY () if nothing is
2095  * left.
2096  */
2097 
2098  if (toplevel && gset->kind == GROUPING_SET_EMPTY)
2099  return (Node *) NIL;
2100 
2101  foreach(l2, gset->content)
2102  {
2103  Node *n1 = lfirst(l2);
2104  Node *n2 = flatten_grouping_sets(n1, false, NULL);
2105 
2106  if (IsA(n1, GroupingSet) &&
2107  ((GroupingSet *) n1)->kind == GROUPING_SET_SETS)
2108  {
2109  result_set = list_concat(result_set, (List *) n2);
2110  }
2111  else
2112  result_set = lappend(result_set, n2);
2113  }
2114 
2115  /*
2116  * At top level, keep the grouping set node; but if we're in a
2117  * nested grouping set, then we need to concat the flattened
2118  * result into the outer list if it's simply nested.
2119  */
2120 
2121  if (toplevel || (gset->kind != GROUPING_SET_SETS))
2122  {
2123  return (Node *) makeGroupingSet(gset->kind, result_set, gset->location);
2124  }
2125  else
2126  return (Node *) result_set;
2127  }
2128  case T_List:
2129  {
2130  List *result = NIL;
2131  ListCell *l;
2132 
2133  foreach(l, (List *) expr)
2134  {
2135  Node *n = flatten_grouping_sets(lfirst(l), toplevel, hasGroupingSets);
2136 
2137  if (n != (Node *) NIL)
2138  {
2139  if (IsA(n, List))
2140  result = list_concat(result, (List *) n);
2141  else
2142  result = lappend(result, n);
2143  }
2144  }
2145 
2146  return (Node *) result;
2147  }
2148  default:
2149  break;
2150  }
2151 
2152  return expr;
2153 }
2154 
2155 /*
2156  * Transform a single expression within a GROUP BY clause or grouping set.
2157  *
2158  * The expression is added to the targetlist if not already present, and to the
2159  * flatresult list (which will become the groupClause) if not already present
2160  * there. The sortClause is consulted for operator and sort order hints.
2161  *
2162  * Returns the ressortgroupref of the expression.
2163  *
2164  * flatresult reference to flat list of SortGroupClause nodes
2165  * seen_local bitmapset of sortgrouprefs already seen at the local level
2166  * pstate ParseState
2167  * gexpr node to transform
2168  * targetlist reference to TargetEntry list
2169  * sortClause ORDER BY clause (SortGroupClause nodes)
2170  * exprKind expression kind
2171  * useSQL99 SQL99 rather than SQL92 syntax
2172  * toplevel false if within any grouping set
2173  */
2174 static Index
2175 transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local,
2176  ParseState *pstate, Node *gexpr,
2177  List **targetlist, List *sortClause,
2178  ParseExprKind exprKind, bool useSQL99, bool toplevel)
2179 {
2180  TargetEntry *tle;
2181  bool found = false;
2182 
2183  if (useSQL99)
2184  tle = findTargetlistEntrySQL99(pstate, gexpr,
2185  targetlist, exprKind);
2186  else
2187  tle = findTargetlistEntrySQL92(pstate, gexpr,
2188  targetlist, exprKind);
2189 
2190  if (tle->ressortgroupref > 0)
2191  {
2192  ListCell *sl;
2193 
2194  /*
2195  * Eliminate duplicates (GROUP BY x, x) but only at local level.
2196  * (Duplicates in grouping sets can affect the number of returned
2197  * rows, so can't be dropped indiscriminately.)
2198  *
2199  * Since we don't care about anything except the sortgroupref, we can
2200  * use a bitmapset rather than scanning lists.
2201  */
2202  if (bms_is_member(tle->ressortgroupref, seen_local))
2203  return 0;
2204 
2205  /*
2206  * If we're already in the flat clause list, we don't need to consider
2207  * adding ourselves again.
2208  */
2209  found = targetIsInSortList(tle, InvalidOid, *flatresult);
2210  if (found)
2211  return tle->ressortgroupref;
2212 
2213  /*
2214  * If the GROUP BY tlist entry also appears in ORDER BY, copy operator
2215  * info from the (first) matching ORDER BY item. This means that if
2216  * you write something like "GROUP BY foo ORDER BY foo USING <<<", the
2217  * GROUP BY operation silently takes on the equality semantics implied
2218  * by the ORDER BY. There are two reasons to do this: it improves the
2219  * odds that we can implement both GROUP BY and ORDER BY with a single
2220  * sort step, and it allows the user to choose the equality semantics
2221  * used by GROUP BY, should she be working with a datatype that has
2222  * more than one equality operator.
2223  *
2224  * If we're in a grouping set, though, we force our requested ordering
2225  * to be NULLS LAST, because if we have any hope of using a sorted agg
2226  * for the job, we're going to be tacking on generated NULL values
2227  * after the corresponding groups. If the user demands nulls first,
2228  * another sort step is going to be inevitable, but that's the
2229  * planner's problem.
2230  */
2231 
2232  foreach(sl, sortClause)
2233  {
2234  SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
2235 
2236  if (sc->tleSortGroupRef == tle->ressortgroupref)
2237  {
2238  SortGroupClause *grpc = copyObject(sc);
2239 
2240  if (!toplevel)
2241  grpc->nulls_first = false;
2242  *flatresult = lappend(*flatresult, grpc);
2243  found = true;
2244  break;
2245  }
2246  }
2247  }
2248 
2249  /*
2250  * If no match in ORDER BY, just add it to the result using default
2251  * sort/group semantics.
2252  */
2253  if (!found)
2254  *flatresult = addTargetToGroupList(pstate, tle,
2255  *flatresult, *targetlist,
2256  exprLocation(gexpr));
2257 
2258  /*
2259  * _something_ must have assigned us a sortgroupref by now...
2260  */
2261 
2262  return tle->ressortgroupref;
2263 }
2264 
2265 /*
2266  * Transform a list of expressions within a GROUP BY clause or grouping set.
2267  *
2268  * The list of expressions belongs to a single clause within which duplicates
2269  * can be safely eliminated.
2270  *
2271  * Returns an integer list of ressortgroupref values.
2272  *
2273  * flatresult reference to flat list of SortGroupClause nodes
2274  * pstate ParseState
2275  * list nodes to transform
2276  * targetlist reference to TargetEntry list
2277  * sortClause ORDER BY clause (SortGroupClause nodes)
2278  * exprKind expression kind
2279  * useSQL99 SQL99 rather than SQL92 syntax
2280  * toplevel false if within any grouping set
2281  */
2282 static List *
2284  ParseState *pstate, List *list,
2285  List **targetlist, List *sortClause,
2286  ParseExprKind exprKind, bool useSQL99, bool toplevel)
2287 {
2288  Bitmapset *seen_local = NULL;
2289  List *result = NIL;
2290  ListCell *gl;
2291 
2292  foreach(gl, list)
2293  {
2294  Node *gexpr = (Node *) lfirst(gl);
2295 
2296  Index ref = transformGroupClauseExpr(flatresult,
2297  seen_local,
2298  pstate,
2299  gexpr,
2300  targetlist,
2301  sortClause,
2302  exprKind,
2303  useSQL99,
2304  toplevel);
2305 
2306  if (ref > 0)
2307  {
2308  seen_local = bms_add_member(seen_local, ref);
2309  result = lappend_int(result, ref);
2310  }
2311  }
2312 
2313  return result;
2314 }
2315 
2316 /*
2317  * Transform a grouping set and (recursively) its content.
2318  *
2319  * The grouping set might be a GROUPING SETS node with other grouping sets
2320  * inside it, but SETS within SETS have already been flattened out before
2321  * reaching here.
2322  *
2323  * Returns the transformed node, which now contains SIMPLE nodes with lists
2324  * of ressortgrouprefs rather than expressions.
2325  *
2326  * flatresult reference to flat list of SortGroupClause nodes
2327  * pstate ParseState
2328  * gset grouping set to transform
2329  * targetlist reference to TargetEntry list
2330  * sortClause ORDER BY clause (SortGroupClause nodes)
2331  * exprKind expression kind
2332  * useSQL99 SQL99 rather than SQL92 syntax
2333  * toplevel false if within any grouping set
2334  */
2335 static Node *
2337  ParseState *pstate, GroupingSet *gset,
2338  List **targetlist, List *sortClause,
2339  ParseExprKind exprKind, bool useSQL99, bool toplevel)
2340 {
2341  ListCell *gl;
2342  List *content = NIL;
2343 
2344  Assert(toplevel || gset->kind != GROUPING_SET_SETS);
2345 
2346  foreach(gl, gset->content)
2347  {
2348  Node *n = lfirst(gl);
2349 
2350  if (IsA(n, List))
2351  {
2352  List *l = transformGroupClauseList(flatresult,
2353  pstate, (List *) n,
2354  targetlist, sortClause,
2355  exprKind, useSQL99, false);
2356 
2357  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2358  l,
2359  exprLocation(n)));
2360  }
2361  else if (IsA(n, GroupingSet))
2362  {
2363  GroupingSet *gset2 = (GroupingSet *) lfirst(gl);
2364 
2365  content = lappend(content, transformGroupingSet(flatresult,
2366  pstate, gset2,
2367  targetlist, sortClause,
2368  exprKind, useSQL99, false));
2369  }
2370  else
2371  {
2372  Index ref = transformGroupClauseExpr(flatresult,
2373  NULL,
2374  pstate,
2375  n,
2376  targetlist,
2377  sortClause,
2378  exprKind,
2379  useSQL99,
2380  false);
2381 
2382  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2383  list_make1_int(ref),
2384  exprLocation(n)));
2385  }
2386  }
2387 
2388  /* Arbitrarily cap the size of CUBE, which has exponential growth */
2389  if (gset->kind == GROUPING_SET_CUBE)
2390  {
2391  if (list_length(content) > 12)
2392  ereport(ERROR,
2393  (errcode(ERRCODE_TOO_MANY_COLUMNS),
2394  errmsg("CUBE is limited to 12 elements"),
2395  parser_errposition(pstate, gset->location)));
2396  }
2397 
2398  return (Node *) makeGroupingSet(gset->kind, content, gset->location);
2399 }
2400 
2401 
2402 /*
2403  * transformGroupClause -
2404  * transform a GROUP BY clause
2405  *
2406  * GROUP BY items will be added to the targetlist (as resjunk columns)
2407  * if not already present, so the targetlist must be passed by reference.
2408  *
2409  * This is also used for window PARTITION BY clauses (which act almost the
2410  * same, but are always interpreted per SQL99 rules).
2411  *
2412  * Grouping sets make this a lot more complex than it was. Our goal here is
2413  * twofold: we make a flat list of SortGroupClause nodes referencing each
2414  * distinct expression used for grouping, with those expressions added to the
2415  * targetlist if needed. At the same time, we build the groupingSets tree,
2416  * which stores only ressortgrouprefs as integer lists inside GroupingSet nodes
2417  * (possibly nested, but limited in depth: a GROUPING_SET_SETS node can contain
2418  * nested SIMPLE, CUBE or ROLLUP nodes, but not more sets - we flatten that
2419  * out; while CUBE and ROLLUP can contain only SIMPLE nodes).
2420  *
2421  * We skip much of the hard work if there are no grouping sets.
2422  *
2423  * One subtlety is that the groupClause list can end up empty while the
2424  * groupingSets list is not; this happens if there are only empty grouping
2425  * sets, or an explicit GROUP BY (). This has the same effect as specifying
2426  * aggregates or a HAVING clause with no GROUP BY; the output is one row per
2427  * grouping set even if the input is empty.
2428  *
2429  * Returns the transformed (flat) groupClause.
2430  *
2431  * pstate ParseState
2432  * grouplist clause to transform
2433  * groupingSets reference to list to contain the grouping set tree
2434  * targetlist reference to TargetEntry list
2435  * sortClause ORDER BY clause (SortGroupClause nodes)
2436  * exprKind expression kind
2437  * useSQL99 SQL99 rather than SQL92 syntax
2438  */
2439 List *
2440 transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets,
2441  List **targetlist, List *sortClause,
2442  ParseExprKind exprKind, bool useSQL99)
2443 {
2444  List *result = NIL;
2445  List *flat_grouplist;
2446  List *gsets = NIL;
2447  ListCell *gl;
2448  bool hasGroupingSets = false;
2449  Bitmapset *seen_local = NULL;
2450 
2451  /*
2452  * Recursively flatten implicit RowExprs. (Technically this is only needed
2453  * for GROUP BY, per the syntax rules for grouping sets, but we do it
2454  * anyway.)
2455  */
2456  flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
2457  true,
2458  &hasGroupingSets);
2459 
2460  /*
2461  * If the list is now empty, but hasGroupingSets is true, it's because we
2462  * elided redundant empty grouping sets. Restore a single empty grouping
2463  * set to leave a canonical form: GROUP BY ()
2464  */
2465 
2466  if (flat_grouplist == NIL && hasGroupingSets)
2467  {
2469  NIL,
2470  exprLocation((Node *) grouplist)));
2471  }
2472 
2473  foreach(gl, flat_grouplist)
2474  {
2475  Node *gexpr = (Node *) lfirst(gl);
2476 
2477  if (IsA(gexpr, GroupingSet))
2478  {
2479  GroupingSet *gset = (GroupingSet *) gexpr;
2480 
2481  switch (gset->kind)
2482  {
2483  case GROUPING_SET_EMPTY:
2484  gsets = lappend(gsets, gset);
2485  break;
2486  case GROUPING_SET_SIMPLE:
2487  /* can't happen */
2488  Assert(false);
2489  break;
2490  case GROUPING_SET_SETS:
2491  case GROUPING_SET_CUBE:
2492  case GROUPING_SET_ROLLUP:
2493  gsets = lappend(gsets,
2494  transformGroupingSet(&result,
2495  pstate, gset,
2496  targetlist, sortClause,
2497  exprKind, useSQL99, true));
2498  break;
2499  }
2500  }
2501  else
2502  {
2503  Index ref = transformGroupClauseExpr(&result, seen_local,
2504  pstate, gexpr,
2505  targetlist, sortClause,
2506  exprKind, useSQL99, true);
2507 
2508  if (ref > 0)
2509  {
2510  seen_local = bms_add_member(seen_local, ref);
2511  if (hasGroupingSets)
2512  gsets = lappend(gsets,
2514  list_make1_int(ref),
2515  exprLocation(gexpr)));
2516  }
2517  }
2518  }
2519 
2520  /* parser should prevent this */
2521  Assert(gsets == NIL || groupingSets != NULL);
2522 
2523  if (groupingSets)
2524  *groupingSets = gsets;
2525 
2526  return result;
2527 }
2528 
2529 /*
2530  * transformSortClause -
2531  * transform an ORDER BY clause
2532  *
2533  * ORDER BY items will be added to the targetlist (as resjunk columns)
2534  * if not already present, so the targetlist must be passed by reference.
2535  *
2536  * This is also used for window and aggregate ORDER BY clauses (which act
2537  * almost the same, but are always interpreted per SQL99 rules).
2538  */
2539 List *
2541  List *orderlist,
2542  List **targetlist,
2543  ParseExprKind exprKind,
2544  bool useSQL99)
2545 {
2546  List *sortlist = NIL;
2547  ListCell *olitem;
2548 
2549  foreach(olitem, orderlist)
2550  {
2551  SortBy *sortby = (SortBy *) lfirst(olitem);
2552  TargetEntry *tle;
2553 
2554  if (useSQL99)
2555  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2556  targetlist, exprKind);
2557  else
2558  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2559  targetlist, exprKind);
2560 
2561  sortlist = addTargetToSortList(pstate, tle,
2562  sortlist, *targetlist, sortby);
2563  }
2564 
2565  return sortlist;
2566 }
2567 
2568 /*
2569  * transformWindowDefinitions -
2570  * transform window definitions (WindowDef to WindowClause)
2571  */
2572 List *
2574  List *windowdefs,
2575  List **targetlist)
2576 {
2577  List *result = NIL;
2578  Index winref = 0;
2579  ListCell *lc;
2580 
2581  foreach(lc, windowdefs)
2582  {
2583  WindowDef *windef = (WindowDef *) lfirst(lc);
2584  WindowClause *refwc = NULL;
2585  List *partitionClause;
2586  List *orderClause;
2587  WindowClause *wc;
2588 
2589  winref++;
2590 
2591  /*
2592  * Check for duplicate window names.
2593  */
2594  if (windef->name &&
2595  findWindowClause(result, windef->name) != NULL)
2596  ereport(ERROR,
2597  (errcode(ERRCODE_WINDOWING_ERROR),
2598  errmsg("window \"%s\" is already defined", windef->name),
2599  parser_errposition(pstate, windef->location)));
2600 
2601  /*
2602  * If it references a previous window, look that up.
2603  */
2604  if (windef->refname)
2605  {
2606  refwc = findWindowClause(result, windef->refname);
2607  if (refwc == NULL)
2608  ereport(ERROR,
2609  (errcode(ERRCODE_UNDEFINED_OBJECT),
2610  errmsg("window \"%s\" does not exist",
2611  windef->refname),
2612  parser_errposition(pstate, windef->location)));
2613  }
2614 
2615  /*
2616  * Transform PARTITION and ORDER specs, if any. These are treated
2617  * almost exactly like top-level GROUP BY and ORDER BY clauses,
2618  * including the special handling of nondefault operator semantics.
2619  */
2620  orderClause = transformSortClause(pstate,
2621  windef->orderClause,
2622  targetlist,
2624  true /* force SQL99 rules */ );
2625  partitionClause = transformGroupClause(pstate,
2626  windef->partitionClause,
2627  NULL,
2628  targetlist,
2629  orderClause,
2631  true /* force SQL99 rules */ );
2632 
2633  /*
2634  * And prepare the new WindowClause.
2635  */
2636  wc = makeNode(WindowClause);
2637  wc->name = windef->name;
2638  wc->refname = windef->refname;
2639 
2640  /*
2641  * Per spec, a windowdef that references a previous one copies the
2642  * previous partition clause (and mustn't specify its own). It can
2643  * specify its own ordering clause, but only if the previous one had
2644  * none. It always specifies its own frame clause, and the previous
2645  * one must not have a frame clause. Yeah, it's bizarre that each of
2646  * these cases works differently, but SQL:2008 says so; see 7.11
2647  * <window clause> syntax rule 10 and general rule 1. The frame
2648  * clause rule is especially bizarre because it makes "OVER foo"
2649  * different from "OVER (foo)", and requires the latter to throw an
2650  * error if foo has a nondefault frame clause. Well, ours not to
2651  * reason why, but we do go out of our way to throw a useful error
2652  * message for such cases.
2653  */
2654  if (refwc)
2655  {
2656  if (partitionClause)
2657  ereport(ERROR,
2658  (errcode(ERRCODE_WINDOWING_ERROR),
2659  errmsg("cannot override PARTITION BY clause of window \"%s\"",
2660  windef->refname),
2661  parser_errposition(pstate, windef->location)));
2663  }
2664  else
2665  wc->partitionClause = partitionClause;
2666  if (refwc)
2667  {
2668  if (orderClause && refwc->orderClause)
2669  ereport(ERROR,
2670  (errcode(ERRCODE_WINDOWING_ERROR),
2671  errmsg("cannot override ORDER BY clause of window \"%s\"",
2672  windef->refname),
2673  parser_errposition(pstate, windef->location)));
2674  if (orderClause)
2675  {
2676  wc->orderClause = orderClause;
2677  wc->copiedOrder = false;
2678  }
2679  else
2680  {
2681  wc->orderClause = copyObject(refwc->orderClause);
2682  wc->copiedOrder = true;
2683  }
2684  }
2685  else
2686  {
2687  wc->orderClause = orderClause;
2688  wc->copiedOrder = false;
2689  }
2690  if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
2691  {
2692  /*
2693  * Use this message if this is a WINDOW clause, or if it's an OVER
2694  * clause that includes ORDER BY or framing clauses. (We already
2695  * rejected PARTITION BY above, so no need to check that.)
2696  */
2697  if (windef->name ||
2698  orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
2699  ereport(ERROR,
2700  (errcode(ERRCODE_WINDOWING_ERROR),
2701  errmsg("cannot copy window \"%s\" because it has a frame clause",
2702  windef->refname),
2703  parser_errposition(pstate, windef->location)));
2704  /* Else this clause is just OVER (foo), so say this: */
2705  ereport(ERROR,
2706  (errcode(ERRCODE_WINDOWING_ERROR),
2707  errmsg("cannot copy window \"%s\" because it has a frame clause",
2708  windef->refname),
2709  errhint("Omit the parentheses in this OVER clause."),
2710  parser_errposition(pstate, windef->location)));
2711  }
2712  wc->frameOptions = windef->frameOptions;
2713  /* Process frame offset expressions */
2714  wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
2715  windef->startOffset);
2716  wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
2717  windef->endOffset);
2718  wc->winref = winref;
2719 
2720  result = lappend(result, wc);
2721  }
2722 
2723  return result;
2724 }
2725 
2726 /*
2727  * transformDistinctClause -
2728  * transform a DISTINCT clause
2729  *
2730  * Since we may need to add items to the query's targetlist, that list
2731  * is passed by reference.
2732  *
2733  * As with GROUP BY, we absorb the sorting semantics of ORDER BY as much as
2734  * possible into the distinctClause. This avoids a possible need to re-sort,
2735  * and allows the user to choose the equality semantics used by DISTINCT,
2736  * should she be working with a datatype that has more than one equality
2737  * operator.
2738  *
2739  * is_agg is true if we are transforming an aggregate(DISTINCT ...)
2740  * function call. This does not affect any behavior, only the phrasing
2741  * of error messages.
2742  */
2743 List *
2745  List **targetlist, List *sortClause, bool is_agg)
2746 {
2747  List *result = NIL;
2748  ListCell *slitem;
2749  ListCell *tlitem;
2750 
2751  /*
2752  * The distinctClause should consist of all ORDER BY items followed by all
2753  * other non-resjunk targetlist items. There must not be any resjunk
2754  * ORDER BY items --- that would imply that we are sorting by a value that
2755  * isn't necessarily unique within a DISTINCT group, so the results
2756  * wouldn't be well-defined. This construction ensures we follow the rule
2757  * that sortClause and distinctClause match; in fact the sortClause will
2758  * always be a prefix of distinctClause.
2759  *
2760  * Note a corner case: the same TLE could be in the ORDER BY list multiple
2761  * times with different sortops. We have to include it in the
2762  * distinctClause the same way to preserve the prefix property. The net
2763  * effect will be that the TLE value will be made unique according to both
2764  * sortops.
2765  */
2766  foreach(slitem, sortClause)
2767  {
2768  SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
2769  TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
2770 
2771  if (tle->resjunk)
2772  ereport(ERROR,
2773  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2774  is_agg ?
2775  errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
2776  errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
2777  parser_errposition(pstate,
2778  exprLocation((Node *) tle->expr))));
2779  result = lappend(result, copyObject(scl));
2780  }
2781 
2782  /*
2783  * Now add any remaining non-resjunk tlist items, using default sort/group
2784  * semantics for their data types.
2785  */
2786  foreach(tlitem, *targetlist)
2787  {
2788  TargetEntry *tle = (TargetEntry *) lfirst(tlitem);
2789 
2790  if (tle->resjunk)
2791  continue; /* ignore junk */
2792  result = addTargetToGroupList(pstate, tle,
2793  result, *targetlist,
2794  exprLocation((Node *) tle->expr));
2795  }
2796 
2797  /*
2798  * Complain if we found nothing to make DISTINCT. Returning an empty list
2799  * would cause the parsed Query to look like it didn't have DISTINCT, with
2800  * results that would probably surprise the user. Note: this case is
2801  * presently impossible for aggregates because of grammar restrictions,
2802  * but we check anyway.
2803  */
2804  if (result == NIL)
2805  ereport(ERROR,
2806  (errcode(ERRCODE_SYNTAX_ERROR),
2807  is_agg ?
2808  errmsg("an aggregate with DISTINCT must have at least one argument") :
2809  errmsg("SELECT DISTINCT must have at least one column")));
2810 
2811  return result;
2812 }
2813 
2814 /*
2815  * transformDistinctOnClause -
2816  * transform a DISTINCT ON clause
2817  *
2818  * Since we may need to add items to the query's targetlist, that list
2819  * is passed by reference.
2820  *
2821  * As with GROUP BY, we absorb the sorting semantics of ORDER BY as much as
2822  * possible into the distinctClause. This avoids a possible need to re-sort,
2823  * and allows the user to choose the equality semantics used by DISTINCT,
2824  * should she be working with a datatype that has more than one equality
2825  * operator.
2826  */
2827 List *
2829  List **targetlist, List *sortClause)
2830 {
2831  List *result = NIL;
2832  List *sortgrouprefs = NIL;
2833  bool skipped_sortitem;
2834  ListCell *lc;
2835  ListCell *lc2;
2836 
2837  /*
2838  * Add all the DISTINCT ON expressions to the tlist (if not already
2839  * present, they are added as resjunk items). Assign sortgroupref numbers
2840  * to them, and make a list of these numbers. (NB: we rely below on the
2841  * sortgrouprefs list being one-for-one with the original distinctlist.
2842  * Also notice that we could have duplicate DISTINCT ON expressions and
2843  * hence duplicate entries in sortgrouprefs.)
2844  */
2845  foreach(lc, distinctlist)
2846  {
2847  Node *dexpr = (Node *) lfirst(lc);
2848  int sortgroupref;
2849  TargetEntry *tle;
2850 
2851  tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
2853  sortgroupref = assignSortGroupRef(tle, *targetlist);
2854  sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
2855  }
2856 
2857  /*
2858  * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
2859  * semantics from ORDER BY items that match DISTINCT ON items, and also
2860  * adopt their column sort order. We insist that the distinctClause and
2861  * sortClause match, so throw error if we find the need to add any more
2862  * distinctClause items after we've skipped an ORDER BY item that wasn't
2863  * in DISTINCT ON.
2864  */
2865  skipped_sortitem = false;
2866  foreach(lc, sortClause)
2867  {
2868  SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
2869 
2870  if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
2871  {
2872  if (skipped_sortitem)
2873  ereport(ERROR,
2874  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2875  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2876  parser_errposition(pstate,
2878  sortgrouprefs,
2879  distinctlist))));
2880  else
2881  result = lappend(result, copyObject(scl));
2882  }
2883  else
2884  skipped_sortitem = true;
2885  }
2886 
2887  /*
2888  * Now add any remaining DISTINCT ON items, using default sort/group
2889  * semantics for their data types. (Note: this is pretty questionable; if
2890  * the ORDER BY list doesn't include all the DISTINCT ON items and more
2891  * besides, you certainly aren't using DISTINCT ON in the intended way,
2892  * and you probably aren't going to get consistent results. It might be
2893  * better to throw an error or warning here. But historically we've
2894  * allowed it, so keep doing so.)
2895  */
2896  forboth(lc, distinctlist, lc2, sortgrouprefs)
2897  {
2898  Node *dexpr = (Node *) lfirst(lc);
2899  int sortgroupref = lfirst_int(lc2);
2900  TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
2901 
2902  if (targetIsInSortList(tle, InvalidOid, result))
2903  continue; /* already in list (with some semantics) */
2904  if (skipped_sortitem)
2905  ereport(ERROR,
2906  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2907  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2908  parser_errposition(pstate, exprLocation(dexpr))));
2909  result = addTargetToGroupList(pstate, tle,
2910  result, *targetlist,
2911  exprLocation(dexpr));
2912  }
2913 
2914  /*
2915  * An empty result list is impossible here because of grammar
2916  * restrictions.
2917  */
2918  Assert(result != NIL);
2919 
2920  return result;
2921 }
2922 
2923 /*
2924  * get_matching_location
2925  * Get the exprLocation of the exprs member corresponding to the
2926  * (first) member of sortgrouprefs that equals sortgroupref.
2927  *
2928  * This is used so that we can point at a troublesome DISTINCT ON entry.
2929  * (Note that we need to use the original untransformed DISTINCT ON list
2930  * item, as whatever TLE it corresponds to will very possibly have a
2931  * parse location pointing to some matching entry in the SELECT list
2932  * or ORDER BY list.)
2933  */
2934 static int
2935 get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs)
2936 {
2937  ListCell *lcs;
2938  ListCell *lce;
2939 
2940  forboth(lcs, sortgrouprefs, lce, exprs)
2941  {
2942  if (lfirst_int(lcs) == sortgroupref)
2943  return exprLocation((Node *) lfirst(lce));
2944  }
2945  /* if no match, caller blew it */
2946  elog(ERROR, "get_matching_location: no matching sortgroupref");
2947  return -1; /* keep compiler quiet */
2948 }
2949 
2950 /*
2951  * resolve_unique_index_expr
2952  * Infer a unique index from a list of indexElems, for ON
2953  * CONFLICT clause
2954  *
2955  * Perform parse analysis of expressions and columns appearing within ON
2956  * CONFLICT clause. During planning, the returned list of expressions is used
2957  * to infer which unique index to use.
2958  */
2959 static List *
2961  Relation heapRel)
2962 {
2963  List *result = NIL;
2964  ListCell *l;
2965 
2966  foreach(l, infer->indexElems)
2967  {
2968  IndexElem *ielem = (IndexElem *) lfirst(l);
2970  Node *parse;
2971 
2972  /*
2973  * Raw grammar re-uses CREATE INDEX infrastructure for unique index
2974  * inference clause, and so will accept opclasses by name and so on.
2975  *
2976  * Make no attempt to match ASC or DESC ordering or NULLS FIRST/NULLS
2977  * LAST ordering, since those are not significant for inference
2978  * purposes (any unique index matching the inference specification in
2979  * other regards is accepted indifferently). Actively reject this as
2980  * wrong-headed.
2981  */
2982  if (ielem->ordering != SORTBY_DEFAULT)
2983  ereport(ERROR,
2984  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2985  errmsg("ASC/DESC is not allowed in ON CONFLICT clause"),
2986  parser_errposition(pstate,
2987  exprLocation((Node *) infer))));
2988  if (ielem->nulls_ordering != SORTBY_NULLS_DEFAULT)
2989  ereport(ERROR,
2990  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2991  errmsg("NULLS FIRST/LAST is not allowed in ON CONFLICT clause"),
2992  parser_errposition(pstate,
2993  exprLocation((Node *) infer))));
2994 
2995  if (!ielem->expr)
2996  {
2997  /* Simple index attribute */
2998  ColumnRef *n;
2999 
3000  /*
3001  * Grammar won't have built raw expression for us in event of
3002  * plain column reference. Create one directly, and perform
3003  * expression transformation. Planner expects this, and performs
3004  * its own normalization for the purposes of matching against
3005  * pg_index.
3006  */
3007  n = makeNode(ColumnRef);
3008  n->fields = list_make1(makeString(ielem->name));
3009  /* Location is approximately that of inference specification */
3010  n->location = infer->location;
3011  parse = (Node *) n;
3012  }
3013  else
3014  {
3015  /* Do parse transformation of the raw expression */
3016  parse = (Node *) ielem->expr;
3017  }
3018 
3019  /*
3020  * transformExpr() should have already rejected subqueries,
3021  * aggregates, and window functions, based on the EXPR_KIND_ for an
3022  * index expression. Expressions returning sets won't have been
3023  * rejected, but don't bother doing so here; there should be no
3024  * available expression unique index to match any such expression
3025  * against anyway.
3026  */
3027  pInfer->expr = transformExpr(pstate, parse, EXPR_KIND_INDEX_EXPRESSION);
3028 
3029  /* Perform lookup of collation and operator class as required */
3030  if (!ielem->collation)
3031  pInfer->infercollid = InvalidOid;
3032  else
3033  pInfer->infercollid = LookupCollation(pstate, ielem->collation,
3034  exprLocation(pInfer->expr));
3035 
3036  if (!ielem->opclass)
3037  pInfer->inferopclass = InvalidOid;
3038  else
3040  ielem->opclass, false);
3041 
3042  result = lappend(result, pInfer);
3043  }
3044 
3045  return result;
3046 }
3047 
3048 /*
3049  * transformOnConflictArbiter -
3050  * transform arbiter expressions in an ON CONFLICT clause.
3051  *
3052  * Transformed expressions used to infer one unique index relation to serve as
3053  * an ON CONFLICT arbiter. Partial unique indexes may be inferred using WHERE
3054  * clause from inference specification clause.
3055  */
3056 void
3058  OnConflictClause *onConflictClause,
3059  List **arbiterExpr, Node **arbiterWhere,
3060  Oid *constraint)
3061 {
3062  InferClause *infer = onConflictClause->infer;
3063 
3064  *arbiterExpr = NIL;
3065  *arbiterWhere = NULL;
3066  *constraint = InvalidOid;
3067 
3068  if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3069  ereport(ERROR,
3070  (errcode(ERRCODE_SYNTAX_ERROR),
3071  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3072  errhint("For example, ON CONFLICT (column_name)."),
3073  parser_errposition(pstate,
3074  exprLocation((Node *) onConflictClause))));
3075 
3076  /*
3077  * To simplify certain aspects of its design, speculative insertion into
3078  * system catalogs is disallowed
3079  */
3080  if (IsCatalogRelation(pstate->p_target_relation))
3081  ereport(ERROR,
3082  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3083  errmsg("ON CONFLICT is not supported with system catalog tables"),
3084  parser_errposition(pstate,
3085  exprLocation((Node *) onConflictClause))));
3086 
3087  /* Same applies to table used by logical decoding as catalog table */
3089  ereport(ERROR,
3090  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3091  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3093  parser_errposition(pstate,
3094  exprLocation((Node *) onConflictClause))));
3095 
3096  /* ON CONFLICT DO NOTHING does not require an inference clause */
3097  if (infer)
3098  {
3099  List *save_namespace;
3100 
3101  /*
3102  * While we process the arbiter expressions, accept only non-qualified
3103  * references to the target table. Hide any other relations.
3104  */
3105  save_namespace = pstate->p_namespace;
3106  pstate->p_namespace = NIL;
3107  addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
3108  false, false, true);
3109 
3110  if (infer->indexElems)
3111  *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3112  pstate->p_target_relation);
3113 
3114  /*
3115  * Handling inference WHERE clause (for partial unique index
3116  * inference)
3117  */
3118  if (infer->whereClause)
3119  *arbiterWhere = transformExpr(pstate, infer->whereClause,
3121 
3122  pstate->p_namespace = save_namespace;
3123 
3124  if (infer->conname)
3126  infer->conname, false);
3127  }
3128 
3129  /*
3130  * It's convenient to form a list of expressions based on the
3131  * representation used by CREATE INDEX, since the same restrictions are
3132  * appropriate (e.g. on subqueries). However, from here on, a dedicated
3133  * primnode representation is used for inference elements, and so
3134  * assign_query_collations() can be trusted to do the right thing with the
3135  * post parse analysis query tree inference clause representation.
3136  */
3137 }
3138 
3139 /*
3140  * addTargetToSortList
3141  * If the given targetlist entry isn't already in the SortGroupClause
3142  * list, add it to the end of the list, using the given sort ordering
3143  * info.
3144  *
3145  * Returns the updated SortGroupClause list.
3146  */
3147 List *
3149  List *sortlist, List *targetlist, SortBy *sortby)
3150 {
3151  Oid restype = exprType((Node *) tle->expr);
3152  Oid sortop;
3153  Oid eqop;
3154  bool hashable;
3155  bool reverse;
3156  int location;
3157  ParseCallbackState pcbstate;
3158 
3159  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3160  if (restype == UNKNOWNOID)
3161  {
3162  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3163  restype, TEXTOID, -1,
3166  -1);
3167  restype = TEXTOID;
3168  }
3169 
3170  /*
3171  * Rather than clutter the API of get_sort_group_operators and the other
3172  * functions we're about to use, make use of error context callback to
3173  * mark any error reports with a parse position. We point to the operator
3174  * location if present, else to the expression being sorted. (NB: use the
3175  * original untransformed expression here; the TLE entry might well point
3176  * at a duplicate expression in the regular SELECT list.)
3177  */
3178  location = sortby->location;
3179  if (location < 0)
3180  location = exprLocation(sortby->node);
3181  setup_parser_errposition_callback(&pcbstate, pstate, location);
3182 
3183  /* determine the sortop, eqop, and directionality */
3184  switch (sortby->sortby_dir)
3185  {
3186  case SORTBY_DEFAULT:
3187  case SORTBY_ASC:
3188  get_sort_group_operators(restype,
3189  true, true, false,
3190  &sortop, &eqop, NULL,
3191  &hashable);
3192  reverse = false;
3193  break;
3194  case SORTBY_DESC:
3195  get_sort_group_operators(restype,
3196  false, true, true,
3197  NULL, &eqop, &sortop,
3198  &hashable);
3199  reverse = true;
3200  break;
3201  case SORTBY_USING:
3202  Assert(sortby->useOp != NIL);
3203  sortop = compatible_oper_opid(sortby->useOp,
3204  restype,
3205  restype,
3206  false);
3207 
3208  /*
3209  * Verify it's a valid ordering operator, fetch the corresponding
3210  * equality operator, and determine whether to consider it like
3211  * ASC or DESC.
3212  */
3213  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3214  if (!OidIsValid(eqop))
3215  ereport(ERROR,
3216  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3217  errmsg("operator %s is not a valid ordering operator",
3218  strVal(llast(sortby->useOp))),
3219  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3220 
3221  /*
3222  * Also see if the equality operator is hashable.
3223  */
3224  hashable = op_hashjoinable(eqop, restype);
3225  break;
3226  default:
3227  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3228  sortop = InvalidOid; /* keep compiler quiet */
3229  eqop = InvalidOid;
3230  hashable = false;
3231  reverse = false;
3232  break;
3233  }
3234 
3236 
3237  /* avoid making duplicate sortlist entries */
3238  if (!targetIsInSortList(tle, sortop, sortlist))
3239  {
3241 
3242  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3243 
3244  sortcl->eqop = eqop;
3245  sortcl->sortop = sortop;
3246  sortcl->hashable = hashable;
3247 
3248  switch (sortby->sortby_nulls)
3249  {
3250  case SORTBY_NULLS_DEFAULT:
3251  /* NULLS FIRST is default for DESC; other way for ASC */
3252  sortcl->nulls_first = reverse;
3253  break;
3254  case SORTBY_NULLS_FIRST:
3255  sortcl->nulls_first = true;
3256  break;
3257  case SORTBY_NULLS_LAST:
3258  sortcl->nulls_first = false;
3259  break;
3260  default:
3261  elog(ERROR, "unrecognized sortby_nulls: %d",
3262  sortby->sortby_nulls);
3263  break;
3264  }
3265 
3266  sortlist = lappend(sortlist, sortcl);
3267  }
3268 
3269  return sortlist;
3270 }
3271 
3272 /*
3273  * addTargetToGroupList
3274  * If the given targetlist entry isn't already in the SortGroupClause
3275  * list, add it to the end of the list, using default sort/group
3276  * semantics.
3277  *
3278  * This is very similar to addTargetToSortList, except that we allow the
3279  * case where only a grouping (equality) operator can be found, and that
3280  * the TLE is considered "already in the list" if it appears there with any
3281  * sorting semantics.
3282  *
3283  * location is the parse location to be fingered in event of trouble. Note
3284  * that we can't rely on exprLocation(tle->expr), because that might point
3285  * to a SELECT item that matches the GROUP BY item; it'd be pretty confusing
3286  * to report such a location.
3287  *
3288  * Returns the updated SortGroupClause list.
3289  */
3290 static List *
3292  List *grouplist, List *targetlist, int location)
3293 {
3294  Oid restype = exprType((Node *) tle->expr);
3295 
3296  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3297  if (restype == UNKNOWNOID)
3298  {
3299  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3300  restype, TEXTOID, -1,
3303  -1);
3304  restype = TEXTOID;
3305  }
3306 
3307  /* avoid making duplicate grouplist entries */
3308  if (!targetIsInSortList(tle, InvalidOid, grouplist))
3309  {
3311  Oid sortop;
3312  Oid eqop;
3313  bool hashable;
3314  ParseCallbackState pcbstate;
3315 
3316  setup_parser_errposition_callback(&pcbstate, pstate, location);
3317 
3318  /* determine the eqop and optional sortop */
3319  get_sort_group_operators(restype,
3320  false, true, false,
3321  &sortop, &eqop, NULL,
3322  &hashable);
3323 
3325 
3326  grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3327  grpcl->eqop = eqop;
3328  grpcl->sortop = sortop;
3329  grpcl->nulls_first = false; /* OK with or without sortop */
3330  grpcl->hashable = hashable;
3331 
3332  grouplist = lappend(grouplist, grpcl);
3333  }
3334 
3335  return grouplist;
3336 }
3337 
3338 /*
3339  * assignSortGroupRef
3340  * Assign the targetentry an unused ressortgroupref, if it doesn't
3341  * already have one. Return the assigned or pre-existing refnumber.
3342  *
3343  * 'tlist' is the targetlist containing (or to contain) the given targetentry.
3344  */
3345 Index
3347 {
3348  Index maxRef;
3349  ListCell *l;
3350 
3351  if (tle->ressortgroupref) /* already has one? */
3352  return tle->ressortgroupref;
3353 
3354  /* easiest way to pick an unused refnumber: max used + 1 */
3355  maxRef = 0;
3356  foreach(l, tlist)
3357  {
3358  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3359 
3360  if (ref > maxRef)
3361  maxRef = ref;
3362  }
3363  tle->ressortgroupref = maxRef + 1;
3364  return tle->ressortgroupref;
3365 }
3366 
3367 /*
3368  * targetIsInSortList
3369  * Is the given target item already in the sortlist?
3370  * If sortop is not InvalidOid, also test for a match to the sortop.
3371  *
3372  * It is not an oversight that this function ignores the nulls_first flag.
3373  * We check sortop when determining if an ORDER BY item is redundant with
3374  * earlier ORDER BY items, because it's conceivable that "ORDER BY
3375  * foo USING <, foo USING <<<" is not redundant, if <<< distinguishes
3376  * values that < considers equal. We need not check nulls_first
3377  * however, because a lower-order column with the same sortop but
3378  * opposite nulls direction is redundant. Also, we can consider
3379  * ORDER BY foo ASC, foo DESC redundant, so check for a commutator match.
3380  *
3381  * Works for both ordering and grouping lists (sortop would normally be
3382  * InvalidOid when considering grouping). Note that the main reason we need
3383  * this routine (and not just a quick test for nonzeroness of ressortgroupref)
3384  * is that a TLE might be in only one of the lists.
3385  */
3386 bool
3387 targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
3388 {
3389  Index ref = tle->ressortgroupref;
3390  ListCell *l;
3391 
3392  /* no need to scan list if tle has no marker */
3393  if (ref == 0)
3394  return false;
3395 
3396  foreach(l, sortList)
3397  {
3398  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3399 
3400  if (scl->tleSortGroupRef == ref &&
3401  (sortop == InvalidOid ||
3402  sortop == scl->sortop ||
3403  sortop == get_commutator(scl->sortop)))
3404  return true;
3405  }
3406  return false;
3407 }
3408 
3409 /*
3410  * findWindowClause
3411  * Find the named WindowClause in the list, or return NULL if not there
3412  */
3413 static WindowClause *
3414 findWindowClause(List *wclist, const char *name)
3415 {
3416  ListCell *l;
3417 
3418  foreach(l, wclist)
3419  {
3420  WindowClause *wc = (WindowClause *) lfirst(l);
3421 
3422  if (wc->name && strcmp(wc->name, name) == 0)
3423  return wc;
3424  }
3425 
3426  return NULL;
3427 }
3428 
3429 /*
3430  * transformFrameOffset
3431  * Process a window frame offset expression
3432  */
3433 static Node *
3434 transformFrameOffset(ParseState *pstate, int frameOptions, Node *clause)
3435 {
3436  const char *constructName = NULL;
3437  Node *node;
3438 
3439  /* Quick exit if no offset expression */
3440  if (clause == NULL)
3441  return NULL;
3442 
3443  if (frameOptions & FRAMEOPTION_ROWS)
3444  {
3445  /* Transform the raw expression tree */
3446  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_ROWS);
3447 
3448  /*
3449  * Like LIMIT clause, simply coerce to int8
3450  */
3451  constructName = "ROWS";
3452  node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
3453  }
3454  else if (frameOptions & FRAMEOPTION_RANGE)
3455  {
3456  /* Transform the raw expression tree */
3457  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_RANGE);
3458 
3459  /*
3460  * this needs a lot of thought to decide how to support in the context
3461  * of Postgres' extensible datatype framework
3462  */
3463  constructName = "RANGE";
3464  /* error was already thrown by gram.y, this is just a backstop */
3465  elog(ERROR, "window frame with value offset is not implemented");
3466  }
3467  else
3468  {
3469  Assert(false);
3470  node = NULL;
3471  }
3472 
3473  /* Disallow variables in frame offsets */
3474  checkExprIsVarFree(pstate, node, constructName);
3475 
3476  return node;
3477 }
#define list_make2(x1, x2)
Definition: pg_list.h:134
Value * makeString(char *str)
Definition: value.c:53
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
List * partitionClause
Definition: parsenodes.h:480
char * refname
Definition: parsenodes.h:1233
#define NIL
Definition: pg_list.h:69
bool copiedOrder
Definition: parsenodes.h:1240
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:91
List * SystemFuncName(char *name)
List * args
Definition: primnodes.h:984
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
Node * docexpr
Definition: primnodes.h:84
bool repeatable_across_queries
Definition: tsmapi.h:63
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1281
Node * val
Definition: parsenodes.h:433
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:370
int errhint(const char *fmt,...)
Definition: elog.c:987
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:516
SortByDir ordering
Definition: parsenodes.h:682
Node * subquery
Definition: parsenodes.h:527
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
static RangeTblEntry * transformRangeTableFunc(ParseState *pstate, RangeTableFunc *t)
Definition: parse_clause.c:707
List * content
Definition: parsenodes.h:1211
List * transformDistinctOnClause(ParseState *pstate, List *distinctlist, List **targetlist, List *sortClause)
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
RangeTblEntry * addRangeTableEntryForJoin(ParseState *pstate, List *colnames, JoinType jointype, List *aliasvars, Alias *alias, bool inFromCl)
SortByDir sortby_dir
Definition: parsenodes.h:461
List * colnames
Definition: primnodes.h:86
List * colnames
Definition: primnodes.h:43
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2946
char * name
Definition: parsenodes.h:431
int frameOptions
Definition: parsenodes.h:482
void markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
List * coltypmods
Definition: primnodes.h:88
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:850
#define castNode(_type_, nodeptr)
Definition: nodes.h:575
Oid get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
#define TEXTOID
Definition: pg_type.h:324
List * addTargetToSortList(ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
static TargetEntry * findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
char * pstrdup(const char *in)
Definition: mcxt.c:1077
Node * agg_filter
Definition: parsenodes.h:344
List * useOp
Definition: parsenodes.h:463
#define TSM_HANDLEROID
Definition: pg_type.h:708
char * name
Definition: parsenodes.h:478
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition: lsyscache.c:264
#define BTREE_AM_OID
Definition: pg_am.h:70
List * columns
Definition: parsenodes.h:567
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
#define llast(l)
Definition: pg_list.h:126
List * indexElems
Definition: parsenodes.h:1288
#define RELKIND_MATVIEW
Definition: pg_class.h:165
List * list_truncate(List *list, int new_size)
Definition: list.c:350
char * defnamespace
Definition: parsenodes.h:707
Index tleSortGroupRef
Definition: parsenodes.h:1141
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
#define INT4OID
Definition: pg_type.h:316
static Node * transformJoinUsingClause(ParseState *pstate, RangeTblEntry *leftRTE, RangeTblEntry *rightRTE, List *leftVars, List *rightVars)
Definition: parse_clause.c:322
Relation parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
Definition: nodes.h:506
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
void transformOnConflictArbiter(ParseState *pstate, OnConflictClause *onConflictClause, List **arbiterExpr, Node **arbiterWhere, Oid *constraint)
bool p_hasAggs
Definition: parse_node.h:192
List * list_concat(List *list1, List *list2)
Definition: list.c:321
return result
Definition: formatting.c:1618
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
static int fc(const char *x)
Definition: preproc-init.c:99
AclMode requiredPerms
Definition: parsenodes.h:1004
#define heap_close(r, l)
Definition: heapam.h:97
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
Oid get_opclass_oid(Oid amID, List *opclassname, bool missing_ok)
Definition: opclasscmds.c:220
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
int location
Definition: parsenodes.h:350
unsigned int Oid
Definition: postgres_ext.h:31
char * resname
Definition: primnodes.h:1354
A_Expr * makeSimpleA_Expr(A_Expr_Kind kind, char *name, Node *lexpr, Node *rexpr, int location)
Definition: makefuncs.c:49
Definition: primnodes.h:163
Node * transformLimitClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:538
ParseExprKind
Definition: parse_node.h:32
static Node * transformFrameOffset(ParseState *pstate, int frameOptions, Node *clause)
List * agg_order
Definition: parsenodes.h:343
#define lsecond(l)
Definition: pg_list.h:114
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3352
List * colcollations
Definition: primnodes.h:89
Oid get_func_rettype(Oid funcid)
Definition: lsyscache.c:1427
signed int int32
Definition: c.h:256
Expr * makeBoolExpr(BoolExprType boolop, List *args, int location)
Definition: makefuncs.c:366
JoinType
Definition: nodes.h:669
bool p_hasWindowFuncs
Definition: parse_node.h:193
static void extractRemainingColumns(List *common_colnames, List *src_colnames, List *src_colvars, List **res_colnames, List **res_colvars)
Definition: parse_clause.c:277
char * schemaname
Definition: primnodes.h:67
int location
Definition: parsenodes.h:227
int location
Definition: parsenodes.h:434
Node * larg
Definition: primnodes.h:1435
GroupingSetKind kind
Definition: parsenodes.h:1210
#define list_make1(x1)
Definition: pg_list.h:133
bool default_with_oids
Definition: guc.c:451
void assign_expr_collations(ParseState *pstate, Node *expr)
char * relname
Definition: primnodes.h:68
Node * expr
Definition: parsenodes.h:678
uint32 AclMode
Definition: parsenodes.h:63
static int get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs)
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:437
bool defGetBoolean(DefElem *def)
Definition: define.c:111
RangeTblEntry * p_rte
Definition: parse_node.h:238
Node * startOffset
Definition: parsenodes.h:483
void pfree(void *pointer)
Definition: mcxt.c:950
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:159
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1214
bool resjunk
Definition: primnodes.h:1359
#define linitial(l)
Definition: pg_list.h:110
SortByNulls nulls_ordering
Definition: parsenodes.h:683
#define ERROR
Definition: elog.h:43
struct WindowDef * over
Definition: parsenodes.h:349
static RangeTblEntry * transformRangeSubselect(ParseState *pstate, RangeSubselect *r)
Definition: parse_clause.c:441
#define lfirst_int(lc)
Definition: pg_list.h:107
List * partitionClause
Definition: parsenodes.h:1234
List * coldeflist
Definition: parsenodes.h:553
Oid vartype
Definition: primnodes.h:170
char * FigureColname(Node *node)
List * args
Definition: primnodes.h:1045
int location
Definition: parsenodes.h:485
bool setof
Definition: parsenodes.h:202
Node * endOffset
Definition: parsenodes.h:484
static RangeTblEntry * transformTableEntry(ParseState *pstate, RangeVar *r)
Definition: parse_clause.c:412
List * coldefexprs
Definition: primnodes.h:91
static List * transformGroupClauseList(List **flatresult, ParseState *pstate, List *list, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
List * ns_names
Definition: primnodes.h:83
bool list_member_int(const List *list, int datum)
Definition: list.c:485
Node * rowexpr
Definition: primnodes.h:85
#define XMLOID
Definition: pg_type.h:359
void assign_list_collations(ParseState *pstate, List *exprs)
List * p_namespace
Definition: parse_node.h:172
static void setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
char * c
void * list_nth(const List *list, int n)
Definition: list.c:410
#define NoLock
Definition: lockdefs.h:34
NodeTag type
Definition: nodes.h:508
TypeName * typeName
Definition: parsenodes.h:582
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:399
char * conname
Definition: parsenodes.h:1290
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:74
void check_stack_depth(void)
Definition: postgres.c:3098
static Node * flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
#define RowExclusiveLock
Definition: lockdefs.h:38
List * namespaces
Definition: parsenodes.h:566
SortByNulls sortby_nulls
Definition: parsenodes.h:462
RangeTblEntry * addRangeTableEntry(ParseState *pstate, RangeVar *relation, Alias *alias, bool inh, bool inFromCl)
List * functions
Definition: parsenodes.h:551
Bitmapset * notnulls
Definition: primnodes.h:92
List * transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
#define RelationGetRelationName(relation)
Definition: rel.h:437
void checkNameSpaceConflicts(ParseState *pstate, List *namespace1, List *namespace2)
#define list_make1_int(x1)
Definition: pg_list.h:139
Node * rowexpr
Definition: parsenodes.h:565
#define ereport(elevel, rest)
Definition: elog.h:122
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition: tlist.c:348
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:143
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Definition: nodes.h:288
List * lappend_int(List *list, int datum)
Definition: list.c:146
bool inh
Definition: primnodes.h:69
bool is_rowsfrom
Definition: parsenodes.h:550
List * lappend(List *list, void *datum)
Definition: list.c:128
RangeTblEntry * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
bool isNatural
Definition: primnodes.h:1434
static Node * buildMergedJoinVar(ParseState *pstate, JoinType jointype, Var *l_colvar, Var *r_colvar)
List * usingClause
Definition: primnodes.h:1437
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:131
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
int ordinalitycol
Definition: primnodes.h:93
bool func_variadic
Definition: parsenodes.h:348
char * NameListToString(List *names)
Definition: namespace.c:2953
static TableSampleClause * transformRangeTableSample(ParseState *pstate, RangeTableSample *rts)
Definition: parse_clause.c:928
Node * startOffset
Definition: parsenodes.h:1237
static void setNamespaceColumnVisibility(List *namespace, bool cols_visible)
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
FuncCall * makeFuncCall(List *name, List *args, int location)
Definition: makefuncs.c:582
List * transformWindowDefinitions(ParseState *pstate, List *windowdefs, List **targetlist)
List * orderClause
Definition: parsenodes.h:481
Node * quals
Definition: primnodes.h:1438
static RangeTblEntry * transformCTEReference(ParseState *pstate, RangeVar *r, CommonTableExpr *cte, Index levelsup)
Definition: parse_clause.c:427
RangeTblEntry * p_target_rangetblentry
Definition: parse_node.h:179
void transformFromClause(ParseState *pstate, List *frmList)
Definition: parse_clause.c:112
unsigned int Index
Definition: c.h:365
InferClause * infer
Definition: parsenodes.h:1304
List * coltypes
Definition: primnodes.h:87
ParseExprKind p_expr_kind
Definition: parse_node.h:182
Alias * alias
Definition: parsenodes.h:568
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:293
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:496
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:316
#define InvalidOid
Definition: postgres_ext.h:36
int setTargetTable(ParseState *pstate, RangeVar *relation, bool inh, bool alsoSource, AclMode requiredPerms)
Definition: parse_clause.c:178
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
List * colexprs
Definition: primnodes.h:90
Query * parse_sub_analyze(Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
Definition: analyze.c:157
#define INTERNALOID
Definition: pg_type.h:694
bool p_lateral_active
Definition: parse_node.h:174
RangeTblEntry * addRangeTableEntryForFunction(ParseState *pstate, List *funcnames, List *funcexprs, List *coldeflists, RangeFunction *rangefunc, bool lateral, bool inFromCl)
List * opclass
Definition: parsenodes.h:681
#define INT8OID
Definition: pg_type.h:304
CmdType commandType
Definition: parsenodes.h:103
Node * colNameToVar(ParseState *pstate, char *colname, bool localonly, int location)
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
CommonTableExpr * scanNameSpaceForCTE(ParseState *pstate, const char *refname, Index *ctelevelsup)
#define makeNode(_type_)
Definition: nodes.h:554
Node * rarg
Definition: primnodes.h:1436
Alias * alias
Definition: primnodes.h:1439
#define NULL
Definition: c.h:229
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:497
JoinType jointype
Definition: primnodes.h:1433
#define Assert(condition)
Definition: c.h:675
static RangeTblEntry * transformRangeFunction(ParseState *pstate, RangeFunction *r)
Definition: parse_clause.c:508
#define lfirst(lc)
Definition: pg_list.h:106
static Node * transformFromClauseItem(ParseState *pstate, Node *n, RangeTblEntry **top_rte, int *top_rti, List **namespace)
char * aliasname
Definition: primnodes.h:42
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:187
Definition: value.h:42
List * ns_uris
Definition: primnodes.h:82
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:369
Expr * expr
Definition: primnodes.h:1352
Node * docexpr
Definition: parsenodes.h:564
Alias * alias
Definition: parsenodes.h:528
Node * endOffset
Definition: parsenodes.h:1238
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
List * args
Definition: parsenodes.h:342
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
RangeTblEntry * addRangeTableEntryForTableFunc(ParseState *pstate, TableFunc *tf, Alias *alias, bool lateral, bool inFromCl)
#define FLOAT8OID
Definition: pg_type.h:415
static void checkTargetlistEntrySQL92(ParseState *pstate, TargetEntry *tle, ParseExprKind exprKind)
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
#define FRAMEOPTION_ROWS
Definition: parsenodes.h:498
Node * whereClause
Definition: parsenodes.h:1289
char * name
Definition: parsenodes.h:677
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
#define UNKNOWNOID
Definition: pg_type.h:427
const char * name
Definition: encode.c:521
#define nodeTag(nodeptr)
Definition: nodes.h:511
bool contain_aggs_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:67
bool interpretOidsOption(List *defList, bool allowOids)
Definition: parse_clause.c:244
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
Definition: parse_func.c:1910
static const struct cname cnames[]
List * orderClause
Definition: parsenodes.h:1235
e
Definition: preproc-init.c:82
tuple list
Definition: sort-test.py:11
static ParseNamespaceItem * makeNamespaceItem(RangeTblEntry *rte, bool rel_visible, bool cols_visible, bool lateral_only, bool lateral_ok)
#define intVal(v)
Definition: value.h:52
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:494
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:604
static Node * transformJoinOnClause(ParseState *pstate, JoinExpr *j, List *namespace)
Definition: parse_clause.c:382
Relation p_target_relation
Definition: parse_node.h:178
Oid coalescetype
Definition: primnodes.h:1043
RangeTblEntry * addRangeTableEntryForCTE(ParseState *pstate, CommonTableExpr *cte, Index levelsup, RangeVar *rv, bool inFromCl)
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
Index ressortgroupref
Definition: primnodes.h:1355
List * p_joinlist
Definition: parse_node.h:170
void * arg
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
Alias * alias
Definition: primnodes.h:72
List * collation
Definition: parsenodes.h:680
bool isLockedRefname(ParseState *pstate, const char *refname)
char * defname
Definition: parsenodes.h:708
List * parameterTypes
Definition: tsmapi.h:60
#define elog
Definition: elog.h:219
List * funcname
Definition: parsenodes.h:341
Node * node
Definition: parsenodes.h:460
char * refname
Definition: parsenodes.h:479
#define copyObject(obj)
Definition: nodes.h:618
List * transformDistinctClause(ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
int location
Definition: primnodes.h:94
CoercionForm row_format
Definition: primnodes.h:996
bool agg_distinct
Definition: parsenodes.h:347
TargetEntry * transformTargetEntry(ParseState *pstate, Node *node, Node *expr, ParseExprKind exprKind, char *colname, bool resjunk)
Definition: parse_target.c:85
#define RELKIND_RELATION
Definition: pg_class.h:160
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:2774
bool agg_star
Definition: parsenodes.h:346
int rtindex
Definition: primnodes.h:1440
OnConflictAction action
Definition: parsenodes.h:1303
Definition: pg_list.h:45
Node * coerce_to_specific_type_typmod(ParseState *pstate, Node *node, Oid targetTypeId, int32 targetTypmod, const char *constructName)
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:420
static WindowClause * findWindowClause(List *wclist, const char *name)
struct TableSampleClause * tablesample
Definition: parsenodes.h:929
#define RelationGetRelid(relation)
Definition: rel.h:417
long val
Definition: informix.c:689
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197
int location
Definition: parsenodes.h:464
List * p_joinexprs
Definition: parse_node.h:169
List * fields
Definition: parsenodes.h:226
#define lfirst_oid(lc)
Definition: pg_list.h:108
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
static Index transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
static List * resolve_unique_index_expr(ParseState *pstate, InferClause *infer, Relation heapRel)
Node * strip_implicit_coercions(Node *node)
Definition: nodeFuncs.c:609
int32 vartypmod
Definition: primnodes.h:171
List * p_rtable
Definition: parse_node.h:168
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)