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