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