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