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