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