PostgreSQL Source Code  git master
analyze.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * analyze.c
4  * transform the raw parse tree into a query tree
5  *
6  * For optimizable statements, we are careful to obtain a suitable lock on
7  * each referenced table, and other modules of the backend preserve or
8  * re-obtain these locks before depending on the results. It is therefore
9  * okay to do significant semantic analysis of these statements. For
10  * utility commands, no locks are obtained here (and if they were, we could
11  * not be sure we'd still have them at execution). Hence the general rule
12  * for utility commands is to just dump them into a Query node untransformed.
13  * DECLARE CURSOR, EXPLAIN, and CREATE TABLE AS are exceptions because they
14  * contain optimizable statements, which we should transform.
15  *
16  *
17  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
18  * Portions Copyright (c) 1994, Regents of the University of California
19  *
20  * src/backend/parser/analyze.c
21  *
22  *-------------------------------------------------------------------------
23  */
24 
25 #include "postgres.h"
26 
27 #include "access/sysattr.h"
28 #include "catalog/pg_proc.h"
29 #include "catalog/pg_type.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_agg.h"
36 #include "parser/parse_clause.h"
37 #include "parser/parse_coerce.h"
38 #include "parser/parse_collate.h"
39 #include "parser/parse_cte.h"
40 #include "parser/parse_expr.h"
41 #include "parser/parse_func.h"
42 #include "parser/parse_merge.h"
43 #include "parser/parse_oper.h"
44 #include "parser/parse_param.h"
45 #include "parser/parse_relation.h"
46 #include "parser/parse_target.h"
47 #include "parser/parse_type.h"
48 #include "parser/parsetree.h"
49 #include "rewrite/rewriteManip.h"
50 #include "utils/backend_status.h"
51 #include "utils/builtins.h"
52 #include "utils/guc.h"
53 #include "utils/queryjumble.h"
54 #include "utils/rel.h"
55 #include "utils/syscache.h"
56 
57 
58 /* Hook for plugins to get control at end of parse analysis */
60 
61 static Query *transformOptionalSelectInto(ParseState *pstate, Node *parseTree);
62 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
63 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt);
65  OnConflictClause *onConflictClause);
66 static int count_rowexpr_columns(ParseState *pstate, Node *expr);
67 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
68 static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
71  bool isTopLevel, List **targetlist);
72 static void determineRecursiveColTypes(ParseState *pstate,
73  Node *larg, List *nrtargetlist);
74 static Query *transformReturnStmt(ParseState *pstate, ReturnStmt *stmt);
75 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
76 static List *transformReturningList(ParseState *pstate, List *returningList);
77 static Query *transformPLAssignStmt(ParseState *pstate,
78  PLAssignStmt *stmt);
80  DeclareCursorStmt *stmt);
81 static Query *transformExplainStmt(ParseState *pstate,
82  ExplainStmt *stmt);
84  CreateTableAsStmt *stmt);
85 static Query *transformCallStmt(ParseState *pstate,
86  CallStmt *stmt);
87 static void transformLockingClause(ParseState *pstate, Query *qry,
88  LockingClause *lc, bool pushedDown);
89 #ifdef RAW_EXPRESSION_COVERAGE_TEST
90 static bool test_raw_expression_coverage(Node *node, void *context);
91 #endif
92 
93 
94 /*
95  * parse_analyze_fixedparams
96  * Analyze a raw parse tree and transform it to Query form.
97  *
98  * Optionally, information about $n parameter types can be supplied.
99  * References to $n indexes not defined by paramTypes[] are disallowed.
100  *
101  * The result is a Query node. Optimizable statements require considerable
102  * transformation, while utility-type statements are simply hung off
103  * a dummy CMD_UTILITY Query node.
104  */
105 Query *
106 parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText,
107  const Oid *paramTypes, int numParams,
108  QueryEnvironment *queryEnv)
109 {
110  ParseState *pstate = make_parsestate(NULL);
111  Query *query;
112  JumbleState *jstate = NULL;
113 
114  Assert(sourceText != NULL); /* required as of 8.4 */
115 
116  pstate->p_sourcetext = sourceText;
117 
118  if (numParams > 0)
119  setup_parse_fixed_parameters(pstate, paramTypes, numParams);
120 
121  pstate->p_queryEnv = queryEnv;
122 
123  query = transformTopLevelStmt(pstate, parseTree);
124 
125  if (IsQueryIdEnabled())
126  jstate = JumbleQuery(query, sourceText);
127 
129  (*post_parse_analyze_hook) (pstate, query, jstate);
130 
131  free_parsestate(pstate);
132 
133  pgstat_report_query_id(query->queryId, false);
134 
135  return query;
136 }
137 
138 /*
139  * parse_analyze_varparams
140  *
141  * This variant is used when it's okay to deduce information about $n
142  * symbol datatypes from context. The passed-in paramTypes[] array can
143  * be modified or enlarged (via repalloc).
144  */
145 Query *
146 parse_analyze_varparams(RawStmt *parseTree, const char *sourceText,
147  Oid **paramTypes, int *numParams,
148  QueryEnvironment *queryEnv)
149 {
150  ParseState *pstate = make_parsestate(NULL);
151  Query *query;
152  JumbleState *jstate = NULL;
153 
154  Assert(sourceText != NULL); /* required as of 8.4 */
155 
156  pstate->p_sourcetext = sourceText;
157 
158  setup_parse_variable_parameters(pstate, paramTypes, numParams);
159 
160  pstate->p_queryEnv = queryEnv;
161 
162  query = transformTopLevelStmt(pstate, parseTree);
163 
164  /* make sure all is well with parameter types */
165  check_variable_parameters(pstate, query);
166 
167  if (IsQueryIdEnabled())
168  jstate = JumbleQuery(query, sourceText);
169 
171  (*post_parse_analyze_hook) (pstate, query, jstate);
172 
173  free_parsestate(pstate);
174 
175  pgstat_report_query_id(query->queryId, false);
176 
177  return query;
178 }
179 
180 /*
181  * parse_analyze_withcb
182  *
183  * This variant is used when the caller supplies their own parser callback to
184  * resolve parameters and possibly other things.
185  */
186 Query *
187 parse_analyze_withcb(RawStmt *parseTree, const char *sourceText,
188  ParserSetupHook parserSetup,
189  void *parserSetupArg,
190  QueryEnvironment *queryEnv)
191 {
192  ParseState *pstate = make_parsestate(NULL);
193  Query *query;
194  JumbleState *jstate = NULL;
195 
196  Assert(sourceText != NULL); /* required as of 8.4 */
197 
198  pstate->p_sourcetext = sourceText;
199  pstate->p_queryEnv = queryEnv;
200  (*parserSetup) (pstate, parserSetupArg);
201 
202  query = transformTopLevelStmt(pstate, parseTree);
203 
204  if (IsQueryIdEnabled())
205  jstate = JumbleQuery(query, sourceText);
206 
208  (*post_parse_analyze_hook) (pstate, query, jstate);
209 
210  free_parsestate(pstate);
211 
212  pgstat_report_query_id(query->queryId, false);
213 
214  return query;
215 }
216 
217 
218 /*
219  * parse_sub_analyze
220  * Entry point for recursively analyzing a sub-statement.
221  */
222 Query *
223 parse_sub_analyze(Node *parseTree, ParseState *parentParseState,
224  CommonTableExpr *parentCTE,
225  bool locked_from_parent,
226  bool resolve_unknowns)
227 {
228  ParseState *pstate = make_parsestate(parentParseState);
229  Query *query;
230 
231  pstate->p_parent_cte = parentCTE;
232  pstate->p_locked_from_parent = locked_from_parent;
233  pstate->p_resolve_unknowns = resolve_unknowns;
234 
235  query = transformStmt(pstate, parseTree);
236 
237  free_parsestate(pstate);
238 
239  return query;
240 }
241 
242 /*
243  * transformTopLevelStmt -
244  * transform a Parse tree into a Query tree.
245  *
246  * This function is just responsible for transferring statement location data
247  * from the RawStmt into the finished Query.
248  */
249 Query *
251 {
252  Query *result;
253 
254  /* We're at top level, so allow SELECT INTO */
255  result = transformOptionalSelectInto(pstate, parseTree->stmt);
256 
257  result->stmt_location = parseTree->stmt_location;
258  result->stmt_len = parseTree->stmt_len;
259 
260  return result;
261 }
262 
263 /*
264  * transformOptionalSelectInto -
265  * If SELECT has INTO, convert it to CREATE TABLE AS.
266  *
267  * The only thing we do here that we don't do in transformStmt() is to
268  * convert SELECT ... INTO into CREATE TABLE AS. Since utility statements
269  * aren't allowed within larger statements, this is only allowed at the top
270  * of the parse tree, and so we only try it before entering the recursive
271  * transformStmt() processing.
272  */
273 static Query *
275 {
276  if (IsA(parseTree, SelectStmt))
277  {
278  SelectStmt *stmt = (SelectStmt *) parseTree;
279 
280  /* If it's a set-operation tree, drill down to leftmost SelectStmt */
281  while (stmt && stmt->op != SETOP_NONE)
282  stmt = stmt->larg;
283  Assert(stmt && IsA(stmt, SelectStmt) && stmt->larg == NULL);
284 
285  if (stmt->intoClause)
286  {
288 
289  ctas->query = parseTree;
290  ctas->into = stmt->intoClause;
291  ctas->objtype = OBJECT_TABLE;
292  ctas->is_select_into = true;
293 
294  /*
295  * Remove the intoClause from the SelectStmt. This makes it safe
296  * for transformSelectStmt to complain if it finds intoClause set
297  * (implying that the INTO appeared in a disallowed place).
298  */
299  stmt->intoClause = NULL;
300 
301  parseTree = (Node *) ctas;
302  }
303  }
304 
305  return transformStmt(pstate, parseTree);
306 }
307 
308 /*
309  * transformStmt -
310  * recursively transform a Parse tree into a Query tree.
311  */
312 Query *
313 transformStmt(ParseState *pstate, Node *parseTree)
314 {
315  Query *result;
316 
317  /*
318  * We apply RAW_EXPRESSION_COVERAGE_TEST testing to basic DML statements;
319  * we can't just run it on everything because raw_expression_tree_walker()
320  * doesn't claim to handle utility statements.
321  */
322 #ifdef RAW_EXPRESSION_COVERAGE_TEST
323  switch (nodeTag(parseTree))
324  {
325  case T_SelectStmt:
326  case T_InsertStmt:
327  case T_UpdateStmt:
328  case T_DeleteStmt:
329  case T_MergeStmt:
330  (void) test_raw_expression_coverage(parseTree, NULL);
331  break;
332  default:
333  break;
334  }
335 #endif /* RAW_EXPRESSION_COVERAGE_TEST */
336 
337  switch (nodeTag(parseTree))
338  {
339  /*
340  * Optimizable statements
341  */
342  case T_InsertStmt:
343  result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
344  break;
345 
346  case T_DeleteStmt:
347  result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
348  break;
349 
350  case T_UpdateStmt:
351  result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
352  break;
353 
354  case T_MergeStmt:
355  result = transformMergeStmt(pstate, (MergeStmt *) parseTree);
356  break;
357 
358  case T_SelectStmt:
359  {
360  SelectStmt *n = (SelectStmt *) parseTree;
361 
362  if (n->valuesLists)
363  result = transformValuesClause(pstate, n);
364  else if (n->op == SETOP_NONE)
365  result = transformSelectStmt(pstate, n);
366  else
367  result = transformSetOperationStmt(pstate, n);
368  }
369  break;
370 
371  case T_ReturnStmt:
372  result = transformReturnStmt(pstate, (ReturnStmt *) parseTree);
373  break;
374 
375  case T_PLAssignStmt:
376  result = transformPLAssignStmt(pstate,
377  (PLAssignStmt *) parseTree);
378  break;
379 
380  /*
381  * Special cases
382  */
383  case T_DeclareCursorStmt:
384  result = transformDeclareCursorStmt(pstate,
385  (DeclareCursorStmt *) parseTree);
386  break;
387 
388  case T_ExplainStmt:
389  result = transformExplainStmt(pstate,
390  (ExplainStmt *) parseTree);
391  break;
392 
393  case T_CreateTableAsStmt:
394  result = transformCreateTableAsStmt(pstate,
395  (CreateTableAsStmt *) parseTree);
396  break;
397 
398  case T_CallStmt:
399  result = transformCallStmt(pstate,
400  (CallStmt *) parseTree);
401  break;
402 
403  default:
404 
405  /*
406  * other statements don't require any transformation; just return
407  * the original parsetree with a Query node plastered on top.
408  */
409  result = makeNode(Query);
410  result->commandType = CMD_UTILITY;
411  result->utilityStmt = (Node *) parseTree;
412  break;
413  }
414 
415  /* Mark as original query until we learn differently */
416  result->querySource = QSRC_ORIGINAL;
417  result->canSetTag = true;
418 
419  return result;
420 }
421 
422 /*
423  * analyze_requires_snapshot
424  * Returns true if a snapshot must be set before doing parse analysis
425  * on the given raw parse tree.
426  *
427  * Classification here should match transformStmt().
428  */
429 bool
431 {
432  bool result;
433 
434  switch (nodeTag(parseTree->stmt))
435  {
436  /*
437  * Optimizable statements
438  */
439  case T_InsertStmt:
440  case T_DeleteStmt:
441  case T_UpdateStmt:
442  case T_MergeStmt:
443  case T_SelectStmt:
444  case T_PLAssignStmt:
445  result = true;
446  break;
447 
448  /*
449  * Special cases
450  */
451  case T_DeclareCursorStmt:
452  case T_ExplainStmt:
453  case T_CreateTableAsStmt:
454  /* yes, because we must analyze the contained statement */
455  result = true;
456  break;
457 
458  default:
459  /* other utility statements don't have any real parse analysis */
460  result = false;
461  break;
462  }
463 
464  return result;
465 }
466 
467 /*
468  * transformDeleteStmt -
469  * transforms a Delete Statement
470  */
471 static Query *
473 {
474  Query *qry = makeNode(Query);
475  ParseNamespaceItem *nsitem;
476  Node *qual;
477 
478  qry->commandType = CMD_DELETE;
479 
480  /* process the WITH clause independently of all else */
481  if (stmt->withClause)
482  {
483  qry->hasRecursive = stmt->withClause->recursive;
484  qry->cteList = transformWithClause(pstate, stmt->withClause);
485  qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
486  }
487 
488  /* set up range table with just the result rel */
489  qry->resultRelation = setTargetTable(pstate, stmt->relation,
490  stmt->relation->inh,
491  true,
492  ACL_DELETE);
493  nsitem = pstate->p_target_nsitem;
494 
495  /* there's no DISTINCT in DELETE */
496  qry->distinctClause = NIL;
497 
498  /* subqueries in USING cannot access the result relation */
499  nsitem->p_lateral_only = true;
500  nsitem->p_lateral_ok = false;
501 
502  /*
503  * The USING clause is non-standard SQL syntax, and is equivalent in
504  * functionality to the FROM list that can be specified for UPDATE. The
505  * USING keyword is used rather than FROM because FROM is already a
506  * keyword in the DELETE syntax.
507  */
508  transformFromClause(pstate, stmt->usingClause);
509 
510  /* remaining clauses can reference the result relation normally */
511  nsitem->p_lateral_only = false;
512  nsitem->p_lateral_ok = true;
513 
514  qual = transformWhereClause(pstate, stmt->whereClause,
515  EXPR_KIND_WHERE, "WHERE");
516 
517  qry->returningList = transformReturningList(pstate, stmt->returningList);
518 
519  /* done building the range table and jointree */
520  qry->rtable = pstate->p_rtable;
521  qry->rteperminfos = pstate->p_rteperminfos;
522  qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
523 
524  qry->hasSubLinks = pstate->p_hasSubLinks;
525  qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
526  qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
527  qry->hasAggs = pstate->p_hasAggs;
528 
529  assign_query_collations(pstate, qry);
530 
531  /* this must be done after collations, for reliable comparison of exprs */
532  if (pstate->p_hasAggs)
533  parseCheckAggregates(pstate, qry);
534 
535  return qry;
536 }
537 
538 /*
539  * transformInsertStmt -
540  * transform an Insert Statement
541  */
542 static Query *
544 {
545  Query *qry = makeNode(Query);
546  SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
547  List *exprList = NIL;
548  bool isGeneralSelect;
549  List *sub_rtable;
550  List *sub_rteperminfos;
551  List *sub_namespace;
552  List *icolumns;
553  List *attrnos;
554  ParseNamespaceItem *nsitem;
555  RTEPermissionInfo *perminfo;
556  ListCell *icols;
557  ListCell *attnos;
558  ListCell *lc;
559  bool isOnConflictUpdate;
560  AclMode targetPerms;
561 
562  /* There can't be any outer WITH to worry about */
563  Assert(pstate->p_ctenamespace == NIL);
564 
565  qry->commandType = CMD_INSERT;
566  pstate->p_is_insert = true;
567 
568  /* process the WITH clause independently of all else */
569  if (stmt->withClause)
570  {
571  qry->hasRecursive = stmt->withClause->recursive;
572  qry->cteList = transformWithClause(pstate, stmt->withClause);
573  qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
574  }
575 
576  qry->override = stmt->override;
577 
578  isOnConflictUpdate = (stmt->onConflictClause &&
580 
581  /*
582  * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
583  * VALUES list, or general SELECT input. We special-case VALUES, both for
584  * efficiency and so we can handle DEFAULT specifications.
585  *
586  * The grammar allows attaching ORDER BY, LIMIT, FOR UPDATE, or WITH to a
587  * VALUES clause. If we have any of those, treat it as a general SELECT;
588  * so it will work, but you can't use DEFAULT items together with those.
589  */
590  isGeneralSelect = (selectStmt && (selectStmt->valuesLists == NIL ||
591  selectStmt->sortClause != NIL ||
592  selectStmt->limitOffset != NULL ||
593  selectStmt->limitCount != NULL ||
594  selectStmt->lockingClause != NIL ||
595  selectStmt->withClause != NULL));
596 
597  /*
598  * If a non-nil rangetable/namespace was passed in, and we are doing
599  * INSERT/SELECT, arrange to pass the rangetable/rteperminfos/namespace
600  * down to the SELECT. This can only happen if we are inside a CREATE
601  * RULE, and in that case we want the rule's OLD and NEW rtable entries to
602  * appear as part of the SELECT's rtable, not as outer references for it.
603  * (Kluge!) The SELECT's joinlist is not affected however. We must do
604  * this before adding the target table to the INSERT's rtable.
605  */
606  if (isGeneralSelect)
607  {
608  sub_rtable = pstate->p_rtable;
609  pstate->p_rtable = NIL;
610  sub_rteperminfos = pstate->p_rteperminfos;
611  pstate->p_rteperminfos = NIL;
612  sub_namespace = pstate->p_namespace;
613  pstate->p_namespace = NIL;
614  }
615  else
616  {
617  sub_rtable = NIL; /* not used, but keep compiler quiet */
618  sub_namespace = NIL;
619  }
620 
621  /*
622  * Must get write lock on INSERT target table before scanning SELECT, else
623  * we will grab the wrong kind of initial lock if the target table is also
624  * mentioned in the SELECT part. Note that the target table is not added
625  * to the joinlist or namespace.
626  */
627  targetPerms = ACL_INSERT;
628  if (isOnConflictUpdate)
629  targetPerms |= ACL_UPDATE;
630  qry->resultRelation = setTargetTable(pstate, stmt->relation,
631  false, false, targetPerms);
632 
633  /* Validate stmt->cols list, or build default list if no list given */
634  icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
635  Assert(list_length(icolumns) == list_length(attrnos));
636 
637  /*
638  * Determine which variant of INSERT we have.
639  */
640  if (selectStmt == NULL)
641  {
642  /*
643  * We have INSERT ... DEFAULT VALUES. We can handle this case by
644  * emitting an empty targetlist --- all columns will be defaulted when
645  * the planner expands the targetlist.
646  */
647  exprList = NIL;
648  }
649  else if (isGeneralSelect)
650  {
651  /*
652  * We make the sub-pstate a child of the outer pstate so that it can
653  * see any Param definitions supplied from above. Since the outer
654  * pstate's rtable and namespace are presently empty, there are no
655  * side-effects of exposing names the sub-SELECT shouldn't be able to
656  * see.
657  */
658  ParseState *sub_pstate = make_parsestate(pstate);
659  Query *selectQuery;
660 
661  /*
662  * Process the source SELECT.
663  *
664  * It is important that this be handled just like a standalone SELECT;
665  * otherwise the behavior of SELECT within INSERT might be different
666  * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
667  * bugs of just that nature...)
668  *
669  * The sole exception is that we prevent resolving unknown-type
670  * outputs as TEXT. This does not change the semantics since if the
671  * column type matters semantically, it would have been resolved to
672  * something else anyway. Doing this lets us resolve such outputs as
673  * the target column's type, which we handle below.
674  */
675  sub_pstate->p_rtable = sub_rtable;
676  sub_pstate->p_rteperminfos = sub_rteperminfos;
677  sub_pstate->p_joinexprs = NIL; /* sub_rtable has no joins */
678  sub_pstate->p_namespace = sub_namespace;
679  sub_pstate->p_resolve_unknowns = false;
680 
681  selectQuery = transformStmt(sub_pstate, stmt->selectStmt);
682 
683  free_parsestate(sub_pstate);
684 
685  /* The grammar should have produced a SELECT */
686  if (!IsA(selectQuery, Query) ||
687  selectQuery->commandType != CMD_SELECT)
688  elog(ERROR, "unexpected non-SELECT command in INSERT ... SELECT");
689 
690  /*
691  * Make the source be a subquery in the INSERT's rangetable, and add
692  * it to the INSERT's joinlist (but not the namespace).
693  */
694  nsitem = addRangeTableEntryForSubquery(pstate,
695  selectQuery,
696  makeAlias("*SELECT*", NIL),
697  false,
698  false);
699  addNSItemToQuery(pstate, nsitem, true, false, false);
700 
701  /*----------
702  * Generate an expression list for the INSERT that selects all the
703  * non-resjunk columns from the subquery. (INSERT's tlist must be
704  * separate from the subquery's tlist because we may add columns,
705  * insert datatype coercions, etc.)
706  *
707  * HACK: unknown-type constants and params in the SELECT's targetlist
708  * are copied up as-is rather than being referenced as subquery
709  * outputs. This is to ensure that when we try to coerce them to
710  * the target column's datatype, the right things happen (see
711  * special cases in coerce_type). Otherwise, this fails:
712  * INSERT INTO foo SELECT 'bar', ... FROM baz
713  *----------
714  */
715  exprList = NIL;
716  foreach(lc, selectQuery->targetList)
717  {
718  TargetEntry *tle = (TargetEntry *) lfirst(lc);
719  Expr *expr;
720 
721  if (tle->resjunk)
722  continue;
723  if (tle->expr &&
724  (IsA(tle->expr, Const) || IsA(tle->expr, Param)) &&
725  exprType((Node *) tle->expr) == UNKNOWNOID)
726  expr = tle->expr;
727  else
728  {
729  Var *var = makeVarFromTargetEntry(nsitem->p_rtindex, tle);
730 
731  var->location = exprLocation((Node *) tle->expr);
732  expr = (Expr *) var;
733  }
734  exprList = lappend(exprList, expr);
735  }
736 
737  /* Prepare row for assignment to target table */
738  exprList = transformInsertRow(pstate, exprList,
739  stmt->cols,
740  icolumns, attrnos,
741  false);
742  }
743  else if (list_length(selectStmt->valuesLists) > 1)
744  {
745  /*
746  * Process INSERT ... VALUES with multiple VALUES sublists. We
747  * generate a VALUES RTE holding the transformed expression lists, and
748  * build up a targetlist containing Vars that reference the VALUES
749  * RTE.
750  */
751  List *exprsLists = NIL;
752  List *coltypes = NIL;
753  List *coltypmods = NIL;
754  List *colcollations = NIL;
755  int sublist_length = -1;
756  bool lateral = false;
757 
758  Assert(selectStmt->intoClause == NULL);
759 
760  foreach(lc, selectStmt->valuesLists)
761  {
762  List *sublist = (List *) lfirst(lc);
763 
764  /*
765  * Do basic expression transformation (same as a ROW() expr, but
766  * allow SetToDefault at top level)
767  */
768  sublist = transformExpressionList(pstate, sublist,
769  EXPR_KIND_VALUES, true);
770 
771  /*
772  * All the sublists must be the same length, *after*
773  * transformation (which might expand '*' into multiple items).
774  * The VALUES RTE can't handle anything different.
775  */
776  if (sublist_length < 0)
777  {
778  /* Remember post-transformation length of first sublist */
779  sublist_length = list_length(sublist);
780  }
781  else if (sublist_length != list_length(sublist))
782  {
783  ereport(ERROR,
784  (errcode(ERRCODE_SYNTAX_ERROR),
785  errmsg("VALUES lists must all be the same length"),
786  parser_errposition(pstate,
787  exprLocation((Node *) sublist))));
788  }
789 
790  /*
791  * Prepare row for assignment to target table. We process any
792  * indirection on the target column specs normally but then strip
793  * off the resulting field/array assignment nodes, since we don't
794  * want the parsed statement to contain copies of those in each
795  * VALUES row. (It's annoying to have to transform the
796  * indirection specs over and over like this, but avoiding it
797  * would take some really messy refactoring of
798  * transformAssignmentIndirection.)
799  */
800  sublist = transformInsertRow(pstate, sublist,
801  stmt->cols,
802  icolumns, attrnos,
803  true);
804 
805  /*
806  * We must assign collations now because assign_query_collations
807  * doesn't process rangetable entries. We just assign all the
808  * collations independently in each row, and don't worry about
809  * whether they are consistent vertically. The outer INSERT query
810  * isn't going to care about the collations of the VALUES columns,
811  * so it's not worth the effort to identify a common collation for
812  * each one here. (But note this does have one user-visible
813  * consequence: INSERT ... VALUES won't complain about conflicting
814  * explicit COLLATEs in a column, whereas the same VALUES
815  * construct in another context would complain.)
816  */
817  assign_list_collations(pstate, sublist);
818 
819  exprsLists = lappend(exprsLists, sublist);
820  }
821 
822  /*
823  * Construct column type/typmod/collation lists for the VALUES RTE.
824  * Every expression in each column has been coerced to the type/typmod
825  * of the corresponding target column or subfield, so it's sufficient
826  * to look at the exprType/exprTypmod of the first row. We don't care
827  * about the collation labeling, so just fill in InvalidOid for that.
828  */
829  foreach(lc, (List *) linitial(exprsLists))
830  {
831  Node *val = (Node *) lfirst(lc);
832 
833  coltypes = lappend_oid(coltypes, exprType(val));
834  coltypmods = lappend_int(coltypmods, exprTypmod(val));
835  colcollations = lappend_oid(colcollations, InvalidOid);
836  }
837 
838  /*
839  * Ordinarily there can't be any current-level Vars in the expression
840  * lists, because the namespace was empty ... but if we're inside
841  * CREATE RULE, then NEW/OLD references might appear. In that case we
842  * have to mark the VALUES RTE as LATERAL.
843  */
844  if (list_length(pstate->p_rtable) != 1 &&
845  contain_vars_of_level((Node *) exprsLists, 0))
846  lateral = true;
847 
848  /*
849  * Generate the VALUES RTE
850  */
851  nsitem = addRangeTableEntryForValues(pstate, exprsLists,
852  coltypes, coltypmods, colcollations,
853  NULL, lateral, true);
854  addNSItemToQuery(pstate, nsitem, true, false, false);
855 
856  /*
857  * Generate list of Vars referencing the RTE
858  */
859  exprList = expandNSItemVars(nsitem, 0, -1, NULL);
860 
861  /*
862  * Re-apply any indirection on the target column specs to the Vars
863  */
864  exprList = transformInsertRow(pstate, exprList,
865  stmt->cols,
866  icolumns, attrnos,
867  false);
868  }
869  else
870  {
871  /*
872  * Process INSERT ... VALUES with a single VALUES sublist. We treat
873  * this case separately for efficiency. The sublist is just computed
874  * directly as the Query's targetlist, with no VALUES RTE. So it
875  * works just like a SELECT without any FROM.
876  */
877  List *valuesLists = selectStmt->valuesLists;
878 
879  Assert(list_length(valuesLists) == 1);
880  Assert(selectStmt->intoClause == NULL);
881 
882  /*
883  * Do basic expression transformation (same as a ROW() expr, but allow
884  * SetToDefault at top level)
885  */
886  exprList = transformExpressionList(pstate,
887  (List *) linitial(valuesLists),
889  true);
890 
891  /* Prepare row for assignment to target table */
892  exprList = transformInsertRow(pstate, exprList,
893  stmt->cols,
894  icolumns, attrnos,
895  false);
896  }
897 
898  /*
899  * Generate query's target list using the computed list of expressions.
900  * Also, mark all the target columns as needing insert permissions.
901  */
902  perminfo = pstate->p_target_nsitem->p_perminfo;
903  qry->targetList = NIL;
904  Assert(list_length(exprList) <= list_length(icolumns));
905  forthree(lc, exprList, icols, icolumns, attnos, attrnos)
906  {
907  Expr *expr = (Expr *) lfirst(lc);
908  ResTarget *col = lfirst_node(ResTarget, icols);
909  AttrNumber attr_num = (AttrNumber) lfirst_int(attnos);
910  TargetEntry *tle;
911 
912  tle = makeTargetEntry(expr,
913  attr_num,
914  col->name,
915  false);
916  qry->targetList = lappend(qry->targetList, tle);
917 
918  perminfo->insertedCols = bms_add_member(perminfo->insertedCols,
920  }
921 
922  /*
923  * If we have any clauses yet to process, set the query namespace to
924  * contain only the target relation, removing any entries added in a
925  * sub-SELECT or VALUES list.
926  */
927  if (stmt->onConflictClause || stmt->returningList)
928  {
929  pstate->p_namespace = NIL;
930  addNSItemToQuery(pstate, pstate->p_target_nsitem,
931  false, true, true);
932  }
933 
934  /* Process ON CONFLICT, if any. */
935  if (stmt->onConflictClause)
936  qry->onConflict = transformOnConflictClause(pstate,
937  stmt->onConflictClause);
938 
939  /* Process RETURNING, if any. */
940  if (stmt->returningList)
941  qry->returningList = transformReturningList(pstate,
942  stmt->returningList);
943 
944  /* done building the range table and jointree */
945  qry->rtable = pstate->p_rtable;
946  qry->rteperminfos = pstate->p_rteperminfos;
947  qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
948 
949  qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
950  qry->hasSubLinks = pstate->p_hasSubLinks;
951 
952  assign_query_collations(pstate, qry);
953 
954  return qry;
955 }
956 
957 /*
958  * Prepare an INSERT row for assignment to the target table.
959  *
960  * exprlist: transformed expressions for source values; these might come from
961  * a VALUES row, or be Vars referencing a sub-SELECT or VALUES RTE output.
962  * stmtcols: original target-columns spec for INSERT (we just test for NIL)
963  * icolumns: effective target-columns spec (list of ResTarget)
964  * attrnos: integer column numbers (must be same length as icolumns)
965  * strip_indirection: if true, remove any field/array assignment nodes
966  */
967 List *
968 transformInsertRow(ParseState *pstate, List *exprlist,
969  List *stmtcols, List *icolumns, List *attrnos,
970  bool strip_indirection)
971 {
972  List *result;
973  ListCell *lc;
974  ListCell *icols;
975  ListCell *attnos;
976 
977  /*
978  * Check length of expr list. It must not have more expressions than
979  * there are target columns. We allow fewer, but only if no explicit
980  * columns list was given (the remaining columns are implicitly
981  * defaulted). Note we must check this *after* transformation because
982  * that could expand '*' into multiple items.
983  */
984  if (list_length(exprlist) > list_length(icolumns))
985  ereport(ERROR,
986  (errcode(ERRCODE_SYNTAX_ERROR),
987  errmsg("INSERT has more expressions than target columns"),
988  parser_errposition(pstate,
989  exprLocation(list_nth(exprlist,
990  list_length(icolumns))))));
991  if (stmtcols != NIL &&
992  list_length(exprlist) < list_length(icolumns))
993  {
994  /*
995  * We can get here for cases like INSERT ... SELECT (a,b,c) FROM ...
996  * where the user accidentally created a RowExpr instead of separate
997  * columns. Add a suitable hint if that seems to be the problem,
998  * because the main error message is quite misleading for this case.
999  * (If there's no stmtcols, you'll get something about data type
1000  * mismatch, which is less misleading so we don't worry about giving a
1001  * hint in that case.)
1002  */
1003  ereport(ERROR,
1004  (errcode(ERRCODE_SYNTAX_ERROR),
1005  errmsg("INSERT has more target columns than expressions"),
1006  ((list_length(exprlist) == 1 &&
1007  count_rowexpr_columns(pstate, linitial(exprlist)) ==
1008  list_length(icolumns)) ?
1009  errhint("The insertion source is a row expression containing the same number of columns expected by the INSERT. Did you accidentally use extra parentheses?") : 0),
1010  parser_errposition(pstate,
1011  exprLocation(list_nth(icolumns,
1012  list_length(exprlist))))));
1013  }
1014 
1015  /*
1016  * Prepare columns for assignment to target table.
1017  */
1018  result = NIL;
1019  forthree(lc, exprlist, icols, icolumns, attnos, attrnos)
1020  {
1021  Expr *expr = (Expr *) lfirst(lc);
1022  ResTarget *col = lfirst_node(ResTarget, icols);
1023  int attno = lfirst_int(attnos);
1024 
1025  expr = transformAssignedExpr(pstate, expr,
1027  col->name,
1028  attno,
1029  col->indirection,
1030  col->location);
1031 
1032  if (strip_indirection)
1033  {
1034  while (expr)
1035  {
1036  if (IsA(expr, FieldStore))
1037  {
1038  FieldStore *fstore = (FieldStore *) expr;
1039 
1040  expr = (Expr *) linitial(fstore->newvals);
1041  }
1042  else if (IsA(expr, SubscriptingRef))
1043  {
1044  SubscriptingRef *sbsref = (SubscriptingRef *) expr;
1045 
1046  if (sbsref->refassgnexpr == NULL)
1047  break;
1048 
1049  expr = sbsref->refassgnexpr;
1050  }
1051  else
1052  break;
1053  }
1054  }
1055 
1056  result = lappend(result, expr);
1057  }
1058 
1059  return result;
1060 }
1061 
1062 /*
1063  * transformOnConflictClause -
1064  * transforms an OnConflictClause in an INSERT
1065  */
1066 static OnConflictExpr *
1068  OnConflictClause *onConflictClause)
1069 {
1070  ParseNamespaceItem *exclNSItem = NULL;
1071  List *arbiterElems;
1072  Node *arbiterWhere;
1073  Oid arbiterConstraint;
1074  List *onConflictSet = NIL;
1075  Node *onConflictWhere = NULL;
1076  int exclRelIndex = 0;
1077  List *exclRelTlist = NIL;
1078  OnConflictExpr *result;
1079 
1080  /*
1081  * If this is ON CONFLICT ... UPDATE, first create the range table entry
1082  * for the EXCLUDED pseudo relation, so that that will be present while
1083  * processing arbiter expressions. (You can't actually reference it from
1084  * there, but this provides a useful error message if you try.)
1085  */
1086  if (onConflictClause->action == ONCONFLICT_UPDATE)
1087  {
1088  Relation targetrel = pstate->p_target_relation;
1089  RangeTblEntry *exclRte;
1090 
1091  exclNSItem = addRangeTableEntryForRelation(pstate,
1092  targetrel,
1094  makeAlias("excluded", NIL),
1095  false, false);
1096  exclRte = exclNSItem->p_rte;
1097  exclRelIndex = exclNSItem->p_rtindex;
1098 
1099  /*
1100  * relkind is set to composite to signal that we're not dealing with
1101  * an actual relation, and no permission checks are required on it.
1102  * (We'll check the actual target relation, instead.)
1103  */
1104  exclRte->relkind = RELKIND_COMPOSITE_TYPE;
1105 
1106  /* Create EXCLUDED rel's targetlist for use by EXPLAIN */
1107  exclRelTlist = BuildOnConflictExcludedTargetlist(targetrel,
1108  exclRelIndex);
1109  }
1110 
1111  /* Process the arbiter clause, ON CONFLICT ON (...) */
1112  transformOnConflictArbiter(pstate, onConflictClause, &arbiterElems,
1113  &arbiterWhere, &arbiterConstraint);
1114 
1115  /* Process DO UPDATE */
1116  if (onConflictClause->action == ONCONFLICT_UPDATE)
1117  {
1118  /*
1119  * Expressions in the UPDATE targetlist need to be handled like UPDATE
1120  * not INSERT. We don't need to save/restore this because all INSERT
1121  * expressions have been parsed already.
1122  */
1123  pstate->p_is_insert = false;
1124 
1125  /*
1126  * Add the EXCLUDED pseudo relation to the query namespace, making it
1127  * available in the UPDATE subexpressions.
1128  */
1129  addNSItemToQuery(pstate, exclNSItem, false, true, true);
1130 
1131  /*
1132  * Now transform the UPDATE subexpressions.
1133  */
1134  onConflictSet =
1135  transformUpdateTargetList(pstate, onConflictClause->targetList);
1136 
1137  onConflictWhere = transformWhereClause(pstate,
1138  onConflictClause->whereClause,
1139  EXPR_KIND_WHERE, "WHERE");
1140 
1141  /*
1142  * Remove the EXCLUDED pseudo relation from the query namespace, since
1143  * it's not supposed to be available in RETURNING. (Maybe someday we
1144  * could allow that, and drop this step.)
1145  */
1146  Assert((ParseNamespaceItem *) llast(pstate->p_namespace) == exclNSItem);
1147  pstate->p_namespace = list_delete_last(pstate->p_namespace);
1148  }
1149 
1150  /* Finally, build ON CONFLICT DO [NOTHING | UPDATE] expression */
1151  result = makeNode(OnConflictExpr);
1152 
1153  result->action = onConflictClause->action;
1154  result->arbiterElems = arbiterElems;
1155  result->arbiterWhere = arbiterWhere;
1156  result->constraint = arbiterConstraint;
1157  result->onConflictSet = onConflictSet;
1158  result->onConflictWhere = onConflictWhere;
1159  result->exclRelIndex = exclRelIndex;
1160  result->exclRelTlist = exclRelTlist;
1161 
1162  return result;
1163 }
1164 
1165 
1166 /*
1167  * BuildOnConflictExcludedTargetlist
1168  * Create target list for the EXCLUDED pseudo-relation of ON CONFLICT,
1169  * representing the columns of targetrel with varno exclRelIndex.
1170  *
1171  * Note: Exported for use in the rewriter.
1172  */
1173 List *
1175  Index exclRelIndex)
1176 {
1177  List *result = NIL;
1178  int attno;
1179  Var *var;
1180  TargetEntry *te;
1181 
1182  /*
1183  * Note that resnos of the tlist must correspond to attnos of the
1184  * underlying relation, hence we need entries for dropped columns too.
1185  */
1186  for (attno = 0; attno < RelationGetNumberOfAttributes(targetrel); attno++)
1187  {
1188  Form_pg_attribute attr = TupleDescAttr(targetrel->rd_att, attno);
1189  char *name;
1190 
1191  if (attr->attisdropped)
1192  {
1193  /*
1194  * can't use atttypid here, but it doesn't really matter what type
1195  * the Const claims to be.
1196  */
1197  var = (Var *) makeNullConst(INT4OID, -1, InvalidOid);
1198  name = NULL;
1199  }
1200  else
1201  {
1202  var = makeVar(exclRelIndex, attno + 1,
1203  attr->atttypid, attr->atttypmod,
1204  attr->attcollation,
1205  0);
1206  name = pstrdup(NameStr(attr->attname));
1207  }
1208 
1209  te = makeTargetEntry((Expr *) var,
1210  attno + 1,
1211  name,
1212  false);
1213 
1214  result = lappend(result, te);
1215  }
1216 
1217  /*
1218  * Add a whole-row-Var entry to support references to "EXCLUDED.*". Like
1219  * the other entries in the EXCLUDED tlist, its resno must match the Var's
1220  * varattno, else the wrong things happen while resolving references in
1221  * setrefs.c. This is against normal conventions for targetlists, but
1222  * it's okay since we don't use this as a real tlist.
1223  */
1224  var = makeVar(exclRelIndex, InvalidAttrNumber,
1225  targetrel->rd_rel->reltype,
1226  -1, InvalidOid, 0);
1227  te = makeTargetEntry((Expr *) var, InvalidAttrNumber, NULL, true);
1228  result = lappend(result, te);
1229 
1230  return result;
1231 }
1232 
1233 
1234 /*
1235  * count_rowexpr_columns -
1236  * get number of columns contained in a ROW() expression;
1237  * return -1 if expression isn't a RowExpr or a Var referencing one.
1238  *
1239  * This is currently used only for hint purposes, so we aren't terribly
1240  * tense about recognizing all possible cases. The Var case is interesting
1241  * because that's what we'll get in the INSERT ... SELECT (...) case.
1242  */
1243 static int
1245 {
1246  if (expr == NULL)
1247  return -1;
1248  if (IsA(expr, RowExpr))
1249  return list_length(((RowExpr *) expr)->args);
1250  if (IsA(expr, Var))
1251  {
1252  Var *var = (Var *) expr;
1253  AttrNumber attnum = var->varattno;
1254 
1255  if (attnum > 0 && var->vartype == RECORDOID)
1256  {
1257  RangeTblEntry *rte;
1258 
1259  rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
1260  if (rte->rtekind == RTE_SUBQUERY)
1261  {
1262  /* Subselect-in-FROM: examine sub-select's output expr */
1264  attnum);
1265 
1266  if (ste == NULL || ste->resjunk)
1267  return -1;
1268  expr = (Node *) ste->expr;
1269  if (IsA(expr, RowExpr))
1270  return list_length(((RowExpr *) expr)->args);
1271  }
1272  }
1273  }
1274  return -1;
1275 }
1276 
1277 
1278 /*
1279  * transformSelectStmt -
1280  * transforms a Select Statement
1281  *
1282  * Note: this covers only cases with no set operations and no VALUES lists;
1283  * see below for the other cases.
1284  */
1285 static Query *
1287 {
1288  Query *qry = makeNode(Query);
1289  Node *qual;
1290  ListCell *l;
1291 
1292  qry->commandType = CMD_SELECT;
1293 
1294  /* process the WITH clause independently of all else */
1295  if (stmt->withClause)
1296  {
1297  qry->hasRecursive = stmt->withClause->recursive;
1298  qry->cteList = transformWithClause(pstate, stmt->withClause);
1299  qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1300  }
1301 
1302  /* Complain if we get called from someplace where INTO is not allowed */
1303  if (stmt->intoClause)
1304  ereport(ERROR,
1305  (errcode(ERRCODE_SYNTAX_ERROR),
1306  errmsg("SELECT ... INTO is not allowed here"),
1307  parser_errposition(pstate,
1308  exprLocation((Node *) stmt->intoClause))));
1309 
1310  /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
1311  pstate->p_locking_clause = stmt->lockingClause;
1312 
1313  /* make WINDOW info available for window functions, too */
1314  pstate->p_windowdefs = stmt->windowClause;
1315 
1316  /* process the FROM clause */
1317  transformFromClause(pstate, stmt->fromClause);
1318 
1319  /* transform targetlist */
1320  qry->targetList = transformTargetList(pstate, stmt->targetList,
1322 
1323  /* mark column origins */
1324  markTargetListOrigins(pstate, qry->targetList);
1325 
1326  /* transform WHERE */
1327  qual = transformWhereClause(pstate, stmt->whereClause,
1328  EXPR_KIND_WHERE, "WHERE");
1329 
1330  /* initial processing of HAVING clause is much like WHERE clause */
1331  qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
1332  EXPR_KIND_HAVING, "HAVING");
1333 
1334  /*
1335  * Transform sorting/grouping stuff. Do ORDER BY first because both
1336  * transformGroupClause and transformDistinctClause need the results. Note
1337  * that these functions can also change the targetList, so it's passed to
1338  * them by reference.
1339  */
1340  qry->sortClause = transformSortClause(pstate,
1341  stmt->sortClause,
1342  &qry->targetList,
1344  false /* allow SQL92 rules */ );
1345 
1346  qry->groupClause = transformGroupClause(pstate,
1347  stmt->groupClause,
1348  &qry->groupingSets,
1349  &qry->targetList,
1350  qry->sortClause,
1352  false /* allow SQL92 rules */ );
1353  qry->groupDistinct = stmt->groupDistinct;
1354 
1355  if (stmt->distinctClause == NIL)
1356  {
1357  qry->distinctClause = NIL;
1358  qry->hasDistinctOn = false;
1359  }
1360  else if (linitial(stmt->distinctClause) == NULL)
1361  {
1362  /* We had SELECT DISTINCT */
1364  &qry->targetList,
1365  qry->sortClause,
1366  false);
1367  qry->hasDistinctOn = false;
1368  }
1369  else
1370  {
1371  /* We had SELECT DISTINCT ON */
1373  stmt->distinctClause,
1374  &qry->targetList,
1375  qry->sortClause);
1376  qry->hasDistinctOn = true;
1377  }
1378 
1379  /* transform LIMIT */
1380  qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1381  EXPR_KIND_OFFSET, "OFFSET",
1382  stmt->limitOption);
1383  qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1384  EXPR_KIND_LIMIT, "LIMIT",
1385  stmt->limitOption);
1386  qry->limitOption = stmt->limitOption;
1387 
1388  /* transform window clauses after we have seen all window functions */
1390  pstate->p_windowdefs,
1391  &qry->targetList);
1392 
1393  /* resolve any still-unresolved output columns as being type text */
1394  if (pstate->p_resolve_unknowns)
1395  resolveTargetListUnknowns(pstate, qry->targetList);
1396 
1397  qry->rtable = pstate->p_rtable;
1398  qry->rteperminfos = pstate->p_rteperminfos;
1399  qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1400 
1401  qry->hasSubLinks = pstate->p_hasSubLinks;
1402  qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
1403  qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
1404  qry->hasAggs = pstate->p_hasAggs;
1405 
1406  foreach(l, stmt->lockingClause)
1407  {
1408  transformLockingClause(pstate, qry,
1409  (LockingClause *) lfirst(l), false);
1410  }
1411 
1412  assign_query_collations(pstate, qry);
1413 
1414  /* this must be done after collations, for reliable comparison of exprs */
1415  if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
1416  parseCheckAggregates(pstate, qry);
1417 
1418  return qry;
1419 }
1420 
1421 /*
1422  * transformValuesClause -
1423  * transforms a VALUES clause that's being used as a standalone SELECT
1424  *
1425  * We build a Query containing a VALUES RTE, rather as if one had written
1426  * SELECT * FROM (VALUES ...) AS "*VALUES*"
1427  */
1428 static Query *
1430 {
1431  Query *qry = makeNode(Query);
1432  List *exprsLists = NIL;
1433  List *coltypes = NIL;
1434  List *coltypmods = NIL;
1435  List *colcollations = NIL;
1436  List **colexprs = NULL;
1437  int sublist_length = -1;
1438  bool lateral = false;
1439  ParseNamespaceItem *nsitem;
1440  ListCell *lc;
1441  ListCell *lc2;
1442  int i;
1443 
1444  qry->commandType = CMD_SELECT;
1445 
1446  /* Most SELECT stuff doesn't apply in a VALUES clause */
1447  Assert(stmt->distinctClause == NIL);
1448  Assert(stmt->intoClause == NULL);
1449  Assert(stmt->targetList == NIL);
1450  Assert(stmt->fromClause == NIL);
1451  Assert(stmt->whereClause == NULL);
1452  Assert(stmt->groupClause == NIL);
1453  Assert(stmt->havingClause == NULL);
1454  Assert(stmt->windowClause == NIL);
1455  Assert(stmt->op == SETOP_NONE);
1456 
1457  /* process the WITH clause independently of all else */
1458  if (stmt->withClause)
1459  {
1460  qry->hasRecursive = stmt->withClause->recursive;
1461  qry->cteList = transformWithClause(pstate, stmt->withClause);
1462  qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1463  }
1464 
1465  /*
1466  * For each row of VALUES, transform the raw expressions.
1467  *
1468  * Note that the intermediate representation we build is column-organized
1469  * not row-organized. That simplifies the type and collation processing
1470  * below.
1471  */
1472  foreach(lc, stmt->valuesLists)
1473  {
1474  List *sublist = (List *) lfirst(lc);
1475 
1476  /*
1477  * Do basic expression transformation (same as a ROW() expr, but here
1478  * we disallow SetToDefault)
1479  */
1480  sublist = transformExpressionList(pstate, sublist,
1481  EXPR_KIND_VALUES, false);
1482 
1483  /*
1484  * All the sublists must be the same length, *after* transformation
1485  * (which might expand '*' into multiple items). The VALUES RTE can't
1486  * handle anything different.
1487  */
1488  if (sublist_length < 0)
1489  {
1490  /* Remember post-transformation length of first sublist */
1491  sublist_length = list_length(sublist);
1492  /* and allocate array for per-column lists */
1493  colexprs = (List **) palloc0(sublist_length * sizeof(List *));
1494  }
1495  else if (sublist_length != list_length(sublist))
1496  {
1497  ereport(ERROR,
1498  (errcode(ERRCODE_SYNTAX_ERROR),
1499  errmsg("VALUES lists must all be the same length"),
1500  parser_errposition(pstate,
1501  exprLocation((Node *) sublist))));
1502  }
1503 
1504  /* Build per-column expression lists */
1505  i = 0;
1506  foreach(lc2, sublist)
1507  {
1508  Node *col = (Node *) lfirst(lc2);
1509 
1510  colexprs[i] = lappend(colexprs[i], col);
1511  i++;
1512  }
1513 
1514  /* Release sub-list's cells to save memory */
1515  list_free(sublist);
1516 
1517  /* Prepare an exprsLists element for this row */
1518  exprsLists = lappend(exprsLists, NIL);
1519  }
1520 
1521  /*
1522  * Now resolve the common types of the columns, and coerce everything to
1523  * those types. Then identify the common typmod and common collation, if
1524  * any, of each column.
1525  *
1526  * We must do collation processing now because (1) assign_query_collations
1527  * doesn't process rangetable entries, and (2) we need to label the VALUES
1528  * RTE with column collations for use in the outer query. We don't
1529  * consider conflict of implicit collations to be an error here; instead
1530  * the column will just show InvalidOid as its collation, and you'll get a
1531  * failure later if that results in failure to resolve a collation.
1532  *
1533  * Note we modify the per-column expression lists in-place.
1534  */
1535  for (i = 0; i < sublist_length; i++)
1536  {
1537  Oid coltype;
1538  int32 coltypmod;
1539  Oid colcoll;
1540 
1541  coltype = select_common_type(pstate, colexprs[i], "VALUES", NULL);
1542 
1543  foreach(lc, colexprs[i])
1544  {
1545  Node *col = (Node *) lfirst(lc);
1546 
1547  col = coerce_to_common_type(pstate, col, coltype, "VALUES");
1548  lfirst(lc) = (void *) col;
1549  }
1550 
1551  coltypmod = select_common_typmod(pstate, colexprs[i], coltype);
1552  colcoll = select_common_collation(pstate, colexprs[i], true);
1553 
1554  coltypes = lappend_oid(coltypes, coltype);
1555  coltypmods = lappend_int(coltypmods, coltypmod);
1556  colcollations = lappend_oid(colcollations, colcoll);
1557  }
1558 
1559  /*
1560  * Finally, rearrange the coerced expressions into row-organized lists.
1561  */
1562  for (i = 0; i < sublist_length; i++)
1563  {
1564  forboth(lc, colexprs[i], lc2, exprsLists)
1565  {
1566  Node *col = (Node *) lfirst(lc);
1567  List *sublist = lfirst(lc2);
1568 
1569  sublist = lappend(sublist, col);
1570  lfirst(lc2) = sublist;
1571  }
1572  list_free(colexprs[i]);
1573  }
1574 
1575  /*
1576  * Ordinarily there can't be any current-level Vars in the expression
1577  * lists, because the namespace was empty ... but if we're inside CREATE
1578  * RULE, then NEW/OLD references might appear. In that case we have to
1579  * mark the VALUES RTE as LATERAL.
1580  */
1581  if (pstate->p_rtable != NIL &&
1582  contain_vars_of_level((Node *) exprsLists, 0))
1583  lateral = true;
1584 
1585  /*
1586  * Generate the VALUES RTE
1587  */
1588  nsitem = addRangeTableEntryForValues(pstate, exprsLists,
1589  coltypes, coltypmods, colcollations,
1590  NULL, lateral, true);
1591  addNSItemToQuery(pstate, nsitem, true, true, true);
1592 
1593  /*
1594  * Generate a targetlist as though expanding "*"
1595  */
1596  Assert(pstate->p_next_resno == 1);
1597  qry->targetList = expandNSItemAttrs(pstate, nsitem, 0, true, -1);
1598 
1599  /*
1600  * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
1601  * VALUES, so cope.
1602  */
1603  qry->sortClause = transformSortClause(pstate,
1604  stmt->sortClause,
1605  &qry->targetList,
1607  false /* allow SQL92 rules */ );
1608 
1609  qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1610  EXPR_KIND_OFFSET, "OFFSET",
1611  stmt->limitOption);
1612  qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1613  EXPR_KIND_LIMIT, "LIMIT",
1614  stmt->limitOption);
1615  qry->limitOption = stmt->limitOption;
1616 
1617  if (stmt->lockingClause)
1618  ereport(ERROR,
1619  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1620  /*------
1621  translator: %s is a SQL row locking clause such as FOR UPDATE */
1622  errmsg("%s cannot be applied to VALUES",
1624  linitial(stmt->lockingClause))->strength))));
1625 
1626  qry->rtable = pstate->p_rtable;
1627  qry->rteperminfos = pstate->p_rteperminfos;
1628  qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1629 
1630  qry->hasSubLinks = pstate->p_hasSubLinks;
1631 
1632  assign_query_collations(pstate, qry);
1633 
1634  return qry;
1635 }
1636 
1637 /*
1638  * transformSetOperationStmt -
1639  * transforms a set-operations tree
1640  *
1641  * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1642  * structure to it. We must transform each leaf SELECT and build up a top-
1643  * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1644  * The tree of set operations is converted into the setOperations field of
1645  * the top-level Query.
1646  */
1647 static Query *
1649 {
1650  Query *qry = makeNode(Query);
1651  SelectStmt *leftmostSelect;
1652  int leftmostRTI;
1653  Query *leftmostQuery;
1654  SetOperationStmt *sostmt;
1655  List *sortClause;
1656  Node *limitOffset;
1657  Node *limitCount;
1658  List *lockingClause;
1659  WithClause *withClause;
1660  Node *node;
1661  ListCell *left_tlist,
1662  *lct,
1663  *lcm,
1664  *lcc,
1665  *l;
1666  List *targetvars,
1667  *targetnames,
1668  *sv_namespace;
1669  int sv_rtable_length;
1670  ParseNamespaceItem *jnsitem;
1671  ParseNamespaceColumn *sortnscolumns;
1672  int sortcolindex;
1673  int tllen;
1674 
1675  qry->commandType = CMD_SELECT;
1676 
1677  /*
1678  * Find leftmost leaf SelectStmt. We currently only need to do this in
1679  * order to deliver a suitable error message if there's an INTO clause
1680  * there, implying the set-op tree is in a context that doesn't allow
1681  * INTO. (transformSetOperationTree would throw error anyway, but it
1682  * seems worth the trouble to throw a different error for non-leftmost
1683  * INTO, so we produce that error in transformSetOperationTree.)
1684  */
1685  leftmostSelect = stmt->larg;
1686  while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1687  leftmostSelect = leftmostSelect->larg;
1688  Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1689  leftmostSelect->larg == NULL);
1690  if (leftmostSelect->intoClause)
1691  ereport(ERROR,
1692  (errcode(ERRCODE_SYNTAX_ERROR),
1693  errmsg("SELECT ... INTO is not allowed here"),
1694  parser_errposition(pstate,
1695  exprLocation((Node *) leftmostSelect->intoClause))));
1696 
1697  /*
1698  * We need to extract ORDER BY and other top-level clauses here and not
1699  * let transformSetOperationTree() see them --- else it'll just recurse
1700  * right back here!
1701  */
1702  sortClause = stmt->sortClause;
1703  limitOffset = stmt->limitOffset;
1704  limitCount = stmt->limitCount;
1705  lockingClause = stmt->lockingClause;
1706  withClause = stmt->withClause;
1707 
1708  stmt->sortClause = NIL;
1709  stmt->limitOffset = NULL;
1710  stmt->limitCount = NULL;
1711  stmt->lockingClause = NIL;
1712  stmt->withClause = NULL;
1713 
1714  /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1715  if (lockingClause)
1716  ereport(ERROR,
1717  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1718  /*------
1719  translator: %s is a SQL row locking clause such as FOR UPDATE */
1720  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1722  linitial(lockingClause))->strength))));
1723 
1724  /* Process the WITH clause independently of all else */
1725  if (withClause)
1726  {
1727  qry->hasRecursive = withClause->recursive;
1728  qry->cteList = transformWithClause(pstate, withClause);
1729  qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1730  }
1731 
1732  /*
1733  * Recursively transform the components of the tree.
1734  */
1735  sostmt = castNode(SetOperationStmt,
1736  transformSetOperationTree(pstate, stmt, true, NULL));
1737  Assert(sostmt);
1738  qry->setOperations = (Node *) sostmt;
1739 
1740  /*
1741  * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1742  */
1743  node = sostmt->larg;
1744  while (node && IsA(node, SetOperationStmt))
1745  node = ((SetOperationStmt *) node)->larg;
1746  Assert(node && IsA(node, RangeTblRef));
1747  leftmostRTI = ((RangeTblRef *) node)->rtindex;
1748  leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1749  Assert(leftmostQuery != NULL);
1750 
1751  /*
1752  * Generate dummy targetlist for outer query using column names of
1753  * leftmost select and common datatypes/collations of topmost set
1754  * operation. Also make lists of the dummy vars and their names for use
1755  * in parsing ORDER BY.
1756  *
1757  * Note: we use leftmostRTI as the varno of the dummy variables. It
1758  * shouldn't matter too much which RT index they have, as long as they
1759  * have one that corresponds to a real RT entry; else funny things may
1760  * happen when the tree is mashed by rule rewriting.
1761  */
1762  qry->targetList = NIL;
1763  targetvars = NIL;
1764  targetnames = NIL;
1765  sortnscolumns = (ParseNamespaceColumn *)
1766  palloc0(list_length(sostmt->colTypes) * sizeof(ParseNamespaceColumn));
1767  sortcolindex = 0;
1768 
1769  forfour(lct, sostmt->colTypes,
1770  lcm, sostmt->colTypmods,
1771  lcc, sostmt->colCollations,
1772  left_tlist, leftmostQuery->targetList)
1773  {
1774  Oid colType = lfirst_oid(lct);
1775  int32 colTypmod = lfirst_int(lcm);
1776  Oid colCollation = lfirst_oid(lcc);
1777  TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1778  char *colName;
1779  TargetEntry *tle;
1780  Var *var;
1781 
1782  Assert(!lefttle->resjunk);
1783  colName = pstrdup(lefttle->resname);
1784  var = makeVar(leftmostRTI,
1785  lefttle->resno,
1786  colType,
1787  colTypmod,
1788  colCollation,
1789  0);
1790  var->location = exprLocation((Node *) lefttle->expr);
1791  tle = makeTargetEntry((Expr *) var,
1792  (AttrNumber) pstate->p_next_resno++,
1793  colName,
1794  false);
1795  qry->targetList = lappend(qry->targetList, tle);
1796  targetvars = lappend(targetvars, var);
1797  targetnames = lappend(targetnames, makeString(colName));
1798  sortnscolumns[sortcolindex].p_varno = leftmostRTI;
1799  sortnscolumns[sortcolindex].p_varattno = lefttle->resno;
1800  sortnscolumns[sortcolindex].p_vartype = colType;
1801  sortnscolumns[sortcolindex].p_vartypmod = colTypmod;
1802  sortnscolumns[sortcolindex].p_varcollid = colCollation;
1803  sortnscolumns[sortcolindex].p_varnosyn = leftmostRTI;
1804  sortnscolumns[sortcolindex].p_varattnosyn = lefttle->resno;
1805  sortcolindex++;
1806  }
1807 
1808  /*
1809  * As a first step towards supporting sort clauses that are expressions
1810  * using the output columns, generate a namespace entry that makes the
1811  * output columns visible. A Join RTE node is handy for this, since we
1812  * can easily control the Vars generated upon matches.
1813  *
1814  * Note: we don't yet do anything useful with such cases, but at least
1815  * "ORDER BY upper(foo)" will draw the right error message rather than
1816  * "foo not found".
1817  */
1818  sv_rtable_length = list_length(pstate->p_rtable);
1819 
1820  jnsitem = addRangeTableEntryForJoin(pstate,
1821  targetnames,
1822  sortnscolumns,
1823  JOIN_INNER,
1824  0,
1825  targetvars,
1826  NIL,
1827  NIL,
1828  NULL,
1829  NULL,
1830  false);
1831 
1832  sv_namespace = pstate->p_namespace;
1833  pstate->p_namespace = NIL;
1834 
1835  /* add jnsitem to column namespace only */
1836  addNSItemToQuery(pstate, jnsitem, false, false, true);
1837 
1838  /*
1839  * For now, we don't support resjunk sort clauses on the output of a
1840  * setOperation tree --- you can only use the SQL92-spec options of
1841  * selecting an output column by name or number. Enforce by checking that
1842  * transformSortClause doesn't add any items to tlist.
1843  */
1844  tllen = list_length(qry->targetList);
1845 
1846  qry->sortClause = transformSortClause(pstate,
1847  sortClause,
1848  &qry->targetList,
1850  false /* allow SQL92 rules */ );
1851 
1852  /* restore namespace, remove join RTE from rtable */
1853  pstate->p_namespace = sv_namespace;
1854  pstate->p_rtable = list_truncate(pstate->p_rtable, sv_rtable_length);
1855 
1856  if (tllen != list_length(qry->targetList))
1857  ereport(ERROR,
1858  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1859  errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
1860  errdetail("Only result column names can be used, not expressions or functions."),
1861  errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause."),
1862  parser_errposition(pstate,
1863  exprLocation(list_nth(qry->targetList, tllen)))));
1864 
1865  qry->limitOffset = transformLimitClause(pstate, limitOffset,
1866  EXPR_KIND_OFFSET, "OFFSET",
1867  stmt->limitOption);
1868  qry->limitCount = transformLimitClause(pstate, limitCount,
1869  EXPR_KIND_LIMIT, "LIMIT",
1870  stmt->limitOption);
1871  qry->limitOption = stmt->limitOption;
1872 
1873  qry->rtable = pstate->p_rtable;
1874  qry->rteperminfos = pstate->p_rteperminfos;
1875  qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1876 
1877  qry->hasSubLinks = pstate->p_hasSubLinks;
1878  qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
1879  qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
1880  qry->hasAggs = pstate->p_hasAggs;
1881 
1882  foreach(l, lockingClause)
1883  {
1884  transformLockingClause(pstate, qry,
1885  (LockingClause *) lfirst(l), false);
1886  }
1887 
1888  assign_query_collations(pstate, qry);
1889 
1890  /* this must be done after collations, for reliable comparison of exprs */
1891  if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
1892  parseCheckAggregates(pstate, qry);
1893 
1894  return qry;
1895 }
1896 
1897 /*
1898  * Make a SortGroupClause node for a SetOperationStmt's groupClauses
1899  *
1900  * If require_hash is true, the caller is indicating that they need hash
1901  * support or they will fail. So look extra hard for hash support.
1902  */
1904 makeSortGroupClauseForSetOp(Oid rescoltype, bool require_hash)
1905 {
1907  Oid sortop;
1908  Oid eqop;
1909  bool hashable;
1910 
1911  /* determine the eqop and optional sortop */
1912  get_sort_group_operators(rescoltype,
1913  false, true, false,
1914  &sortop, &eqop, NULL,
1915  &hashable);
1916 
1917  /*
1918  * The type cache doesn't believe that record is hashable (see
1919  * cache_record_field_properties()), but if the caller really needs hash
1920  * support, we can assume it does. Worst case, if any components of the
1921  * record don't support hashing, we will fail at execution.
1922  */
1923  if (require_hash && (rescoltype == RECORDOID || rescoltype == RECORDARRAYOID))
1924  hashable = true;
1925 
1926  /* we don't have a tlist yet, so can't assign sortgrouprefs */
1927  grpcl->tleSortGroupRef = 0;
1928  grpcl->eqop = eqop;
1929  grpcl->sortop = sortop;
1930  grpcl->nulls_first = false; /* OK with or without sortop */
1931  grpcl->hashable = hashable;
1932 
1933  return grpcl;
1934 }
1935 
1936 /*
1937  * transformSetOperationTree
1938  * Recursively transform leaves and internal nodes of a set-op tree
1939  *
1940  * In addition to returning the transformed node, if targetlist isn't NULL
1941  * then we return a list of its non-resjunk TargetEntry nodes. For a leaf
1942  * set-op node these are the actual targetlist entries; otherwise they are
1943  * dummy entries created to carry the type, typmod, collation, and location
1944  * (for error messages) of each output column of the set-op node. This info
1945  * is needed only during the internal recursion of this function, so outside
1946  * callers pass NULL for targetlist. Note: the reason for passing the
1947  * actual targetlist entries of a leaf node is so that upper levels can
1948  * replace UNKNOWN Consts with properly-coerced constants.
1949  */
1950 static Node *
1952  bool isTopLevel, List **targetlist)
1953 {
1954  bool isLeaf;
1955 
1956  Assert(stmt && IsA(stmt, SelectStmt));
1957 
1958  /* Guard against stack overflow due to overly complex set-expressions */
1960 
1961  /*
1962  * Validity-check both leaf and internal SELECTs for disallowed ops.
1963  */
1964  if (stmt->intoClause)
1965  ereport(ERROR,
1966  (errcode(ERRCODE_SYNTAX_ERROR),
1967  errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT"),
1968  parser_errposition(pstate,
1969  exprLocation((Node *) stmt->intoClause))));
1970 
1971  /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1972  if (stmt->lockingClause)
1973  ereport(ERROR,
1974  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1975  /*------
1976  translator: %s is a SQL row locking clause such as FOR UPDATE */
1977  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1979  linitial(stmt->lockingClause))->strength))));
1980 
1981  /*
1982  * If an internal node of a set-op tree has ORDER BY, LIMIT, FOR UPDATE,
1983  * or WITH clauses attached, we need to treat it like a leaf node to
1984  * generate an independent sub-Query tree. Otherwise, it can be
1985  * represented by a SetOperationStmt node underneath the parent Query.
1986  */
1987  if (stmt->op == SETOP_NONE)
1988  {
1989  Assert(stmt->larg == NULL && stmt->rarg == NULL);
1990  isLeaf = true;
1991  }
1992  else
1993  {
1994  Assert(stmt->larg != NULL && stmt->rarg != NULL);
1995  if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
1996  stmt->lockingClause || stmt->withClause)
1997  isLeaf = true;
1998  else
1999  isLeaf = false;
2000  }
2001 
2002  if (isLeaf)
2003  {
2004  /* Process leaf SELECT */
2005  Query *selectQuery;
2006  char selectName[32];
2007  ParseNamespaceItem *nsitem;
2008  RangeTblRef *rtr;
2009  ListCell *tl;
2010 
2011  /*
2012  * Transform SelectStmt into a Query.
2013  *
2014  * This works the same as SELECT transformation normally would, except
2015  * that we prevent resolving unknown-type outputs as TEXT. This does
2016  * not change the subquery's semantics since if the column type
2017  * matters semantically, it would have been resolved to something else
2018  * anyway. Doing this lets us resolve such outputs using
2019  * select_common_type(), below.
2020  *
2021  * Note: previously transformed sub-queries don't affect the parsing
2022  * of this sub-query, because they are not in the toplevel pstate's
2023  * namespace list.
2024  */
2025  selectQuery = parse_sub_analyze((Node *) stmt, pstate,
2026  NULL, false, false);
2027 
2028  /*
2029  * Check for bogus references to Vars on the current query level (but
2030  * upper-level references are okay). Normally this can't happen
2031  * because the namespace will be empty, but it could happen if we are
2032  * inside a rule.
2033  */
2034  if (pstate->p_namespace)
2035  {
2036  if (contain_vars_of_level((Node *) selectQuery, 1))
2037  ereport(ERROR,
2038  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2039  errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"),
2040  parser_errposition(pstate,
2041  locate_var_of_level((Node *) selectQuery, 1))));
2042  }
2043 
2044  /*
2045  * Extract a list of the non-junk TLEs for upper-level processing.
2046  */
2047  if (targetlist)
2048  {
2049  *targetlist = NIL;
2050  foreach(tl, selectQuery->targetList)
2051  {
2052  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2053 
2054  if (!tle->resjunk)
2055  *targetlist = lappend(*targetlist, tle);
2056  }
2057  }
2058 
2059  /*
2060  * Make the leaf query be a subquery in the top-level rangetable.
2061  */
2062  snprintf(selectName, sizeof(selectName), "*SELECT* %d",
2063  list_length(pstate->p_rtable) + 1);
2064  nsitem = addRangeTableEntryForSubquery(pstate,
2065  selectQuery,
2066  makeAlias(selectName, NIL),
2067  false,
2068  false);
2069 
2070  /*
2071  * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
2072  */
2073  rtr = makeNode(RangeTblRef);
2074  rtr->rtindex = nsitem->p_rtindex;
2075  return (Node *) rtr;
2076  }
2077  else
2078  {
2079  /* Process an internal node (set operation node) */
2081  List *ltargetlist;
2082  List *rtargetlist;
2083  ListCell *ltl;
2084  ListCell *rtl;
2085  const char *context;
2086  bool recursive = (pstate->p_parent_cte &&
2087  pstate->p_parent_cte->cterecursive);
2088 
2089  context = (stmt->op == SETOP_UNION ? "UNION" :
2090  (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2091  "EXCEPT"));
2092 
2093  op->op = stmt->op;
2094  op->all = stmt->all;
2095 
2096  /*
2097  * Recursively transform the left child node.
2098  */
2099  op->larg = transformSetOperationTree(pstate, stmt->larg,
2100  false,
2101  &ltargetlist);
2102 
2103  /*
2104  * If we are processing a recursive union query, now is the time to
2105  * examine the non-recursive term's output columns and mark the
2106  * containing CTE as having those result columns. We should do this
2107  * only at the topmost setop of the CTE, of course.
2108  */
2109  if (isTopLevel && recursive)
2110  determineRecursiveColTypes(pstate, op->larg, ltargetlist);
2111 
2112  /*
2113  * Recursively transform the right child node.
2114  */
2115  op->rarg = transformSetOperationTree(pstate, stmt->rarg,
2116  false,
2117  &rtargetlist);
2118 
2119  /*
2120  * Verify that the two children have the same number of non-junk
2121  * columns, and determine the types of the merged output columns.
2122  */
2123  if (list_length(ltargetlist) != list_length(rtargetlist))
2124  ereport(ERROR,
2125  (errcode(ERRCODE_SYNTAX_ERROR),
2126  errmsg("each %s query must have the same number of columns",
2127  context),
2128  parser_errposition(pstate,
2129  exprLocation((Node *) rtargetlist))));
2130 
2131  if (targetlist)
2132  *targetlist = NIL;
2133  op->colTypes = NIL;
2134  op->colTypmods = NIL;
2135  op->colCollations = NIL;
2136  op->groupClauses = NIL;
2137  forboth(ltl, ltargetlist, rtl, rtargetlist)
2138  {
2139  TargetEntry *ltle = (TargetEntry *) lfirst(ltl);
2140  TargetEntry *rtle = (TargetEntry *) lfirst(rtl);
2141  Node *lcolnode = (Node *) ltle->expr;
2142  Node *rcolnode = (Node *) rtle->expr;
2143  Oid lcoltype = exprType(lcolnode);
2144  Oid rcoltype = exprType(rcolnode);
2145  Node *bestexpr;
2146  int bestlocation;
2147  Oid rescoltype;
2148  int32 rescoltypmod;
2149  Oid rescolcoll;
2150 
2151  /* select common type, same as CASE et al */
2152  rescoltype = select_common_type(pstate,
2153  list_make2(lcolnode, rcolnode),
2154  context,
2155  &bestexpr);
2156  bestlocation = exprLocation(bestexpr);
2157 
2158  /*
2159  * Verify the coercions are actually possible. If not, we'd fail
2160  * later anyway, but we want to fail now while we have sufficient
2161  * context to produce an error cursor position.
2162  *
2163  * For all non-UNKNOWN-type cases, we verify coercibility but we
2164  * don't modify the child's expression, for fear of changing the
2165  * child query's semantics.
2166  *
2167  * If a child expression is an UNKNOWN-type Const or Param, we
2168  * want to replace it with the coerced expression. This can only
2169  * happen when the child is a leaf set-op node. It's safe to
2170  * replace the expression because if the child query's semantics
2171  * depended on the type of this output column, it'd have already
2172  * coerced the UNKNOWN to something else. We want to do this
2173  * because (a) we want to verify that a Const is valid for the
2174  * target type, or resolve the actual type of an UNKNOWN Param,
2175  * and (b) we want to avoid unnecessary discrepancies between the
2176  * output type of the child query and the resolved target type.
2177  * Such a discrepancy would disable optimization in the planner.
2178  *
2179  * If it's some other UNKNOWN-type node, eg a Var, we do nothing
2180  * (knowing that coerce_to_common_type would fail). The planner
2181  * is sometimes able to fold an UNKNOWN Var to a constant before
2182  * it has to coerce the type, so failing now would just break
2183  * cases that might work.
2184  */
2185  if (lcoltype != UNKNOWNOID)
2186  lcolnode = coerce_to_common_type(pstate, lcolnode,
2187  rescoltype, context);
2188  else if (IsA(lcolnode, Const) ||
2189  IsA(lcolnode, Param))
2190  {
2191  lcolnode = coerce_to_common_type(pstate, lcolnode,
2192  rescoltype, context);
2193  ltle->expr = (Expr *) lcolnode;
2194  }
2195 
2196  if (rcoltype != UNKNOWNOID)
2197  rcolnode = coerce_to_common_type(pstate, rcolnode,
2198  rescoltype, context);
2199  else if (IsA(rcolnode, Const) ||
2200  IsA(rcolnode, Param))
2201  {
2202  rcolnode = coerce_to_common_type(pstate, rcolnode,
2203  rescoltype, context);
2204  rtle->expr = (Expr *) rcolnode;
2205  }
2206 
2207  rescoltypmod = select_common_typmod(pstate,
2208  list_make2(lcolnode, rcolnode),
2209  rescoltype);
2210 
2211  /*
2212  * Select common collation. A common collation is required for
2213  * all set operators except UNION ALL; see SQL:2008 7.13 <query
2214  * expression> Syntax Rule 15c. (If we fail to identify a common
2215  * collation for a UNION ALL column, the colCollations element
2216  * will be set to InvalidOid, which may result in a runtime error
2217  * if something at a higher query level wants to use the column's
2218  * collation.)
2219  */
2220  rescolcoll = select_common_collation(pstate,
2221  list_make2(lcolnode, rcolnode),
2222  (op->op == SETOP_UNION && op->all));
2223 
2224  /* emit results */
2225  op->colTypes = lappend_oid(op->colTypes, rescoltype);
2226  op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
2227  op->colCollations = lappend_oid(op->colCollations, rescolcoll);
2228 
2229  /*
2230  * For all cases except UNION ALL, identify the grouping operators
2231  * (and, if available, sorting operators) that will be used to
2232  * eliminate duplicates.
2233  */
2234  if (op->op != SETOP_UNION || !op->all)
2235  {
2236  ParseCallbackState pcbstate;
2237 
2238  setup_parser_errposition_callback(&pcbstate, pstate,
2239  bestlocation);
2240 
2241  /*
2242  * If it's a recursive union, we need to require hashing
2243  * support.
2244  */
2245  op->groupClauses = lappend(op->groupClauses,
2246  makeSortGroupClauseForSetOp(rescoltype, recursive));
2247 
2249  }
2250 
2251  /*
2252  * Construct a dummy tlist entry to return. We use a SetToDefault
2253  * node for the expression, since it carries exactly the fields
2254  * needed, but any other expression node type would do as well.
2255  */
2256  if (targetlist)
2257  {
2258  SetToDefault *rescolnode = makeNode(SetToDefault);
2259  TargetEntry *restle;
2260 
2261  rescolnode->typeId = rescoltype;
2262  rescolnode->typeMod = rescoltypmod;
2263  rescolnode->collation = rescolcoll;
2264  rescolnode->location = bestlocation;
2265  restle = makeTargetEntry((Expr *) rescolnode,
2266  0, /* no need to set resno */
2267  NULL,
2268  false);
2269  *targetlist = lappend(*targetlist, restle);
2270  }
2271  }
2272 
2273  return (Node *) op;
2274  }
2275 }
2276 
2277 /*
2278  * Process the outputs of the non-recursive term of a recursive union
2279  * to set up the parent CTE's columns
2280  */
2281 static void
2282 determineRecursiveColTypes(ParseState *pstate, Node *larg, List *nrtargetlist)
2283 {
2284  Node *node;
2285  int leftmostRTI;
2286  Query *leftmostQuery;
2287  List *targetList;
2288  ListCell *left_tlist;
2289  ListCell *nrtl;
2290  int next_resno;
2291 
2292  /*
2293  * Find leftmost leaf SELECT
2294  */
2295  node = larg;
2296  while (node && IsA(node, SetOperationStmt))
2297  node = ((SetOperationStmt *) node)->larg;
2298  Assert(node && IsA(node, RangeTblRef));
2299  leftmostRTI = ((RangeTblRef *) node)->rtindex;
2300  leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
2301  Assert(leftmostQuery != NULL);
2302 
2303  /*
2304  * Generate dummy targetlist using column names of leftmost select and
2305  * dummy result expressions of the non-recursive term.
2306  */
2307  targetList = NIL;
2308  next_resno = 1;
2309 
2310  forboth(nrtl, nrtargetlist, left_tlist, leftmostQuery->targetList)
2311  {
2312  TargetEntry *nrtle = (TargetEntry *) lfirst(nrtl);
2313  TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
2314  char *colName;
2315  TargetEntry *tle;
2316 
2317  Assert(!lefttle->resjunk);
2318  colName = pstrdup(lefttle->resname);
2319  tle = makeTargetEntry(nrtle->expr,
2320  next_resno++,
2321  colName,
2322  false);
2323  targetList = lappend(targetList, tle);
2324  }
2325 
2326  /* Now build CTE's output column info using dummy targetlist */
2327  analyzeCTETargetList(pstate, pstate->p_parent_cte, targetList);
2328 }
2329 
2330 
2331 /*
2332  * transformReturnStmt -
2333  * transforms a return statement
2334  */
2335 static Query *
2337 {
2338  Query *qry = makeNode(Query);
2339 
2340  qry->commandType = CMD_SELECT;
2341  qry->isReturn = true;
2342 
2344  1, NULL, false));
2345 
2346  if (pstate->p_resolve_unknowns)
2347  resolveTargetListUnknowns(pstate, qry->targetList);
2348  qry->rtable = pstate->p_rtable;
2349  qry->rteperminfos = pstate->p_rteperminfos;
2350  qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2351  qry->hasSubLinks = pstate->p_hasSubLinks;
2352  qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
2353  qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2354  qry->hasAggs = pstate->p_hasAggs;
2355 
2356  assign_query_collations(pstate, qry);
2357 
2358  return qry;
2359 }
2360 
2361 
2362 /*
2363  * transformUpdateStmt -
2364  * transforms an update statement
2365  */
2366 static Query *
2368 {
2369  Query *qry = makeNode(Query);
2370  ParseNamespaceItem *nsitem;
2371  Node *qual;
2372 
2373  qry->commandType = CMD_UPDATE;
2374  pstate->p_is_insert = false;
2375 
2376  /* process the WITH clause independently of all else */
2377  if (stmt->withClause)
2378  {
2379  qry->hasRecursive = stmt->withClause->recursive;
2380  qry->cteList = transformWithClause(pstate, stmt->withClause);
2381  qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
2382  }
2383 
2384  qry->resultRelation = setTargetTable(pstate, stmt->relation,
2385  stmt->relation->inh,
2386  true,
2387  ACL_UPDATE);
2388  nsitem = pstate->p_target_nsitem;
2389 
2390  /* subqueries in FROM cannot access the result relation */
2391  nsitem->p_lateral_only = true;
2392  nsitem->p_lateral_ok = false;
2393 
2394  /*
2395  * the FROM clause is non-standard SQL syntax. We used to be able to do
2396  * this with REPLACE in POSTQUEL so we keep the feature.
2397  */
2398  transformFromClause(pstate, stmt->fromClause);
2399 
2400  /* remaining clauses can reference the result relation normally */
2401  nsitem->p_lateral_only = false;
2402  nsitem->p_lateral_ok = true;
2403 
2404  qual = transformWhereClause(pstate, stmt->whereClause,
2405  EXPR_KIND_WHERE, "WHERE");
2406 
2407  qry->returningList = transformReturningList(pstate, stmt->returningList);
2408 
2409  /*
2410  * Now we are done with SELECT-like processing, and can get on with
2411  * transforming the target list to match the UPDATE target columns.
2412  */
2413  qry->targetList = transformUpdateTargetList(pstate, stmt->targetList);
2414 
2415  qry->rtable = pstate->p_rtable;
2416  qry->rteperminfos = pstate->p_rteperminfos;
2417  qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2418 
2419  qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2420  qry->hasSubLinks = pstate->p_hasSubLinks;
2421 
2422  assign_query_collations(pstate, qry);
2423 
2424  return qry;
2425 }
2426 
2427 /*
2428  * transformUpdateTargetList -
2429  * handle SET clause in UPDATE/MERGE/INSERT ... ON CONFLICT UPDATE
2430  */
2431 List *
2433 {
2434  List *tlist = NIL;
2435  RTEPermissionInfo *target_perminfo;
2436  ListCell *orig_tl;
2437  ListCell *tl;
2438 
2439  tlist = transformTargetList(pstate, origTlist,
2441 
2442  /* Prepare to assign non-conflicting resnos to resjunk attributes */
2445 
2446  /* Prepare non-junk columns for assignment to target table */
2447  target_perminfo = pstate->p_target_nsitem->p_perminfo;
2448  orig_tl = list_head(origTlist);
2449 
2450  foreach(tl, tlist)
2451  {
2452  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2453  ResTarget *origTarget;
2454  int attrno;
2455 
2456  if (tle->resjunk)
2457  {
2458  /*
2459  * Resjunk nodes need no additional processing, but be sure they
2460  * have resnos that do not match any target columns; else rewriter
2461  * or planner might get confused. They don't need a resname
2462  * either.
2463  */
2464  tle->resno = (AttrNumber) pstate->p_next_resno++;
2465  tle->resname = NULL;
2466  continue;
2467  }
2468  if (orig_tl == NULL)
2469  elog(ERROR, "UPDATE target count mismatch --- internal error");
2470  origTarget = lfirst_node(ResTarget, orig_tl);
2471 
2472  attrno = attnameAttNum(pstate->p_target_relation,
2473  origTarget->name, true);
2474  if (attrno == InvalidAttrNumber)
2475  ereport(ERROR,
2476  (errcode(ERRCODE_UNDEFINED_COLUMN),
2477  errmsg("column \"%s\" of relation \"%s\" does not exist",
2478  origTarget->name,
2480  parser_errposition(pstate, origTarget->location)));
2481 
2482  updateTargetListEntry(pstate, tle, origTarget->name,
2483  attrno,
2484  origTarget->indirection,
2485  origTarget->location);
2486 
2487  /* Mark the target column as requiring update permissions */
2488  target_perminfo->updatedCols = bms_add_member(target_perminfo->updatedCols,
2490 
2491  orig_tl = lnext(origTlist, orig_tl);
2492  }
2493  if (orig_tl != NULL)
2494  elog(ERROR, "UPDATE target count mismatch --- internal error");
2495 
2496  return tlist;
2497 }
2498 
2499 /*
2500  * transformReturningList -
2501  * handle a RETURNING clause in INSERT/UPDATE/DELETE
2502  */
2503 static List *
2504 transformReturningList(ParseState *pstate, List *returningList)
2505 {
2506  List *rlist;
2507  int save_next_resno;
2508 
2509  if (returningList == NIL)
2510  return NIL; /* nothing to do */
2511 
2512  /*
2513  * We need to assign resnos starting at one in the RETURNING list. Save
2514  * and restore the main tlist's value of p_next_resno, just in case
2515  * someone looks at it later (probably won't happen).
2516  */
2517  save_next_resno = pstate->p_next_resno;
2518  pstate->p_next_resno = 1;
2519 
2520  /* transform RETURNING identically to a SELECT targetlist */
2521  rlist = transformTargetList(pstate, returningList, EXPR_KIND_RETURNING);
2522 
2523  /*
2524  * Complain if the nonempty tlist expanded to nothing (which is possible
2525  * if it contains only a star-expansion of a zero-column table). If we
2526  * allow this, the parsed Query will look like it didn't have RETURNING,
2527  * with results that would probably surprise the user.
2528  */
2529  if (rlist == NIL)
2530  ereport(ERROR,
2531  (errcode(ERRCODE_SYNTAX_ERROR),
2532  errmsg("RETURNING must have at least one column"),
2533  parser_errposition(pstate,
2534  exprLocation(linitial(returningList)))));
2535 
2536  /* mark column origins */
2537  markTargetListOrigins(pstate, rlist);
2538 
2539  /* resolve any still-unresolved output columns as being type text */
2540  if (pstate->p_resolve_unknowns)
2541  resolveTargetListUnknowns(pstate, rlist);
2542 
2543  /* restore state */
2544  pstate->p_next_resno = save_next_resno;
2545 
2546  return rlist;
2547 }
2548 
2549 
2550 /*
2551  * transformPLAssignStmt -
2552  * transform a PL/pgSQL assignment statement
2553  *
2554  * If there is no opt_indirection, the transformed statement looks like
2555  * "SELECT a_expr ...", except the expression has been cast to the type of
2556  * the target. With indirection, it's still a SELECT, but the expression will
2557  * incorporate FieldStore and/or assignment SubscriptingRef nodes to compute a
2558  * new value for a container-type variable represented by the target. The
2559  * expression references the target as the container source.
2560  */
2561 static Query *
2563 {
2564  Query *qry = makeNode(Query);
2565  ColumnRef *cref = makeNode(ColumnRef);
2566  List *indirection = stmt->indirection;
2567  int nnames = stmt->nnames;
2568  SelectStmt *sstmt = stmt->val;
2569  Node *target;
2570  Oid targettype;
2571  int32 targettypmod;
2572  Oid targetcollation;
2573  List *tlist;
2574  TargetEntry *tle;
2575  Oid type_id;
2576  Node *qual;
2577  ListCell *l;
2578 
2579  /*
2580  * First, construct a ColumnRef for the target variable. If the target
2581  * has more than one dotted name, we have to pull the extra names out of
2582  * the indirection list.
2583  */
2584  cref->fields = list_make1(makeString(stmt->name));
2585  cref->location = stmt->location;
2586  if (nnames > 1)
2587  {
2588  /* avoid munging the raw parsetree */
2589  indirection = list_copy(indirection);
2590  while (--nnames > 0 && indirection != NIL)
2591  {
2592  Node *ind = (Node *) linitial(indirection);
2593 
2594  if (!IsA(ind, String))
2595  elog(ERROR, "invalid name count in PLAssignStmt");
2596  cref->fields = lappend(cref->fields, ind);
2597  indirection = list_delete_first(indirection);
2598  }
2599  }
2600 
2601  /*
2602  * Transform the target reference. Typically we will get back a Param
2603  * node, but there's no reason to be too picky about its type.
2604  */
2605  target = transformExpr(pstate, (Node *) cref,
2607  targettype = exprType(target);
2608  targettypmod = exprTypmod(target);
2609  targetcollation = exprCollation(target);
2610 
2611  /*
2612  * The rest mostly matches transformSelectStmt, except that we needn't
2613  * consider WITH or INTO, and we build a targetlist our own way.
2614  */
2615  qry->commandType = CMD_SELECT;
2616  pstate->p_is_insert = false;
2617 
2618  /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
2619  pstate->p_locking_clause = sstmt->lockingClause;
2620 
2621  /* make WINDOW info available for window functions, too */
2622  pstate->p_windowdefs = sstmt->windowClause;
2623 
2624  /* process the FROM clause */
2625  transformFromClause(pstate, sstmt->fromClause);
2626 
2627  /* initially transform the targetlist as if in SELECT */
2628  tlist = transformTargetList(pstate, sstmt->targetList,
2630 
2631  /* we should have exactly one targetlist item */
2632  if (list_length(tlist) != 1)
2633  ereport(ERROR,
2634  (errcode(ERRCODE_SYNTAX_ERROR),
2635  errmsg_plural("assignment source returned %d column",
2636  "assignment source returned %d columns",
2637  list_length(tlist),
2638  list_length(tlist))));
2639 
2640  tle = linitial_node(TargetEntry, tlist);
2641 
2642  /*
2643  * This next bit is similar to transformAssignedExpr; the key difference
2644  * is we use COERCION_PLPGSQL not COERCION_ASSIGNMENT.
2645  */
2646  type_id = exprType((Node *) tle->expr);
2647 
2649 
2650  if (indirection)
2651  {
2652  tle->expr = (Expr *)
2654  target,
2655  stmt->name,
2656  false,
2657  targettype,
2658  targettypmod,
2659  targetcollation,
2660  indirection,
2661  list_head(indirection),
2662  (Node *) tle->expr,
2664  exprLocation(target));
2665  }
2666  else if (targettype != type_id &&
2667  (targettype == RECORDOID || ISCOMPLEX(targettype)) &&
2668  (type_id == RECORDOID || ISCOMPLEX(type_id)))
2669  {
2670  /*
2671  * Hack: do not let coerce_to_target_type() deal with inconsistent
2672  * composite types. Just pass the expression result through as-is,
2673  * and let the PL/pgSQL executor do the conversion its way. This is
2674  * rather bogus, but it's needed for backwards compatibility.
2675  */
2676  }
2677  else
2678  {
2679  /*
2680  * For normal non-qualified target column, do type checking and
2681  * coercion.
2682  */
2683  Node *orig_expr = (Node *) tle->expr;
2684 
2685  tle->expr = (Expr *)
2686  coerce_to_target_type(pstate,
2687  orig_expr, type_id,
2688  targettype, targettypmod,
2691  -1);
2692  /* With COERCION_PLPGSQL, this error is probably unreachable */
2693  if (tle->expr == NULL)
2694  ereport(ERROR,
2695  (errcode(ERRCODE_DATATYPE_MISMATCH),
2696  errmsg("variable \"%s\" is of type %s"
2697  " but expression is of type %s",
2698  stmt->name,
2699  format_type_be(targettype),
2700  format_type_be(type_id)),
2701  errhint("You will need to rewrite or cast the expression."),
2702  parser_errposition(pstate, exprLocation(orig_expr))));
2703  }
2704 
2705  pstate->p_expr_kind = EXPR_KIND_NONE;
2706 
2707  qry->targetList = list_make1(tle);
2708 
2709  /* transform WHERE */
2710  qual = transformWhereClause(pstate, sstmt->whereClause,
2711  EXPR_KIND_WHERE, "WHERE");
2712 
2713  /* initial processing of HAVING clause is much like WHERE clause */
2714  qry->havingQual = transformWhereClause(pstate, sstmt->havingClause,
2715  EXPR_KIND_HAVING, "HAVING");
2716 
2717  /*
2718  * Transform sorting/grouping stuff. Do ORDER BY first because both
2719  * transformGroupClause and transformDistinctClause need the results. Note
2720  * that these functions can also change the targetList, so it's passed to
2721  * them by reference.
2722  */
2723  qry->sortClause = transformSortClause(pstate,
2724  sstmt->sortClause,
2725  &qry->targetList,
2727  false /* allow SQL92 rules */ );
2728 
2729  qry->groupClause = transformGroupClause(pstate,
2730  sstmt->groupClause,
2731  &qry->groupingSets,
2732  &qry->targetList,
2733  qry->sortClause,
2735  false /* allow SQL92 rules */ );
2736 
2737  if (sstmt->distinctClause == NIL)
2738  {
2739  qry->distinctClause = NIL;
2740  qry->hasDistinctOn = false;
2741  }
2742  else if (linitial(sstmt->distinctClause) == NULL)
2743  {
2744  /* We had SELECT DISTINCT */
2746  &qry->targetList,
2747  qry->sortClause,
2748  false);
2749  qry->hasDistinctOn = false;
2750  }
2751  else
2752  {
2753  /* We had SELECT DISTINCT ON */
2755  sstmt->distinctClause,
2756  &qry->targetList,
2757  qry->sortClause);
2758  qry->hasDistinctOn = true;
2759  }
2760 
2761  /* transform LIMIT */
2762  qry->limitOffset = transformLimitClause(pstate, sstmt->limitOffset,
2763  EXPR_KIND_OFFSET, "OFFSET",
2764  sstmt->limitOption);
2765  qry->limitCount = transformLimitClause(pstate, sstmt->limitCount,
2766  EXPR_KIND_LIMIT, "LIMIT",
2767  sstmt->limitOption);
2768  qry->limitOption = sstmt->limitOption;
2769 
2770  /* transform window clauses after we have seen all window functions */
2772  pstate->p_windowdefs,
2773  &qry->targetList);
2774 
2775  qry->rtable = pstate->p_rtable;
2776  qry->rteperminfos = pstate->p_rteperminfos;
2777  qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2778 
2779  qry->hasSubLinks = pstate->p_hasSubLinks;
2780  qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
2781  qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2782  qry->hasAggs = pstate->p_hasAggs;
2783 
2784  foreach(l, sstmt->lockingClause)
2785  {
2786  transformLockingClause(pstate, qry,
2787  (LockingClause *) lfirst(l), false);
2788  }
2789 
2790  assign_query_collations(pstate, qry);
2791 
2792  /* this must be done after collations, for reliable comparison of exprs */
2793  if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
2794  parseCheckAggregates(pstate, qry);
2795 
2796  return qry;
2797 }
2798 
2799 
2800 /*
2801  * transformDeclareCursorStmt -
2802  * transform a DECLARE CURSOR Statement
2803  *
2804  * DECLARE CURSOR is like other utility statements in that we emit it as a
2805  * CMD_UTILITY Query node; however, we must first transform the contained
2806  * query. We used to postpone that until execution, but it's really necessary
2807  * to do it during the normal parse analysis phase to ensure that side effects
2808  * of parser hooks happen at the expected time.
2809  */
2810 static Query *
2812 {
2813  Query *result;
2814  Query *query;
2815 
2816  if ((stmt->options & CURSOR_OPT_SCROLL) &&
2817  (stmt->options & CURSOR_OPT_NO_SCROLL))
2818  ereport(ERROR,
2819  (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
2820  /* translator: %s is a SQL keyword */
2821  errmsg("cannot specify both %s and %s",
2822  "SCROLL", "NO SCROLL")));
2823 
2824  if ((stmt->options & CURSOR_OPT_ASENSITIVE) &&
2825  (stmt->options & CURSOR_OPT_INSENSITIVE))
2826  ereport(ERROR,
2827  (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
2828  /* translator: %s is a SQL keyword */
2829  errmsg("cannot specify both %s and %s",
2830  "ASENSITIVE", "INSENSITIVE")));
2831 
2832  /* Transform contained query, not allowing SELECT INTO */
2833  query = transformStmt(pstate, stmt->query);
2834  stmt->query = (Node *) query;
2835 
2836  /* Grammar should not have allowed anything but SELECT */
2837  if (!IsA(query, Query) ||
2838  query->commandType != CMD_SELECT)
2839  elog(ERROR, "unexpected non-SELECT command in DECLARE CURSOR");
2840 
2841  /*
2842  * We also disallow data-modifying WITH in a cursor. (This could be
2843  * allowed, but the semantics of when the updates occur might be
2844  * surprising.)
2845  */
2846  if (query->hasModifyingCTE)
2847  ereport(ERROR,
2848  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2849  errmsg("DECLARE CURSOR must not contain data-modifying statements in WITH")));
2850 
2851  /* FOR UPDATE and WITH HOLD are not compatible */
2852  if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
2853  ereport(ERROR,
2854  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2855  /*------
2856  translator: %s is a SQL row locking clause such as FOR UPDATE */
2857  errmsg("DECLARE CURSOR WITH HOLD ... %s is not supported",
2859  linitial(query->rowMarks))->strength)),
2860  errdetail("Holdable cursors must be READ ONLY.")));
2861 
2862  /* FOR UPDATE and SCROLL are not compatible */
2863  if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
2864  ereport(ERROR,
2865  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2866  /*------
2867  translator: %s is a SQL row locking clause such as FOR UPDATE */
2868  errmsg("DECLARE SCROLL CURSOR ... %s is not supported",
2870  linitial(query->rowMarks))->strength)),
2871  errdetail("Scrollable cursors must be READ ONLY.")));
2872 
2873  /* FOR UPDATE and INSENSITIVE are not compatible */
2874  if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
2875  ereport(ERROR,
2876  (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
2877  /*------
2878  translator: %s is a SQL row locking clause such as FOR UPDATE */
2879  errmsg("DECLARE INSENSITIVE CURSOR ... %s is not valid",
2881  linitial(query->rowMarks))->strength)),
2882  errdetail("Insensitive cursors must be READ ONLY.")));
2883 
2884  /* represent the command as a utility Query */
2885  result = makeNode(Query);
2886  result->commandType = CMD_UTILITY;
2887  result->utilityStmt = (Node *) stmt;
2888 
2889  return result;
2890 }
2891 
2892 
2893 /*
2894  * transformExplainStmt -
2895  * transform an EXPLAIN Statement
2896  *
2897  * EXPLAIN is like other utility statements in that we emit it as a
2898  * CMD_UTILITY Query node; however, we must first transform the contained
2899  * query. We used to postpone that until execution, but it's really necessary
2900  * to do it during the normal parse analysis phase to ensure that side effects
2901  * of parser hooks happen at the expected time.
2902  */
2903 static Query *
2905 {
2906  Query *result;
2907 
2908  /* transform contained query, allowing SELECT INTO */
2909  stmt->query = (Node *) transformOptionalSelectInto(pstate, stmt->query);
2910 
2911  /* represent the command as a utility Query */
2912  result = makeNode(Query);
2913  result->commandType = CMD_UTILITY;
2914  result->utilityStmt = (Node *) stmt;
2915 
2916  return result;
2917 }
2918 
2919 
2920 /*
2921  * transformCreateTableAsStmt -
2922  * transform a CREATE TABLE AS, SELECT ... INTO, or CREATE MATERIALIZED VIEW
2923  * Statement
2924  *
2925  * As with DECLARE CURSOR and EXPLAIN, transform the contained statement now.
2926  */
2927 static Query *
2929 {
2930  Query *result;
2931  Query *query;
2932 
2933  /* transform contained query, not allowing SELECT INTO */
2934  query = transformStmt(pstate, stmt->query);
2935  stmt->query = (Node *) query;
2936 
2937  /* additional work needed for CREATE MATERIALIZED VIEW */
2938  if (stmt->objtype == OBJECT_MATVIEW)
2939  {
2940  /*
2941  * Prohibit a data-modifying CTE in the query used to create a
2942  * materialized view. It's not sufficiently clear what the user would
2943  * want to happen if the MV is refreshed or incrementally maintained.
2944  */
2945  if (query->hasModifyingCTE)
2946  ereport(ERROR,
2947  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2948  errmsg("materialized views must not use data-modifying statements in WITH")));
2949 
2950  /*
2951  * Check whether any temporary database objects are used in the
2952  * creation query. It would be hard to refresh data or incrementally
2953  * maintain it if a source disappeared.
2954  */
2955  if (isQueryUsingTempRelation(query))
2956  ereport(ERROR,
2957  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2958  errmsg("materialized views must not use temporary tables or views")));
2959 
2960  /*
2961  * A materialized view would either need to save parameters for use in
2962  * maintaining/loading the data or prohibit them entirely. The latter
2963  * seems safer and more sane.
2964  */
2965  if (query_contains_extern_params(query))
2966  ereport(ERROR,
2967  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2968  errmsg("materialized views may not be defined using bound parameters")));
2969 
2970  /*
2971  * For now, we disallow unlogged materialized views, because it seems
2972  * like a bad idea for them to just go to empty after a crash. (If we
2973  * could mark them as unpopulated, that would be better, but that
2974  * requires catalog changes which crash recovery can't presently
2975  * handle.)
2976  */
2977  if (stmt->into->rel->relpersistence == RELPERSISTENCE_UNLOGGED)
2978  ereport(ERROR,
2979  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2980  errmsg("materialized views cannot be unlogged")));
2981 
2982  /*
2983  * At runtime, we'll need a copy of the parsed-but-not-rewritten Query
2984  * for purposes of creating the view's ON SELECT rule. We stash that
2985  * in the IntoClause because that's where intorel_startup() can
2986  * conveniently get it from.
2987  */
2988  stmt->into->viewQuery = (Node *) copyObject(query);
2989  }
2990 
2991  /* represent the command as a utility Query */
2992  result = makeNode(Query);
2993  result->commandType = CMD_UTILITY;
2994  result->utilityStmt = (Node *) stmt;
2995 
2996  return result;
2997 }
2998 
2999 /*
3000  * transform a CallStmt
3001  */
3002 static Query *
3004 {
3005  List *targs;
3006  ListCell *lc;
3007  Node *node;
3008  FuncExpr *fexpr;
3009  HeapTuple proctup;
3010  Datum proargmodes;
3011  bool isNull;
3012  List *outargs = NIL;
3013  Query *result;
3014 
3015  /*
3016  * First, do standard parse analysis on the procedure call and its
3017  * arguments, allowing us to identify the called procedure.
3018  */
3019  targs = NIL;
3020  foreach(lc, stmt->funccall->args)
3021  {
3022  targs = lappend(targs, transformExpr(pstate,
3023  (Node *) lfirst(lc),
3025  }
3026 
3027  node = ParseFuncOrColumn(pstate,
3028  stmt->funccall->funcname,
3029  targs,
3030  pstate->p_last_srf,
3031  stmt->funccall,
3032  true,
3033  stmt->funccall->location);
3034 
3035  assign_expr_collations(pstate, node);
3036 
3037  fexpr = castNode(FuncExpr, node);
3038 
3039  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fexpr->funcid));
3040  if (!HeapTupleIsValid(proctup))
3041  elog(ERROR, "cache lookup failed for function %u", fexpr->funcid);
3042 
3043  /*
3044  * Expand the argument list to deal with named-argument notation and
3045  * default arguments. For ordinary FuncExprs this'd be done during
3046  * planning, but a CallStmt doesn't go through planning, and there seems
3047  * no good reason not to do it here.
3048  */
3049  fexpr->args = expand_function_arguments(fexpr->args,
3050  true,
3051  fexpr->funcresulttype,
3052  proctup);
3053 
3054  /* Fetch proargmodes; if it's null, there are no output args */
3055  proargmodes = SysCacheGetAttr(PROCOID, proctup,
3056  Anum_pg_proc_proargmodes,
3057  &isNull);
3058  if (!isNull)
3059  {
3060  /*
3061  * Split the list into input arguments in fexpr->args and output
3062  * arguments in stmt->outargs. INOUT arguments appear in both lists.
3063  */
3064  ArrayType *arr;
3065  int numargs;
3066  char *argmodes;
3067  List *inargs;
3068  int i;
3069 
3070  arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
3071  numargs = list_length(fexpr->args);
3072  if (ARR_NDIM(arr) != 1 ||
3073  ARR_DIMS(arr)[0] != numargs ||
3074  ARR_HASNULL(arr) ||
3075  ARR_ELEMTYPE(arr) != CHAROID)
3076  elog(ERROR, "proargmodes is not a 1-D char array of length %d or it contains nulls",
3077  numargs);
3078  argmodes = (char *) ARR_DATA_PTR(arr);
3079 
3080  inargs = NIL;
3081  i = 0;
3082  foreach(lc, fexpr->args)
3083  {
3084  Node *n = lfirst(lc);
3085 
3086  switch (argmodes[i])
3087  {
3088  case PROARGMODE_IN:
3089  case PROARGMODE_VARIADIC:
3090  inargs = lappend(inargs, n);
3091  break;
3092  case PROARGMODE_OUT:
3093  outargs = lappend(outargs, n);
3094  break;
3095  case PROARGMODE_INOUT:
3096  inargs = lappend(inargs, n);
3097  outargs = lappend(outargs, copyObject(n));
3098  break;
3099  default:
3100  /* note we don't support PROARGMODE_TABLE */
3101  elog(ERROR, "invalid argmode %c for procedure",
3102  argmodes[i]);
3103  break;
3104  }
3105  i++;
3106  }
3107  fexpr->args = inargs;
3108  }
3109 
3110  stmt->funcexpr = fexpr;
3111  stmt->outargs = outargs;
3112 
3113  ReleaseSysCache(proctup);
3114 
3115  /* represent the command as a utility Query */
3116  result = makeNode(Query);
3117  result->commandType = CMD_UTILITY;
3118  result->utilityStmt = (Node *) stmt;
3119 
3120  return result;
3121 }
3122 
3123 /*
3124  * Produce a string representation of a LockClauseStrength value.
3125  * This should only be applied to valid values (not LCS_NONE).
3126  */
3127 const char *
3129 {
3130  switch (strength)
3131  {
3132  case LCS_NONE:
3133  Assert(false);
3134  break;
3135  case LCS_FORKEYSHARE:
3136  return "FOR KEY SHARE";
3137  case LCS_FORSHARE:
3138  return "FOR SHARE";
3139  case LCS_FORNOKEYUPDATE:
3140  return "FOR NO KEY UPDATE";
3141  case LCS_FORUPDATE:
3142  return "FOR UPDATE";
3143  }
3144  return "FOR some"; /* shouldn't happen */
3145 }
3146 
3147 /*
3148  * Check for features that are not supported with FOR [KEY] UPDATE/SHARE.
3149  *
3150  * exported so planner can check again after rewriting, query pullup, etc
3151  */
3152 void
3154 {
3155  Assert(strength != LCS_NONE); /* else caller error */
3156 
3157  if (qry->setOperations)
3158  ereport(ERROR,
3159  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3160  /*------
3161  translator: %s is a SQL row locking clause such as FOR UPDATE */
3162  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
3163  LCS_asString(strength))));
3164  if (qry->distinctClause != NIL)
3165  ereport(ERROR,
3166  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3167  /*------
3168  translator: %s is a SQL row locking clause such as FOR UPDATE */
3169  errmsg("%s is not allowed with DISTINCT clause",
3170  LCS_asString(strength))));
3171  if (qry->groupClause != NIL || qry->groupingSets != NIL)
3172  ereport(ERROR,
3173  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3174  /*------
3175  translator: %s is a SQL row locking clause such as FOR UPDATE */
3176  errmsg("%s is not allowed with GROUP BY clause",
3177  LCS_asString(strength))));
3178  if (qry->havingQual != NULL)
3179  ereport(ERROR,
3180  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3181  /*------
3182  translator: %s is a SQL row locking clause such as FOR UPDATE */
3183  errmsg("%s is not allowed with HAVING clause",
3184  LCS_asString(strength))));
3185  if (qry->hasAggs)
3186  ereport(ERROR,
3187  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3188  /*------
3189  translator: %s is a SQL row locking clause such as FOR UPDATE */
3190  errmsg("%s is not allowed with aggregate functions",
3191  LCS_asString(strength))));
3192  if (qry->hasWindowFuncs)
3193  ereport(ERROR,
3194  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3195  /*------
3196  translator: %s is a SQL row locking clause such as FOR UPDATE */
3197  errmsg("%s is not allowed with window functions",
3198  LCS_asString(strength))));
3199  if (qry->hasTargetSRFs)
3200  ereport(ERROR,
3201  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3202  /*------
3203  translator: %s is a SQL row locking clause such as FOR UPDATE */
3204  errmsg("%s is not allowed with set-returning functions in the target list",
3205  LCS_asString(strength))));
3206 }
3207 
3208 /*
3209  * Transform a FOR [KEY] UPDATE/SHARE clause
3210  *
3211  * This basically involves replacing names by integer relids.
3212  *
3213  * NB: if you need to change this, see also markQueryForLocking()
3214  * in rewriteHandler.c, and isLockedRefname() in parse_relation.c.
3215  */
3216 static void
3218  bool pushedDown)
3219 {
3220  List *lockedRels = lc->lockedRels;
3221  ListCell *l;
3222  ListCell *rt;
3223  Index i;
3224  LockingClause *allrels;
3225 
3226  CheckSelectLocking(qry, lc->strength);
3227 
3228  /* make a clause we can pass down to subqueries to select all rels */
3229  allrels = makeNode(LockingClause);
3230  allrels->lockedRels = NIL; /* indicates all rels */
3231  allrels->strength = lc->strength;
3232  allrels->waitPolicy = lc->waitPolicy;
3233 
3234  if (lockedRels == NIL)
3235  {
3236  /*
3237  * Lock all regular tables used in query and its subqueries. We
3238  * examine inFromCl to exclude auto-added RTEs, particularly NEW/OLD
3239  * in rules. This is a bit of an abuse of a mostly-obsolete flag, but
3240  * it's convenient. We can't rely on the namespace mechanism that has
3241  * largely replaced inFromCl, since for example we need to lock
3242  * base-relation RTEs even if they are masked by upper joins.
3243  */
3244  i = 0;
3245  foreach(rt, qry->rtable)
3246  {
3247  RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3248 
3249  ++i;
3250  if (!rte->inFromCl)
3251  continue;
3252  switch (rte->rtekind)
3253  {
3254  case RTE_RELATION:
3255  {
3256  RTEPermissionInfo *perminfo;
3257 
3258  applyLockingClause(qry, i,
3259  lc->strength,
3260  lc->waitPolicy,
3261  pushedDown);
3262  perminfo = getRTEPermissionInfo(qry->rteperminfos, rte);
3263  perminfo->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3264  }
3265  break;
3266  case RTE_SUBQUERY:
3267  applyLockingClause(qry, i, lc->strength, lc->waitPolicy,
3268  pushedDown);
3269 
3270  /*
3271  * FOR UPDATE/SHARE of subquery is propagated to all of
3272  * subquery's rels, too. We could do this later (based on
3273  * the marking of the subquery RTE) but it is convenient
3274  * to have local knowledge in each query level about which
3275  * rels need to be opened with RowShareLock.
3276  */
3277  transformLockingClause(pstate, rte->subquery,
3278  allrels, true);
3279  break;
3280  default:
3281  /* ignore JOIN, SPECIAL, FUNCTION, VALUES, CTE RTEs */
3282  break;
3283  }
3284  }
3285  }
3286  else
3287  {
3288  /*
3289  * Lock just the named tables. As above, we allow locking any base
3290  * relation regardless of alias-visibility rules, so we need to
3291  * examine inFromCl to exclude OLD/NEW.
3292  */
3293  foreach(l, lockedRels)
3294  {
3295  RangeVar *thisrel = (RangeVar *) lfirst(l);
3296 
3297  /* For simplicity we insist on unqualified alias names here */
3298  if (thisrel->catalogname || thisrel->schemaname)
3299  ereport(ERROR,
3300  (errcode(ERRCODE_SYNTAX_ERROR),
3301  /*------
3302  translator: %s is a SQL row locking clause such as FOR UPDATE */
3303  errmsg("%s must specify unqualified relation names",
3304  LCS_asString(lc->strength)),
3305  parser_errposition(pstate, thisrel->location)));
3306 
3307  i = 0;
3308  foreach(rt, qry->rtable)
3309  {
3310  RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3311  char *rtename = rte->eref->aliasname;
3312 
3313  ++i;
3314  if (!rte->inFromCl)
3315  continue;
3316 
3317  /*
3318  * A join RTE without an alias is not visible as a relation
3319  * name and needs to be skipped (otherwise it might hide a
3320  * base relation with the same name), except if it has a USING
3321  * alias, which *is* visible.
3322  *
3323  * Subquery and values RTEs without aliases are never visible
3324  * as relation names and must always be skipped.
3325  */
3326  if (rte->alias == NULL)
3327  {
3328  if (rte->rtekind == RTE_JOIN)
3329  {
3330  if (rte->join_using_alias == NULL)
3331  continue;
3332  rtename = rte->join_using_alias->aliasname;
3333  }
3334  else if (rte->rtekind == RTE_SUBQUERY ||
3335  rte->rtekind == RTE_VALUES)
3336  continue;
3337  }
3338 
3339  if (strcmp(rtename, thisrel->relname) == 0)
3340  {
3341  switch (rte->rtekind)
3342  {
3343  case RTE_RELATION:
3344  {
3345  RTEPermissionInfo *perminfo;
3346 
3347  applyLockingClause(qry, i,
3348  lc->strength,
3349  lc->waitPolicy,
3350  pushedDown);
3351  perminfo = getRTEPermissionInfo(qry->rteperminfos, rte);
3352  perminfo->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3353  }
3354  break;
3355  case RTE_SUBQUERY:
3356  applyLockingClause(qry, i, lc->strength,
3357  lc->waitPolicy, pushedDown);
3358  /* see comment above */
3359  transformLockingClause(pstate, rte->subquery,
3360  allrels, true);
3361  break;
3362  case RTE_JOIN:
3363  ereport(ERROR,
3364  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3365  /*------
3366  translator: %s is a SQL row locking clause such as FOR UPDATE */
3367  errmsg("%s cannot be applied to a join",
3368  LCS_asString(lc->strength)),
3369  parser_errposition(pstate, thisrel->location)));
3370  break;
3371  case RTE_FUNCTION:
3372  ereport(ERROR,
3373  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3374  /*------
3375  translator: %s is a SQL row locking clause such as FOR UPDATE */
3376  errmsg("%s cannot be applied to a function",
3377  LCS_asString(lc->strength)),
3378  parser_errposition(pstate, thisrel->location)));
3379  break;
3380  case RTE_TABLEFUNC:
3381  ereport(ERROR,
3382  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3383  /*------
3384  translator: %s is a SQL row locking clause such as FOR UPDATE */
3385  errmsg("%s cannot be applied to a table function",
3386  LCS_asString(lc->strength)),
3387  parser_errposition(pstate, thisrel->location)));
3388  break;
3389  case RTE_VALUES:
3390  ereport(ERROR,
3391  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3392  /*------
3393  translator: %s is a SQL row locking clause such as FOR UPDATE */
3394  errmsg("%s cannot be applied to VALUES",
3395  LCS_asString(lc->strength)),
3396  parser_errposition(pstate, thisrel->location)));
3397  break;
3398  case RTE_CTE:
3399  ereport(ERROR,
3400  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3401  /*------
3402  translator: %s is a SQL row locking clause such as FOR UPDATE */
3403  errmsg("%s cannot be applied to a WITH query",
3404  LCS_asString(lc->strength)),
3405  parser_errposition(pstate, thisrel->location)));
3406  break;
3407  case RTE_NAMEDTUPLESTORE:
3408  ereport(ERROR,
3409  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3410  /*------
3411  translator: %s is a SQL row locking clause such as FOR UPDATE */
3412  errmsg("%s cannot be applied to a named tuplestore",
3413  LCS_asString(lc->strength)),
3414  parser_errposition(pstate, thisrel->location)));
3415  break;
3416 
3417  /* Shouldn't be possible to see RTE_RESULT here */
3418 
3419  default:
3420  elog(ERROR, "unrecognized RTE type: %d",
3421  (int) rte->rtekind);
3422  break;
3423  }
3424  break; /* out of foreach loop */
3425  }
3426  }
3427  if (rt == NULL)
3428  ereport(ERROR,
3430  /*------
3431  translator: %s is a SQL row locking clause such as FOR UPDATE */
3432  errmsg("relation \"%s\" in %s clause not found in FROM clause",
3433  thisrel->relname,
3434  LCS_asString(lc->strength)),
3435  parser_errposition(pstate, thisrel->location)));
3436  }
3437  }
3438 }
3439 
3440 /*
3441  * Record locking info for a single rangetable item
3442  */
3443 void
3445  LockClauseStrength strength, LockWaitPolicy waitPolicy,
3446  bool pushedDown)
3447 {
3448  RowMarkClause *rc;
3449 
3450  Assert(strength != LCS_NONE); /* else caller error */
3451 
3452  /* If it's an explicit clause, make sure hasForUpdate gets set */
3453  if (!pushedDown)
3454  qry->hasForUpdate = true;
3455 
3456  /* Check for pre-existing entry for same rtindex */
3457  if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
3458  {
3459  /*
3460  * If the same RTE is specified with more than one locking strength,
3461  * use the strongest. (Reasonable, since you can't take both a shared
3462  * and exclusive lock at the same time; it'll end up being exclusive
3463  * anyway.)
3464  *
3465  * Similarly, if the same RTE is specified with more than one lock
3466  * wait policy, consider that NOWAIT wins over SKIP LOCKED, which in
3467  * turn wins over waiting for the lock (the default). This is a bit
3468  * more debatable but raising an error doesn't seem helpful. (Consider
3469  * for instance SELECT FOR UPDATE NOWAIT from a view that internally
3470  * contains a plain FOR UPDATE spec.) Having NOWAIT win over SKIP
3471  * LOCKED is reasonable since the former throws an error in case of
3472  * coming across a locked tuple, which may be undesirable in some
3473  * cases but it seems better than silently returning inconsistent
3474  * results.
3475  *
3476  * And of course pushedDown becomes false if any clause is explicit.
3477  */
3478  rc->strength = Max(rc->strength, strength);
3479  rc->waitPolicy = Max(rc->waitPolicy, waitPolicy);
3480  rc->pushedDown &= pushedDown;
3481  return;
3482  }
3483 
3484  /* Make a new RowMarkClause */
3485  rc = makeNode(RowMarkClause);
3486  rc->rti = rtindex;
3487  rc->strength = strength;
3488  rc->waitPolicy = waitPolicy;
3489  rc->pushedDown = pushedDown;
3490  qry->rowMarks = lappend(qry->rowMarks, rc);
3491 }
3492 
3493 /*
3494  * Coverage testing for raw_expression_tree_walker().
3495  *
3496  * When enabled, we run raw_expression_tree_walker() over every DML statement
3497  * submitted to parse analysis. Without this provision, that function is only
3498  * applied in limited cases involving CTEs, and we don't really want to have
3499  * to test everything inside as well as outside a CTE.
3500  */
3501 #ifdef RAW_EXPRESSION_COVERAGE_TEST
3502 
3503 static bool
3504 test_raw_expression_coverage(Node *node, void *context)
3505 {
3506  if (node == NULL)
3507  return false;
3508  return raw_expression_tree_walker(node,
3509  test_raw_expression_coverage,
3510  context);
3511 }
3512 
3513 #endif /* RAW_EXPRESSION_COVERAGE_TEST */
void(* post_parse_analyze_hook_type)(ParseState *pstate, Query *query, JumbleState *jstate)
Definition: analyze.h:22
#define ARR_NDIM(a)
Definition: array.h:283
#define ARR_DATA_PTR(a)
Definition: array.h:315
#define DatumGetArrayTypeP(X)
Definition: array.h:254
#define ARR_ELEMTYPE(a)
Definition: array.h:285
#define ARR_DIMS(a)
Definition: array.h:287
#define ARR_HASNULL(a)
Definition: array.h:284
int16 AttrNumber
Definition: attnum.h:21
#define InvalidAttrNumber
Definition: attnum.h:23
void pgstat_report_query_id(uint64 query_id, bool force)
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:739
#define NameStr(name)
Definition: c.h:682
signed int int32
Definition: c.h:430
#define Max(x, y)
Definition: c.h:931
unsigned int Index
Definition: c.h:550
List * expand_function_arguments(List *args, bool include_out_arguments, Oid result_type, HeapTuple func_tuple)
Definition: clauses.c:3999
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1016
int errdetail(const char *fmt,...)
Definition: elog.c:1039
int errhint(const char *fmt,...)
Definition: elog.c:1153
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
const char * name
Definition: encode.c:561
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
long val
Definition: informix.c:664
int i
Definition: isn.c:73
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Assert(fmt[strlen(fmt) - 1] !='\n')
List * list_truncate(List *list, int new_size)
Definition: list.c:630
List * lappend(List *list, void *datum)
Definition: list.c:338
List * lappend_int(List *list, int datum)
Definition: list.c:356
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374
List * list_copy(const List *oldlist)
Definition: list.c:1572
List * list_delete_first(List *list)
Definition: list.c:942
void list_free(List *list)
Definition: list.c:1545
List * list_delete_last(List *list)
Definition: list.c:956
#define RowExclusiveLock
Definition: lockdefs.h:38
LockWaitPolicy
Definition: lockoptions.h:37
LockClauseStrength
Definition: lockoptions.h:22
@ LCS_FORUPDATE
Definition: lockoptions.h:27
@ LCS_NONE
Definition: lockoptions.h:23
@ LCS_FORSHARE
Definition: lockoptions.h:25
@ LCS_FORKEYSHARE
Definition: lockoptions.h:24
@ LCS_FORNOKEYUPDATE
Definition: lockoptions.h:26
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:387
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition: makefuncs.c:103
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:337
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:285
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
char * pstrdup(const char *in)
Definition: mcxt.c:1483
void * palloc0(Size size)
Definition: mcxt.c:1230
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:266
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:764
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1243
#define raw_expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:174
#define IsA(nodeptr, _type_)
Definition: nodes.h:168
#define copyObject(obj)
Definition: nodes.h:233
#define nodeTag(nodeptr)
Definition: nodes.h:122
@ ONCONFLICT_UPDATE
Definition: nodes.h:417
@ CMD_UTILITY
Definition: nodes.h:270
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_DELETE
Definition: nodes.h:268
@ CMD_UPDATE
Definition: nodes.h:266
@ CMD_SELECT
Definition: nodes.h:265
#define makeNode(_type_)
Definition: nodes.h:165
#define castNode(_type_, nodeptr)
Definition: nodes.h:186
@ JOIN_INNER
Definition: nodes.h:293
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:108
void parseCheckAggregates(ParseState *pstate, Query *qry)
Definition: parse_agg.c:1062
List * transformWindowDefinitions(ParseState *pstate, List *windowdefs, List **targetlist)
List * transformDistinctOnClause(ParseState *pstate, List *distinctlist, List **targetlist, List *sortClause)
Node * transformLimitClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName, LimitOption limitOption)
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
void transformFromClause(ParseState *pstate, List *frmList)
Definition: parse_clause.c:113
List * transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
List * transformDistinctClause(ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
void transformOnConflictArbiter(ParseState *pstate, OnConflictClause *onConflictClause, List **arbiterExpr, Node **arbiterWhere, Oid *constraint)
int setTargetTable(ParseState *pstate, RangeVar *relation, bool inh, bool alsoSource, AclMode requiredPerms)
Definition: parse_clause.c:179
Node * coerce_to_common_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *context)
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
int32 select_common_typmod(ParseState *pstate, List *exprs, Oid common_type)
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
void assign_list_collations(ParseState *pstate, List *exprs)
Oid select_common_collation(ParseState *pstate, List *exprs, bool none_ok)
void assign_query_collations(ParseState *pstate, Query *query)
void assign_expr_collations(ParseState *pstate, Node *expr)
void analyzeCTETargetList(ParseState *pstate, CommonTableExpr *cte, List *tlist)
Definition: parse_cte.c:552
List * transformWithClause(ParseState *pstate, WithClause *withClause)
Definition: parse_cte.c:109
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:92
Node * ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs, Node *last_srf, FuncCall *fn, bool proc_call, int location)
Definition: parse_func.c:90
Query * transformMergeStmt(ParseState *pstate, MergeStmt *stmt)
Definition: parse_merge.c:96
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:76
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
@ EXPR_KIND_VALUES
Definition: parse_node.h:65
@ EXPR_KIND_ORDER_BY
Definition: parse_node.h:60
@ EXPR_KIND_OFFSET
Definition: parse_node.h:63
@ EXPR_KIND_HAVING
Definition: parse_node.h:47
@ EXPR_KIND_INSERT_TARGET
Definition: parse_node.h:55
@ EXPR_KIND_LIMIT
Definition: parse_node.h:62
@ EXPR_KIND_WHERE
Definition: parse_node.h:46
@ EXPR_KIND_UPDATE_TARGET
Definition: parse_node.h:57
@ EXPR_KIND_SELECT_TARGET
Definition: parse_node.h:54
@ EXPR_KIND_RETURNING
Definition: parse_node.h:64
@ EXPR_KIND_NONE
Definition: parse_node.h:40
@ EXPR_KIND_CALL_ARGUMENT
Definition: parse_node.h:80
@ EXPR_KIND_GROUP_BY
Definition: parse_node.h:59
@ EXPR_KIND_UPDATE_SOURCE
Definition: parse_node.h:56
@ EXPR_KIND_VALUES_SINGLE
Definition: parse_node.h:66
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:192
void check_variable_parameters(ParseState *pstate, Query *query)
Definition: parse_param.c:268
bool query_contains_extern_params(Query *query)
Definition: parse_param.c:330
void setup_parse_variable_parameters(ParseState *pstate, Oid **paramTypes, int *numParams)
Definition: parse_param.c:83
void setup_parse_fixed_parameters(ParseState *pstate, const Oid *paramTypes, int numParams)
Definition: parse_param.c:67
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
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)
RowMarkClause * get_parse_rowmark(Query *qry, Index rtindex)
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
ParseNamespaceItem * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
ParseNamespaceItem * addRangeTableEntryForValues(ParseState *pstate, List *exprs, List *coltypes, List *coltypmods, List *colcollations, Alias *alias, bool lateral, bool inFromCl)
List * expandNSItemAttrs(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, bool require_col_privs, int location)
List * expandNSItemVars(ParseNamespaceItem *nsitem, int sublevels_up, int location, List **colnames)
bool isQueryUsingTempRelation(Query *query)
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
List * transformTargetList(ParseState *pstate, List *targetlist, ParseExprKind exprKind)
Definition: parse_target.c:122
Expr * transformAssignedExpr(ParseState *pstate, Expr *expr, ParseExprKind exprKind, const char *colname, int attrno, List *indirection, int location)
Definition: parse_target.c:453
void updateTargetListEntry(ParseState *pstate, TargetEntry *tle, char *colname, int attrno, List *indirection, int location)
Definition: parse_target.c:620
void resolveTargetListUnknowns(ParseState *pstate, List *targetlist)
Definition: parse_target.c:289
void markTargetListOrigins(ParseState *pstate, List *targetlist)
Definition: parse_target.c:319
List * checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
Node * transformAssignmentIndirection(ParseState *pstate, Node *basenode, const char *targetName, bool targetIsSubscripting, Oid targetTypeId, int32 targetTypMod, Oid targetCollation, List *indirection, ListCell *indirection_cell, Node *rhs, CoercionContext ccontext, int location)
Definition: parse_target.c:684
List * transformExpressionList(ParseState *pstate, List *exprlist, ParseExprKind exprKind, bool allowDefault)
Definition: parse_target.c:221
#define ISCOMPLEX(typeid)
Definition: parse_type.h:58
#define CURSOR_OPT_INSENSITIVE
Definition: parsenodes.h:2927
#define CURSOR_OPT_SCROLL
Definition: parsenodes.h:2925
#define ACL_DELETE
Definition: parsenodes.h:86
@ SETOP_INTERSECT
Definition: parsenodes.h:1746
@ SETOP_UNION
Definition: parsenodes.h:1745
@ SETOP_NONE
Definition: parsenodes.h:1744
uint64 AclMode
Definition: parsenodes.h:81
#define ACL_INSERT
Definition: parsenodes.h:83
#define ACL_UPDATE
Definition: parsenodes.h:85
@ QSRC_ORIGINAL
Definition: parsenodes.h:43
@ RTE_JOIN
Definition: parsenodes.h:984
@ RTE_CTE
Definition: parsenodes.h:988
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:989
@ RTE_VALUES
Definition: parsenodes.h:987
@ RTE_SUBQUERY
Definition: parsenodes.h:983
@ RTE_FUNCTION
Definition: parsenodes.h:985
@ RTE_TABLEFUNC
Definition: parsenodes.h:986
@ RTE_RELATION
Definition: parsenodes.h:982
@ OBJECT_MATVIEW
Definition: parsenodes.h:1911
@ OBJECT_TABLE
Definition: parsenodes.h:1929
#define CURSOR_OPT_HOLD
Definition: parsenodes.h:2929
#define ACL_SELECT_FOR_UPDATE
Definition: parsenodes.h:102
#define CURSOR_OPT_ASENSITIVE
Definition: parsenodes.h:2928
#define CURSOR_OPT_NO_SCROLL
Definition: parsenodes.h:2926
static OnConflictExpr * transformOnConflictClause(ParseState *pstate, OnConflictClause *onConflictClause)
Definition: analyze.c:1067
Query * parse_analyze_withcb(RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: analyze.c:187
List * transformUpdateTargetList(ParseState *pstate, List *origTlist)
Definition: analyze.c:2432
Query * parse_sub_analyze(Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
Definition: analyze.c:223
static Query * transformOptionalSelectInto(ParseState *pstate, Node *parseTree)
Definition: analyze.c:274
static void transformLockingClause(ParseState *pstate, Query *qry, LockingClause *lc, bool pushedDown)
Definition: analyze.c:3217
static Query * transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
Definition: analyze.c:472
List * transformInsertRow(ParseState *pstate, List *exprlist, List *stmtcols, List *icolumns, List *attrnos, bool strip_indirection)
Definition: analyze.c:968
void CheckSelectLocking(Query *qry, LockClauseStrength strength)
Definition: analyze.c:3153
static Node * transformSetOperationTree(ParseState *pstate, SelectStmt *stmt, bool isTopLevel, List **targetlist)
Definition: analyze.c:1951
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:250
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:430
void applyLockingClause(Query *qry, Index rtindex, LockClauseStrength strength, LockWaitPolicy waitPolicy, bool pushedDown)
Definition: analyze.c:3444
static void determineRecursiveColTypes(ParseState *pstate, Node *larg, List *nrtargetlist)
Definition: analyze.c:2282
static Query * transformReturnStmt(ParseState *pstate, ReturnStmt *stmt)
Definition: analyze.c:2336
static Query * transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt)
Definition: analyze.c:2562
static Query * transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
Definition: analyze.c:2928
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:59
static Query * transformCallStmt(ParseState *pstate, CallStmt *stmt)
Definition: analyze.c:3003
static List * transformReturningList(ParseState *pstate, List *returningList)
Definition: analyze.c:2504
static Query * transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1648
List * BuildOnConflictExcludedTargetlist(Relation targetrel, Index exclRelIndex)
Definition: analyze.c:1174
SortGroupClause * makeSortGroupClauseForSetOp(Oid rescoltype, bool require_hash)
Definition: analyze.c:1904
const char * LCS_asString(LockClauseStrength strength)
Definition: analyze.c:3128
static Query * transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
Definition: analyze.c:2367
static Query * transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1286
static Query * transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
Definition: analyze.c:2904
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:313
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:146
static int count_rowexpr_columns(ParseState *pstate, Node *expr)
Definition: analyze.c:1244
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:106
static Query * transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
Definition: analyze.c:2811
static Query * transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
Definition: analyze.c:543
static Query * transformValuesClause(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1429
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
int16 attnum
Definition: pg_attribute.h:83
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define lfirst(lc)
Definition: pg_list.h:170
#define llast(l)
Definition: pg_list.h:196
#define lfirst_node(type, lc)
Definition: pg_list.h:174
static int list_length(const List *l)
Definition: pg_list.h:150
#define linitial_node(type, l)
Definition: pg_list.h:179
#define NIL
Definition: pg_list.h:66
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:465
#define lfirst_int(lc)
Definition: pg_list.h:171
#define list_make1(x1)
Definition: pg_list.h:210
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:510
static ListCell * list_head(const List *l)
Definition: pg_list.h:126
#define linitial(l)
Definition: pg_list.h:176
#define forfour(cell1, list1, cell2, list2, cell3, list3, cell4, list4)
Definition: pg_list.h:522
static void * list_nth(const List *list, int n)
Definition: pg_list.h:297
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:341
#define lfirst_oid(lc)
Definition: pg_list.h:172
#define list_make2(x1, x2)
Definition: pg_list.h:212
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:77
#define snprintf
Definition: port.h:238
void check_stack_depth(void)
Definition: postgres.c:3440
uintptr_t Datum
Definition: postgres.h:412
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:588
@ COERCION_PLPGSQL
Definition: primnodes.h:568
JumbleState * JumbleQuery(Query *query, const char *querytext)
Definition: queryjumble.c:102
static bool IsQueryIdEnabled(void)
Definition: queryjumble.h:77
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:507
#define RelationGetRelationName(relation)
Definition: rel.h:535
char * aliasname
Definition: primnodes.h:42
FuncCall * funccall
Definition: parsenodes.h:3146
FuncExpr * funcexpr
Definition: parsenodes.h:3147
List * outargs
Definition: parsenodes.h:3148
int location
Definition: parsenodes.h:262
List * fields
Definition: parsenodes.h:261
IntoClause * into
Definition: parsenodes.h:3526
ObjectType objtype
Definition: parsenodes.h:3527
WithClause * withClause
Definition: parsenodes.h:1697
Node * whereClause
Definition: parsenodes.h:1695
RangeVar * relation
Definition: parsenodes.h:1693
List * usingClause
Definition: parsenodes.h:1694
List * returningList
Definition: parsenodes.h:1696
Node * query
Definition: parsenodes.h:3505
List * newvals
Definition: primnodes.h:979
int location
Definition: parsenodes.h:403
List * funcname
Definition: parsenodes.h:393
List * args
Definition: parsenodes.h:394
Oid funcid
Definition: primnodes.h:598
List * args
Definition: primnodes.h:606
Oid funcresulttype
Definition: primnodes.h:599
OnConflictClause * onConflictClause
Definition: parsenodes.h:1680
Node * selectStmt
Definition: parsenodes.h:1679
OverridingKind override
Definition: parsenodes.h:1683
WithClause * withClause
Definition: parsenodes.h:1682
RangeVar * relation
Definition: parsenodes.h:1677
List * cols
Definition: parsenodes.h:1678
Node * viewQuery
Definition: primnodes.h:134
RangeVar * rel
Definition: primnodes.h:128
Definition: pg_list.h:52
List * lockedRels
Definition: parsenodes.h:798
LockClauseStrength strength
Definition: parsenodes.h:799
LockWaitPolicy waitPolicy
Definition: parsenodes.h:800
Definition: nodes.h:118
OnConflictAction action
Definition: parsenodes.h:1517
List * arbiterElems
Definition: primnodes.h:1683
OnConflictAction action
Definition: primnodes.h:1680
List * onConflictSet
Definition: primnodes.h:1689
List * exclRelTlist
Definition: primnodes.h:1692
Node * onConflictWhere
Definition: primnodes.h:1690
Node * arbiterWhere
Definition: primnodes.h:1685
SelectStmt * val
Definition: parsenodes.h:1861
List * indirection
Definition: parsenodes.h:1859
AttrNumber p_varattno
Definition: parse_node.h:313
AttrNumber p_varattnosyn
Definition: parse_node.h:318
RangeTblEntry * p_rte
Definition: parse_node.h:278
RTEPermissionInfo * p_perminfo
Definition: parse_node.h:280
bool p_hasTargetSRFs
Definition: parse_node.h:216
List * p_ctenamespace
Definition: parse_node.h:195
bool p_hasWindowFuncs
Definition: parse_node.h:215
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:199
ParseExprKind p_expr_kind
Definition: parse_node.h:202
bool p_locked_from_parent
Definition: parse_node.h:206
List * p_namespace
Definition: parse_node.h:192
bool p_is_insert
Definition: parse_node.h:200
QueryEnvironment * p_queryEnv
Definition: parse_node.h:211
const char * p_sourcetext
Definition: parse_node.h:185
List * p_windowdefs
Definition: parse_node.h:201
bool p_resolve_unknowns
Definition: parse_node.h:208
int p_next_resno
Definition: parse_node.h:203
bool p_hasModifyingCTE
Definition: parse_node.h:218
List * p_rteperminfos
Definition: parse_node.h:187
List * p_joinexprs
Definition: parse_node.h:189
Relation p_target_relation
Definition: parse_node.h:198
CommonTableExpr * p_parent_cte
Definition: parse_node.h:197
bool p_hasSubLinks
Definition: parse_node.h:217
Node * p_last_srf
Definition: parse_node.h:220
List * p_joinlist
Definition: parse_node.h:190
List * p_locking_clause
Definition: parse_node.h:205
List * p_rtable
Definition: parse_node.h:186
bool p_hasAggs
Definition: parse_node.h:214
List * rowMarks
Definition: parsenodes.h:189
bool hasWindowFuncs
Definition: parsenodes.h:142
bool groupDistinct
Definition: parsenodes.h:173
Node * limitCount
Definition: parsenodes.h:186
int stmt_location
Definition: parsenodes.h:206
FromExpr * jointree
Definition: parsenodes.h:158
List * returningList
Definition: parsenodes.h:170
List * rteperminfos
Definition: parsenodes.h:156
Node * setOperations
Definition: parsenodes.h:191
List * cteList
Definition: parsenodes.h:153
bool hasTargetSRFs
Definition: parsenodes.h:143
List * groupClause
Definition: parsenodes.h:172
int stmt_len
Definition: parsenodes.h:207
bool canSetTag
Definition: parsenodes.h:134
Node * havingQual
Definition: parsenodes.h:177
List * rtable
Definition: parsenodes.h:155
Node * limitOffset
Definition: parsenodes.h:185
QuerySource querySource
Definition: parsenodes.h:126
int resultRelation
Definition: parsenodes.h:138
bool hasAggs
Definition: parsenodes.h:141
CmdType commandType
Definition: parsenodes.h:124
bool hasDistinctOn
Definition: parsenodes.h:145
bool hasRecursive
Definition: parsenodes.h:146
LimitOption limitOption
Definition: parsenodes.h:187
bool hasModifyingCTE
Definition: parsenodes.h:147
Node * utilityStmt
Definition: parsenodes.h:136
List * windowClause
Definition: parsenodes.h:179
List * targetList
Definition: parsenodes.h:164
bool hasForUpdate
Definition: parsenodes.h:148
bool hasSubLinks
Definition: parsenodes.h:144
List * groupingSets
Definition: parsenodes.h:175
bool isReturn
Definition: parsenodes.h:151
List * distinctClause
Definition: parsenodes.h:181
List * sortClause
Definition: parsenodes.h:183
OverridingKind override
Definition: parsenodes.h:166
AclMode requiredPerms
Definition: parsenodes.h:1208
Bitmapset * updatedCols
Definition: parsenodes.h:1212
Alias * join_using_alias
Definition: parsenodes.h:1090
Query * subquery
Definition: parsenodes.h:1041
Alias * eref
Definition: parsenodes.h:1152
Alias * alias
Definition: parsenodes.h:1151
RTEKind rtekind
Definition: parsenodes.h:1001
int location
Definition: primnodes.h:89
char * relname
Definition: primnodes.h:77
bool inh
Definition: primnodes.h:80
char relpersistence
Definition: primnodes.h:83
char * schemaname
Definition: primnodes.h:74
int stmt_len
Definition: parsenodes.h:1659
Node * stmt
Definition: parsenodes.h:1657
int stmt_location
Definition: parsenodes.h:1658
TupleDesc rd_att
Definition: rel.h:111
Form_pg_class rd_rel
Definition: rel.h:110
int location
Definition: parsenodes.h:487
List * indirection
Definition: parsenodes.h:485
char * name
Definition: parsenodes.h:484
Node * returnval
Definition: parsenodes.h:1843
LockClauseStrength strength
Definition: parsenodes.h:1473
LockWaitPolicy waitPolicy
Definition: parsenodes.h:1474
LimitOption limitOption
Definition: parsenodes.h:1785
List * sortClause
Definition: parsenodes.h:1782
List * targetList
Definition: parsenodes.h:1760
IntoClause * intoClause
Definition: parsenodes.h:1759
Node * limitOffset
Definition: parsenodes.h:1783
bool groupDistinct
Definition: parsenodes.h:1764
List * fromClause
Definition: parsenodes.h:1761
List * groupClause
Definition: parsenodes.h:1763
Node * havingClause
Definition: parsenodes.h:1765
List * lockingClause
Definition: parsenodes.h:1786
Node * limitCount
Definition: parsenodes.h:1784
List * windowClause
Definition: parsenodes.h:1766
List * distinctClause
Definition: parsenodes.h:1757
List * valuesLists
Definition: parsenodes.h:1776
struct SelectStmt * larg
Definition: parsenodes.h:1794
struct SelectStmt * rarg
Definition: parsenodes.h:1795
Node * whereClause
Definition: parsenodes.h:1762
SetOperation op
Definition: parsenodes.h:1792
WithClause * withClause
Definition: parsenodes.h:1787
List * colCollations
Definition: parsenodes.h:1831
SetOperation op
Definition: parsenodes.h:1822
int32 typeMod
Definition: primnodes.h:1442
Index tleSortGroupRef
Definition: parsenodes.h:1346
Definition: value.h:64
Expr * refassgnexpr
Definition: primnodes.h:554
Expr * expr
Definition: primnodes.h:1555
char * resname
Definition: primnodes.h:1557
AttrNumber resno
Definition: primnodes.h:1556
bool resjunk
Definition: primnodes.h:1562
List * targetList
Definition: parsenodes.h:1708
List * returningList
Definition: parsenodes.h:1711
List * fromClause
Definition: parsenodes.h:1710
Node * whereClause
Definition: parsenodes.h:1709
RangeVar * relation
Definition: parsenodes.h:1707
WithClause * withClause
Definition: parsenodes.h:1712
Definition: primnodes.h:205
Oid vartype
Definition: primnodes.h:220
AttrNumber varattno
Definition: primnodes.h:217
int varno
Definition: primnodes.h:212
Index varlevelsup
Definition: primnodes.h:230
int location
Definition: primnodes.h:243
bool recursive
Definition: parsenodes.h:1489
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434
@ PROCOID
Definition: syscache.h:79
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
String * makeString(char *str)
Definition: value.c:63
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:431
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:499