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