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