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