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