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