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