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