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