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