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