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  qry->onConflict = transformOnConflictClause(pstate,
846  stmt->onConflictClause);
847 
848  /*
849  * If we have a RETURNING clause, we need to add the target relation to
850  * the query namespace before processing it, so that Var references in
851  * RETURNING will work. Also, remove any namespace entries added in a
852  * sub-SELECT or VALUES list.
853  */
854  if (stmt->returningList)
855  {
856  pstate->p_namespace = NIL;
857  addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
858  false, true, true);
859  qry->returningList = transformReturningList(pstate,
860  stmt->returningList);
861  }
862 
863  /* done building the range table and jointree */
864  qry->rtable = pstate->p_rtable;
865  qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
866 
867  qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
868  qry->hasSubLinks = pstate->p_hasSubLinks;
869 
870  assign_query_collations(pstate, qry);
871 
872  return qry;
873 }
874 
875 /*
876  * Prepare an INSERT row for assignment to the target table.
877  *
878  * exprlist: transformed expressions for source values; these might come from
879  * a VALUES row, or be Vars referencing a sub-SELECT or VALUES RTE output.
880  * stmtcols: original target-columns spec for INSERT (we just test for NIL)
881  * icolumns: effective target-columns spec (list of ResTarget)
882  * attrnos: integer column numbers (must be same length as icolumns)
883  * strip_indirection: if true, remove any field/array assignment nodes
884  */
885 static List *
886 transformInsertRow(ParseState *pstate, List *exprlist,
887  List *stmtcols, List *icolumns, List *attrnos,
888  bool strip_indirection)
889 {
890  List *result;
891  ListCell *lc;
892  ListCell *icols;
893  ListCell *attnos;
894 
895  /*
896  * Check length of expr list. It must not have more expressions than
897  * there are target columns. We allow fewer, but only if no explicit
898  * columns list was given (the remaining columns are implicitly
899  * defaulted). Note we must check this *after* transformation because
900  * that could expand '*' into multiple items.
901  */
902  if (list_length(exprlist) > list_length(icolumns))
903  ereport(ERROR,
904  (errcode(ERRCODE_SYNTAX_ERROR),
905  errmsg("INSERT has more expressions than target columns"),
906  parser_errposition(pstate,
907  exprLocation(list_nth(exprlist,
908  list_length(icolumns))))));
909  if (stmtcols != NIL &&
910  list_length(exprlist) < list_length(icolumns))
911  {
912  /*
913  * We can get here for cases like INSERT ... SELECT (a,b,c) FROM ...
914  * where the user accidentally created a RowExpr instead of separate
915  * columns. Add a suitable hint if that seems to be the problem,
916  * because the main error message is quite misleading for this case.
917  * (If there's no stmtcols, you'll get something about data type
918  * mismatch, which is less misleading so we don't worry about giving a
919  * hint in that case.)
920  */
921  ereport(ERROR,
922  (errcode(ERRCODE_SYNTAX_ERROR),
923  errmsg("INSERT has more target columns than expressions"),
924  ((list_length(exprlist) == 1 &&
925  count_rowexpr_columns(pstate, linitial(exprlist)) ==
926  list_length(icolumns)) ?
927  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),
928  parser_errposition(pstate,
929  exprLocation(list_nth(icolumns,
930  list_length(exprlist))))));
931  }
932 
933  /*
934  * Prepare columns for assignment to target table.
935  */
936  result = NIL;
937  icols = list_head(icolumns);
938  attnos = list_head(attrnos);
939  foreach(lc, exprlist)
940  {
941  Expr *expr = (Expr *) lfirst(lc);
942  ResTarget *col;
943 
944  col = castNode(ResTarget, lfirst(icols));
945 
946  expr = transformAssignedExpr(pstate, expr,
948  col->name,
949  lfirst_int(attnos),
950  col->indirection,
951  col->location);
952 
953  if (strip_indirection)
954  {
955  while (expr)
956  {
957  if (IsA(expr, FieldStore))
958  {
959  FieldStore *fstore = (FieldStore *) expr;
960 
961  expr = (Expr *) linitial(fstore->newvals);
962  }
963  else if (IsA(expr, ArrayRef))
964  {
965  ArrayRef *aref = (ArrayRef *) expr;
966 
967  if (aref->refassgnexpr == NULL)
968  break;
969  expr = aref->refassgnexpr;
970  }
971  else
972  break;
973  }
974  }
975 
976  result = lappend(result, expr);
977 
978  icols = lnext(icols);
979  attnos = lnext(attnos);
980  }
981 
982  return result;
983 }
984 
985 /*
986  * transformOnConflictClause -
987  * transforms an OnConflictClause in an INSERT
988  */
989 static OnConflictExpr *
991  OnConflictClause *onConflictClause)
992 {
993  List *arbiterElems;
994  Node *arbiterWhere;
995  Oid arbiterConstraint;
996  List *onConflictSet = NIL;
997  Node *onConflictWhere = NULL;
998  RangeTblEntry *exclRte = NULL;
999  int exclRelIndex = 0;
1000  List *exclRelTlist = NIL;
1002 
1003  /* Process the arbiter clause, ON CONFLICT ON (...) */
1004  transformOnConflictArbiter(pstate, onConflictClause, &arbiterElems,
1005  &arbiterWhere, &arbiterConstraint);
1006 
1007  /* Process DO UPDATE */
1008  if (onConflictClause->action == ONCONFLICT_UPDATE)
1009  {
1010  Relation targetrel = pstate->p_target_relation;
1011  Var *var;
1012  TargetEntry *te;
1013  int attno;
1014 
1015  /*
1016  * All INSERT expressions have been parsed, get ready for potentially
1017  * existing SET statements that need to be processed like an UPDATE.
1018  */
1019  pstate->p_is_insert = false;
1020 
1021  /*
1022  * Add range table entry for the EXCLUDED pseudo relation; relkind is
1023  * set to composite to signal that we're not dealing with an actual
1024  * relation.
1025  */
1026  exclRte = addRangeTableEntryForRelation(pstate,
1027  targetrel,
1028  makeAlias("excluded", NIL),
1029  false, false);
1030  exclRte->relkind = RELKIND_COMPOSITE_TYPE;
1031  exclRelIndex = list_length(pstate->p_rtable);
1032 
1033  /*
1034  * Build a targetlist representing the columns of the EXCLUDED pseudo
1035  * relation. Have to be careful to use resnos that correspond to
1036  * attnos of the underlying relation.
1037  */
1038  for (attno = 0; attno < targetrel->rd_rel->relnatts; attno++)
1039  {
1040  Form_pg_attribute attr = targetrel->rd_att->attrs[attno];
1041  char *name;
1042 
1043  if (attr->attisdropped)
1044  {
1045  /*
1046  * can't use atttypid here, but it doesn't really matter what
1047  * type the Const claims to be.
1048  */
1049  var = (Var *) makeNullConst(INT4OID, -1, InvalidOid);
1050  name = "";
1051  }
1052  else
1053  {
1054  var = makeVar(exclRelIndex, attno + 1,
1055  attr->atttypid, attr->atttypmod,
1056  attr->attcollation,
1057  0);
1058  name = pstrdup(NameStr(attr->attname));
1059  }
1060 
1061  te = makeTargetEntry((Expr *) var,
1062  attno + 1,
1063  name,
1064  false);
1065 
1066  /* don't require select access yet */
1067  exclRelTlist = lappend(exclRelTlist, te);
1068  }
1069 
1070  /*
1071  * Add a whole-row-Var entry to support references to "EXCLUDED.*".
1072  * Like the other entries in exclRelTlist, its resno must match the
1073  * Var's varattno, else the wrong things happen while resolving
1074  * references in setrefs.c. This is against normal conventions for
1075  * targetlists, but it's okay since we don't use this as a real tlist.
1076  */
1077  var = makeVar(exclRelIndex, InvalidAttrNumber,
1078  targetrel->rd_rel->reltype,
1079  -1, InvalidOid, 0);
1080  te = makeTargetEntry((Expr *) var, InvalidAttrNumber, NULL, true);
1081  exclRelTlist = lappend(exclRelTlist, te);
1082 
1083  /*
1084  * Add EXCLUDED and the target RTE to the namespace, so that they can
1085  * be used in the UPDATE statement.
1086  */
1087  addRTEtoQuery(pstate, exclRte, false, true, true);
1088  addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
1089  false, true, true);
1090 
1091  onConflictSet =
1092  transformUpdateTargetList(pstate, onConflictClause->targetList);
1093 
1094  onConflictWhere = transformWhereClause(pstate,
1095  onConflictClause->whereClause,
1096  EXPR_KIND_WHERE, "WHERE");
1097  }
1098 
1099  /* Finally, build ON CONFLICT DO [NOTHING | UPDATE] expression */
1100  result = makeNode(OnConflictExpr);
1101 
1102  result->action = onConflictClause->action;
1103  result->arbiterElems = arbiterElems;
1104  result->arbiterWhere = arbiterWhere;
1105  result->constraint = arbiterConstraint;
1106  result->onConflictSet = onConflictSet;
1107  result->onConflictWhere = onConflictWhere;
1108  result->exclRelIndex = exclRelIndex;
1109  result->exclRelTlist = exclRelTlist;
1110 
1111  return result;
1112 }
1113 
1114 
1115 /*
1116  * count_rowexpr_columns -
1117  * get number of columns contained in a ROW() expression;
1118  * return -1 if expression isn't a RowExpr or a Var referencing one.
1119  *
1120  * This is currently used only for hint purposes, so we aren't terribly
1121  * tense about recognizing all possible cases. The Var case is interesting
1122  * because that's what we'll get in the INSERT ... SELECT (...) case.
1123  */
1124 static int
1126 {
1127  if (expr == NULL)
1128  return -1;
1129  if (IsA(expr, RowExpr))
1130  return list_length(((RowExpr *) expr)->args);
1131  if (IsA(expr, Var))
1132  {
1133  Var *var = (Var *) expr;
1134  AttrNumber attnum = var->varattno;
1135 
1136  if (attnum > 0 && var->vartype == RECORDOID)
1137  {
1138  RangeTblEntry *rte;
1139 
1140  rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
1141  if (rte->rtekind == RTE_SUBQUERY)
1142  {
1143  /* Subselect-in-FROM: examine sub-select's output expr */
1145  attnum);
1146 
1147  if (ste == NULL || ste->resjunk)
1148  return -1;
1149  expr = (Node *) ste->expr;
1150  if (IsA(expr, RowExpr))
1151  return list_length(((RowExpr *) expr)->args);
1152  }
1153  }
1154  }
1155  return -1;
1156 }
1157 
1158 
1159 /*
1160  * transformSelectStmt -
1161  * transforms a Select Statement
1162  *
1163  * Note: this covers only cases with no set operations and no VALUES lists;
1164  * see below for the other cases.
1165  */
1166 static Query *
1168 {
1169  Query *qry = makeNode(Query);
1170  Node *qual;
1171  ListCell *l;
1172 
1173  qry->commandType = CMD_SELECT;
1174 
1175  /* process the WITH clause independently of all else */
1176  if (stmt->withClause)
1177  {
1178  qry->hasRecursive = stmt->withClause->recursive;
1179  qry->cteList = transformWithClause(pstate, stmt->withClause);
1180  qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1181  }
1182 
1183  /* Complain if we get called from someplace where INTO is not allowed */
1184  if (stmt->intoClause)
1185  ereport(ERROR,
1186  (errcode(ERRCODE_SYNTAX_ERROR),
1187  errmsg("SELECT ... INTO is not allowed here"),
1188  parser_errposition(pstate,
1189  exprLocation((Node *) stmt->intoClause))));
1190 
1191  /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
1192  pstate->p_locking_clause = stmt->lockingClause;
1193 
1194  /* make WINDOW info available for window functions, too */
1195  pstate->p_windowdefs = stmt->windowClause;
1196 
1197  /* process the FROM clause */
1198  transformFromClause(pstate, stmt->fromClause);
1199 
1200  /* transform targetlist */
1201  qry->targetList = transformTargetList(pstate, stmt->targetList,
1203 
1204  /* mark column origins */
1205  markTargetListOrigins(pstate, qry->targetList);
1206 
1207  /* transform WHERE */
1208  qual = transformWhereClause(pstate, stmt->whereClause,
1209  EXPR_KIND_WHERE, "WHERE");
1210 
1211  /* initial processing of HAVING clause is much like WHERE clause */
1212  qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
1213  EXPR_KIND_HAVING, "HAVING");
1214 
1215  /*
1216  * Transform sorting/grouping stuff. Do ORDER BY first because both
1217  * transformGroupClause and transformDistinctClause need the results. Note
1218  * that these functions can also change the targetList, so it's passed to
1219  * them by reference.
1220  */
1221  qry->sortClause = transformSortClause(pstate,
1222  stmt->sortClause,
1223  &qry->targetList,
1225  false /* allow SQL92 rules */ );
1226 
1227  qry->groupClause = transformGroupClause(pstate,
1228  stmt->groupClause,
1229  &qry->groupingSets,
1230  &qry->targetList,
1231  qry->sortClause,
1233  false /* allow SQL92 rules */ );
1234 
1235  if (stmt->distinctClause == NIL)
1236  {
1237  qry->distinctClause = NIL;
1238  qry->hasDistinctOn = false;
1239  }
1240  else if (linitial(stmt->distinctClause) == NULL)
1241  {
1242  /* We had SELECT DISTINCT */
1244  &qry->targetList,
1245  qry->sortClause,
1246  false);
1247  qry->hasDistinctOn = false;
1248  }
1249  else
1250  {
1251  /* We had SELECT DISTINCT ON */
1253  stmt->distinctClause,
1254  &qry->targetList,
1255  qry->sortClause);
1256  qry->hasDistinctOn = true;
1257  }
1258 
1259  /* transform LIMIT */
1260  qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1261  EXPR_KIND_OFFSET, "OFFSET");
1262  qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1263  EXPR_KIND_LIMIT, "LIMIT");
1264 
1265  /* transform window clauses after we have seen all window functions */
1267  pstate->p_windowdefs,
1268  &qry->targetList);
1269 
1270  /* resolve any still-unresolved output columns as being type text */
1271  if (pstate->p_resolve_unknowns)
1272  resolveTargetListUnknowns(pstate, qry->targetList);
1273 
1274  qry->rtable = pstate->p_rtable;
1275  qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1276 
1277  qry->hasSubLinks = pstate->p_hasSubLinks;
1278  qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
1279  qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
1280  qry->hasAggs = pstate->p_hasAggs;
1281  if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
1282  parseCheckAggregates(pstate, qry);
1283 
1284  foreach(l, stmt->lockingClause)
1285  {
1286  transformLockingClause(pstate, qry,
1287  (LockingClause *) lfirst(l), false);
1288  }
1289 
1290  assign_query_collations(pstate, qry);
1291 
1292  return qry;
1293 }
1294 
1295 /*
1296  * transformValuesClause -
1297  * transforms a VALUES clause that's being used as a standalone SELECT
1298  *
1299  * We build a Query containing a VALUES RTE, rather as if one had written
1300  * SELECT * FROM (VALUES ...) AS "*VALUES*"
1301  */
1302 static Query *
1304 {
1305  Query *qry = makeNode(Query);
1306  List *exprsLists;
1307  List *coltypes = NIL;
1308  List *coltypmods = NIL;
1309  List *colcollations = NIL;
1310  List **colexprs = NULL;
1311  int sublist_length = -1;
1312  bool lateral = false;
1313  RangeTblEntry *rte;
1314  int rtindex;
1315  ListCell *lc;
1316  ListCell *lc2;
1317  int i;
1318 
1319  qry->commandType = CMD_SELECT;
1320 
1321  /* Most SELECT stuff doesn't apply in a VALUES clause */
1322  Assert(stmt->distinctClause == NIL);
1323  Assert(stmt->intoClause == NULL);
1324  Assert(stmt->targetList == NIL);
1325  Assert(stmt->fromClause == NIL);
1326  Assert(stmt->whereClause == NULL);
1327  Assert(stmt->groupClause == NIL);
1328  Assert(stmt->havingClause == NULL);
1329  Assert(stmt->windowClause == NIL);
1330  Assert(stmt->op == SETOP_NONE);
1331 
1332  /* process the WITH clause independently of all else */
1333  if (stmt->withClause)
1334  {
1335  qry->hasRecursive = stmt->withClause->recursive;
1336  qry->cteList = transformWithClause(pstate, stmt->withClause);
1337  qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1338  }
1339 
1340  /*
1341  * For each row of VALUES, transform the raw expressions.
1342  *
1343  * Note that the intermediate representation we build is column-organized
1344  * not row-organized. That simplifies the type and collation processing
1345  * below.
1346  */
1347  foreach(lc, stmt->valuesLists)
1348  {
1349  List *sublist = (List *) lfirst(lc);
1350 
1351  /*
1352  * Do basic expression transformation (same as a ROW() expr, but here
1353  * we disallow SetToDefault)
1354  */
1355  sublist = transformExpressionList(pstate, sublist,
1356  EXPR_KIND_VALUES, false);
1357 
1358  /*
1359  * All the sublists must be the same length, *after* transformation
1360  * (which might expand '*' into multiple items). The VALUES RTE can't
1361  * handle anything different.
1362  */
1363  if (sublist_length < 0)
1364  {
1365  /* Remember post-transformation length of first sublist */
1366  sublist_length = list_length(sublist);
1367  /* and allocate array for per-column lists */
1368  colexprs = (List **) palloc0(sublist_length * sizeof(List *));
1369  }
1370  else if (sublist_length != list_length(sublist))
1371  {
1372  ereport(ERROR,
1373  (errcode(ERRCODE_SYNTAX_ERROR),
1374  errmsg("VALUES lists must all be the same length"),
1375  parser_errposition(pstate,
1376  exprLocation((Node *) sublist))));
1377  }
1378 
1379  /* Build per-column expression lists */
1380  i = 0;
1381  foreach(lc2, sublist)
1382  {
1383  Node *col = (Node *) lfirst(lc2);
1384 
1385  colexprs[i] = lappend(colexprs[i], col);
1386  i++;
1387  }
1388 
1389  /* Release sub-list's cells to save memory */
1390  list_free(sublist);
1391  }
1392 
1393  /*
1394  * Now resolve the common types of the columns, and coerce everything to
1395  * those types. Then identify the common typmod and common collation, if
1396  * any, of each column.
1397  *
1398  * We must do collation processing now because (1) assign_query_collations
1399  * doesn't process rangetable entries, and (2) we need to label the VALUES
1400  * RTE with column collations for use in the outer query. We don't
1401  * consider conflict of implicit collations to be an error here; instead
1402  * the column will just show InvalidOid as its collation, and you'll get a
1403  * failure later if that results in failure to resolve a collation.
1404  *
1405  * Note we modify the per-column expression lists in-place.
1406  */
1407  for (i = 0; i < sublist_length; i++)
1408  {
1409  Oid coltype;
1410  int32 coltypmod = -1;
1411  Oid colcoll;
1412  bool first = true;
1413 
1414  coltype = select_common_type(pstate, colexprs[i], "VALUES", NULL);
1415 
1416  foreach(lc, colexprs[i])
1417  {
1418  Node *col = (Node *) lfirst(lc);
1419 
1420  col = coerce_to_common_type(pstate, col, coltype, "VALUES");
1421  lfirst(lc) = (void *) col;
1422  if (first)
1423  {
1424  coltypmod = exprTypmod(col);
1425  first = false;
1426  }
1427  else
1428  {
1429  /* As soon as we see a non-matching typmod, fall back to -1 */
1430  if (coltypmod >= 0 && coltypmod != exprTypmod(col))
1431  coltypmod = -1;
1432  }
1433  }
1434 
1435  colcoll = select_common_collation(pstate, colexprs[i], true);
1436 
1437  coltypes = lappend_oid(coltypes, coltype);
1438  coltypmods = lappend_int(coltypmods, coltypmod);
1439  colcollations = lappend_oid(colcollations, colcoll);
1440  }
1441 
1442  /*
1443  * Finally, rearrange the coerced expressions into row-organized lists.
1444  */
1445  exprsLists = NIL;
1446  foreach(lc, colexprs[0])
1447  {
1448  Node *col = (Node *) lfirst(lc);
1449  List *sublist;
1450 
1451  sublist = list_make1(col);
1452  exprsLists = lappend(exprsLists, sublist);
1453  }
1454  list_free(colexprs[0]);
1455  for (i = 1; i < sublist_length; i++)
1456  {
1457  forboth(lc, colexprs[i], lc2, exprsLists)
1458  {
1459  Node *col = (Node *) lfirst(lc);
1460  List *sublist = lfirst(lc2);
1461 
1462  /* sublist pointer in exprsLists won't need adjustment */
1463  (void) lappend(sublist, col);
1464  }
1465  list_free(colexprs[i]);
1466  }
1467 
1468  /*
1469  * Ordinarily there can't be any current-level Vars in the expression
1470  * lists, because the namespace was empty ... but if we're inside CREATE
1471  * RULE, then NEW/OLD references might appear. In that case we have to
1472  * mark the VALUES RTE as LATERAL.
1473  */
1474  if (pstate->p_rtable != NIL &&
1475  contain_vars_of_level((Node *) exprsLists, 0))
1476  lateral = true;
1477 
1478  /*
1479  * Generate the VALUES RTE
1480  */
1481  rte = addRangeTableEntryForValues(pstate, exprsLists,
1482  coltypes, coltypmods, colcollations,
1483  NULL, lateral, true);
1484  addRTEtoQuery(pstate, rte, true, true, true);
1485 
1486  /* assume new rte is at end */
1487  rtindex = list_length(pstate->p_rtable);
1488  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
1489 
1490  /*
1491  * Generate a targetlist as though expanding "*"
1492  */
1493  Assert(pstate->p_next_resno == 1);
1494  qry->targetList = expandRelAttrs(pstate, rte, rtindex, 0, -1);
1495 
1496  /*
1497  * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
1498  * VALUES, so cope.
1499  */
1500  qry->sortClause = transformSortClause(pstate,
1501  stmt->sortClause,
1502  &qry->targetList,
1504  false /* allow SQL92 rules */ );
1505 
1506  qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1507  EXPR_KIND_OFFSET, "OFFSET");
1508  qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1509  EXPR_KIND_LIMIT, "LIMIT");
1510 
1511  if (stmt->lockingClause)
1512  ereport(ERROR,
1513  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1514  /*------
1515  translator: %s is a SQL row locking clause such as FOR UPDATE */
1516  errmsg("%s cannot be applied to VALUES",
1518  linitial(stmt->lockingClause))->strength))));
1519 
1520  qry->rtable = pstate->p_rtable;
1521  qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1522 
1523  qry->hasSubLinks = pstate->p_hasSubLinks;
1524 
1525  assign_query_collations(pstate, qry);
1526 
1527  return qry;
1528 }
1529 
1530 /*
1531  * transformSetOperationStmt -
1532  * transforms a set-operations tree
1533  *
1534  * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1535  * structure to it. We must transform each leaf SELECT and build up a top-
1536  * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1537  * The tree of set operations is converted into the setOperations field of
1538  * the top-level Query.
1539  */
1540 static Query *
1542 {
1543  Query *qry = makeNode(Query);
1544  SelectStmt *leftmostSelect;
1545  int leftmostRTI;
1546  Query *leftmostQuery;
1547  SetOperationStmt *sostmt;
1548  List *sortClause;
1549  Node *limitOffset;
1550  Node *limitCount;
1551  List *lockingClause;
1552  WithClause *withClause;
1553  Node *node;
1554  ListCell *left_tlist,
1555  *lct,
1556  *lcm,
1557  *lcc,
1558  *l;
1559  List *targetvars,
1560  *targetnames,
1561  *sv_namespace;
1562  int sv_rtable_length;
1563  RangeTblEntry *jrte;
1564  int tllen;
1565 
1566  qry->commandType = CMD_SELECT;
1567 
1568  /*
1569  * Find leftmost leaf SelectStmt. We currently only need to do this in
1570  * order to deliver a suitable error message if there's an INTO clause
1571  * there, implying the set-op tree is in a context that doesn't allow
1572  * INTO. (transformSetOperationTree would throw error anyway, but it
1573  * seems worth the trouble to throw a different error for non-leftmost
1574  * INTO, so we produce that error in transformSetOperationTree.)
1575  */
1576  leftmostSelect = stmt->larg;
1577  while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1578  leftmostSelect = leftmostSelect->larg;
1579  Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1580  leftmostSelect->larg == NULL);
1581  if (leftmostSelect->intoClause)
1582  ereport(ERROR,
1583  (errcode(ERRCODE_SYNTAX_ERROR),
1584  errmsg("SELECT ... INTO is not allowed here"),
1585  parser_errposition(pstate,
1586  exprLocation((Node *) leftmostSelect->intoClause))));
1587 
1588  /*
1589  * We need to extract ORDER BY and other top-level clauses here and not
1590  * let transformSetOperationTree() see them --- else it'll just recurse
1591  * right back here!
1592  */
1593  sortClause = stmt->sortClause;
1594  limitOffset = stmt->limitOffset;
1595  limitCount = stmt->limitCount;
1596  lockingClause = stmt->lockingClause;
1597  withClause = stmt->withClause;
1598 
1599  stmt->sortClause = NIL;
1600  stmt->limitOffset = NULL;
1601  stmt->limitCount = NULL;
1602  stmt->lockingClause = NIL;
1603  stmt->withClause = NULL;
1604 
1605  /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1606  if (lockingClause)
1607  ereport(ERROR,
1608  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1609  /*------
1610  translator: %s is a SQL row locking clause such as FOR UPDATE */
1611  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1613  linitial(lockingClause))->strength))));
1614 
1615  /* Process the WITH clause independently of all else */
1616  if (withClause)
1617  {
1618  qry->hasRecursive = withClause->recursive;
1619  qry->cteList = transformWithClause(pstate, withClause);
1620  qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1621  }
1622 
1623  /*
1624  * Recursively transform the components of the tree.
1625  */
1626  sostmt = castNode(SetOperationStmt,
1627  transformSetOperationTree(pstate, stmt, true, NULL));
1628  Assert(sostmt);
1629  qry->setOperations = (Node *) sostmt;
1630 
1631  /*
1632  * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1633  */
1634  node = sostmt->larg;
1635  while (node && IsA(node, SetOperationStmt))
1636  node = ((SetOperationStmt *) node)->larg;
1637  Assert(node && IsA(node, RangeTblRef));
1638  leftmostRTI = ((RangeTblRef *) node)->rtindex;
1639  leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1640  Assert(leftmostQuery != NULL);
1641 
1642  /*
1643  * Generate dummy targetlist for outer query using column names of
1644  * leftmost select and common datatypes/collations of topmost set
1645  * operation. Also make lists of the dummy vars and their names for use
1646  * in parsing ORDER BY.
1647  *
1648  * Note: we use leftmostRTI as the varno of the dummy variables. It
1649  * shouldn't matter too much which RT index they have, as long as they
1650  * have one that corresponds to a real RT entry; else funny things may
1651  * happen when the tree is mashed by rule rewriting.
1652  */
1653  qry->targetList = NIL;
1654  targetvars = NIL;
1655  targetnames = NIL;
1656  left_tlist = list_head(leftmostQuery->targetList);
1657 
1658  forthree(lct, sostmt->colTypes,
1659  lcm, sostmt->colTypmods,
1660  lcc, sostmt->colCollations)
1661  {
1662  Oid colType = lfirst_oid(lct);
1663  int32 colTypmod = lfirst_int(lcm);
1664  Oid colCollation = lfirst_oid(lcc);
1665  TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1666  char *colName;
1667  TargetEntry *tle;
1668  Var *var;
1669 
1670  Assert(!lefttle->resjunk);
1671  colName = pstrdup(lefttle->resname);
1672  var = makeVar(leftmostRTI,
1673  lefttle->resno,
1674  colType,
1675  colTypmod,
1676  colCollation,
1677  0);
1678  var->location = exprLocation((Node *) lefttle->expr);
1679  tle = makeTargetEntry((Expr *) var,
1680  (AttrNumber) pstate->p_next_resno++,
1681  colName,
1682  false);
1683  qry->targetList = lappend(qry->targetList, tle);
1684  targetvars = lappend(targetvars, var);
1685  targetnames = lappend(targetnames, makeString(colName));
1686  left_tlist = lnext(left_tlist);
1687  }
1688 
1689  /*
1690  * As a first step towards supporting sort clauses that are expressions
1691  * using the output columns, generate a namespace entry that makes the
1692  * output columns visible. A Join RTE node is handy for this, since we
1693  * can easily control the Vars generated upon matches.
1694  *
1695  * Note: we don't yet do anything useful with such cases, but at least
1696  * "ORDER BY upper(foo)" will draw the right error message rather than
1697  * "foo not found".
1698  */
1699  sv_rtable_length = list_length(pstate->p_rtable);
1700 
1701  jrte = addRangeTableEntryForJoin(pstate,
1702  targetnames,
1703  JOIN_INNER,
1704  targetvars,
1705  NULL,
1706  false);
1707 
1708  sv_namespace = pstate->p_namespace;
1709  pstate->p_namespace = NIL;
1710 
1711  /* add jrte to column namespace only */
1712  addRTEtoQuery(pstate, jrte, false, false, true);
1713 
1714  /*
1715  * For now, we don't support resjunk sort clauses on the output of a
1716  * setOperation tree --- you can only use the SQL92-spec options of
1717  * selecting an output column by name or number. Enforce by checking that
1718  * transformSortClause doesn't add any items to tlist.
1719  */
1720  tllen = list_length(qry->targetList);
1721 
1722  qry->sortClause = transformSortClause(pstate,
1723  sortClause,
1724  &qry->targetList,
1726  false /* allow SQL92 rules */ );
1727 
1728  /* restore namespace, remove jrte from rtable */
1729  pstate->p_namespace = sv_namespace;
1730  pstate->p_rtable = list_truncate(pstate->p_rtable, sv_rtable_length);
1731 
1732  if (tllen != list_length(qry->targetList))
1733  ereport(ERROR,
1734  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1735  errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
1736  errdetail("Only result column names can be used, not expressions or functions."),
1737  errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause."),
1738  parser_errposition(pstate,
1739  exprLocation(list_nth(qry->targetList, tllen)))));
1740 
1741  qry->limitOffset = transformLimitClause(pstate, limitOffset,
1742  EXPR_KIND_OFFSET, "OFFSET");
1743  qry->limitCount = transformLimitClause(pstate, limitCount,
1744  EXPR_KIND_LIMIT, "LIMIT");
1745 
1746  qry->rtable = pstate->p_rtable;
1747  qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1748 
1749  qry->hasSubLinks = pstate->p_hasSubLinks;
1750  qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
1751  qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
1752  qry->hasAggs = pstate->p_hasAggs;
1753  if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
1754  parseCheckAggregates(pstate, qry);
1755 
1756  foreach(l, lockingClause)
1757  {
1758  transformLockingClause(pstate, qry,
1759  (LockingClause *) lfirst(l), false);
1760  }
1761 
1762  assign_query_collations(pstate, qry);
1763 
1764  return qry;
1765 }
1766 
1767 /*
1768  * transformSetOperationTree
1769  * Recursively transform leaves and internal nodes of a set-op tree
1770  *
1771  * In addition to returning the transformed node, if targetlist isn't NULL
1772  * then we return a list of its non-resjunk TargetEntry nodes. For a leaf
1773  * set-op node these are the actual targetlist entries; otherwise they are
1774  * dummy entries created to carry the type, typmod, collation, and location
1775  * (for error messages) of each output column of the set-op node. This info
1776  * is needed only during the internal recursion of this function, so outside
1777  * callers pass NULL for targetlist. Note: the reason for passing the
1778  * actual targetlist entries of a leaf node is so that upper levels can
1779  * replace UNKNOWN Consts with properly-coerced constants.
1780  */
1781 static Node *
1783  bool isTopLevel, List **targetlist)
1784 {
1785  bool isLeaf;
1786 
1787  Assert(stmt && IsA(stmt, SelectStmt));
1788 
1789  /* Guard against stack overflow due to overly complex set-expressions */
1791 
1792  /*
1793  * Validity-check both leaf and internal SELECTs for disallowed ops.
1794  */
1795  if (stmt->intoClause)
1796  ereport(ERROR,
1797  (errcode(ERRCODE_SYNTAX_ERROR),
1798  errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT"),
1799  parser_errposition(pstate,
1800  exprLocation((Node *) stmt->intoClause))));
1801 
1802  /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1803  if (stmt->lockingClause)
1804  ereport(ERROR,
1805  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1806  /*------
1807  translator: %s is a SQL row locking clause such as FOR UPDATE */
1808  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1810  linitial(stmt->lockingClause))->strength))));
1811 
1812  /*
1813  * If an internal node of a set-op tree has ORDER BY, LIMIT, FOR UPDATE,
1814  * or WITH clauses attached, we need to treat it like a leaf node to
1815  * generate an independent sub-Query tree. Otherwise, it can be
1816  * represented by a SetOperationStmt node underneath the parent Query.
1817  */
1818  if (stmt->op == SETOP_NONE)
1819  {
1820  Assert(stmt->larg == NULL && stmt->rarg == NULL);
1821  isLeaf = true;
1822  }
1823  else
1824  {
1825  Assert(stmt->larg != NULL && stmt->rarg != NULL);
1826  if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
1827  stmt->lockingClause || stmt->withClause)
1828  isLeaf = true;
1829  else
1830  isLeaf = false;
1831  }
1832 
1833  if (isLeaf)
1834  {
1835  /* Process leaf SELECT */
1836  Query *selectQuery;
1837  char selectName[32];
1839  RangeTblRef *rtr;
1840  ListCell *tl;
1841 
1842  /*
1843  * Transform SelectStmt into a Query.
1844  *
1845  * This works the same as SELECT transformation normally would, except
1846  * that we prevent resolving unknown-type outputs as TEXT. This does
1847  * not change the subquery's semantics since if the column type
1848  * matters semantically, it would have been resolved to something else
1849  * anyway. Doing this lets us resolve such outputs using
1850  * select_common_type(), below.
1851  *
1852  * Note: previously transformed sub-queries don't affect the parsing
1853  * of this sub-query, because they are not in the toplevel pstate's
1854  * namespace list.
1855  */
1856  selectQuery = parse_sub_analyze((Node *) stmt, pstate,
1857  NULL, false, false);
1858 
1859  /*
1860  * Check for bogus references to Vars on the current query level (but
1861  * upper-level references are okay). Normally this can't happen
1862  * because the namespace will be empty, but it could happen if we are
1863  * inside a rule.
1864  */
1865  if (pstate->p_namespace)
1866  {
1867  if (contain_vars_of_level((Node *) selectQuery, 1))
1868  ereport(ERROR,
1869  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1870  errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"),
1871  parser_errposition(pstate,
1872  locate_var_of_level((Node *) selectQuery, 1))));
1873  }
1874 
1875  /*
1876  * Extract a list of the non-junk TLEs for upper-level processing.
1877  */
1878  if (targetlist)
1879  {
1880  *targetlist = NIL;
1881  foreach(tl, selectQuery->targetList)
1882  {
1883  TargetEntry *tle = (TargetEntry *) lfirst(tl);
1884 
1885  if (!tle->resjunk)
1886  *targetlist = lappend(*targetlist, tle);
1887  }
1888  }
1889 
1890  /*
1891  * Make the leaf query be a subquery in the top-level rangetable.
1892  */
1893  snprintf(selectName, sizeof(selectName), "*SELECT* %d",
1894  list_length(pstate->p_rtable) + 1);
1895  rte = addRangeTableEntryForSubquery(pstate,
1896  selectQuery,
1897  makeAlias(selectName, NIL),
1898  false,
1899  false);
1900 
1901  /*
1902  * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
1903  */
1904  rtr = makeNode(RangeTblRef);
1905  /* assume new rte is at end */
1906  rtr->rtindex = list_length(pstate->p_rtable);
1907  Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1908  return (Node *) rtr;
1909  }
1910  else
1911  {
1912  /* Process an internal node (set operation node) */
1914  List *ltargetlist;
1915  List *rtargetlist;
1916  ListCell *ltl;
1917  ListCell *rtl;
1918  const char *context;
1919 
1920  context = (stmt->op == SETOP_UNION ? "UNION" :
1921  (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
1922  "EXCEPT"));
1923 
1924  op->op = stmt->op;
1925  op->all = stmt->all;
1926 
1927  /*
1928  * Recursively transform the left child node.
1929  */
1930  op->larg = transformSetOperationTree(pstate, stmt->larg,
1931  false,
1932  &ltargetlist);
1933 
1934  /*
1935  * If we are processing a recursive union query, now is the time to
1936  * examine the non-recursive term's output columns and mark the
1937  * containing CTE as having those result columns. We should do this
1938  * only at the topmost setop of the CTE, of course.
1939  */
1940  if (isTopLevel &&
1941  pstate->p_parent_cte &&
1942  pstate->p_parent_cte->cterecursive)
1943  determineRecursiveColTypes(pstate, op->larg, ltargetlist);
1944 
1945  /*
1946  * Recursively transform the right child node.
1947  */
1948  op->rarg = transformSetOperationTree(pstate, stmt->rarg,
1949  false,
1950  &rtargetlist);
1951 
1952  /*
1953  * Verify that the two children have the same number of non-junk
1954  * columns, and determine the types of the merged output columns.
1955  */
1956  if (list_length(ltargetlist) != list_length(rtargetlist))
1957  ereport(ERROR,
1958  (errcode(ERRCODE_SYNTAX_ERROR),
1959  errmsg("each %s query must have the same number of columns",
1960  context),
1961  parser_errposition(pstate,
1962  exprLocation((Node *) rtargetlist))));
1963 
1964  if (targetlist)
1965  *targetlist = NIL;
1966  op->colTypes = NIL;
1967  op->colTypmods = NIL;
1968  op->colCollations = NIL;
1969  op->groupClauses = NIL;
1970  forboth(ltl, ltargetlist, rtl, rtargetlist)
1971  {
1972  TargetEntry *ltle = (TargetEntry *) lfirst(ltl);
1973  TargetEntry *rtle = (TargetEntry *) lfirst(rtl);
1974  Node *lcolnode = (Node *) ltle->expr;
1975  Node *rcolnode = (Node *) rtle->expr;
1976  Oid lcoltype = exprType(lcolnode);
1977  Oid rcoltype = exprType(rcolnode);
1978  int32 lcoltypmod = exprTypmod(lcolnode);
1979  int32 rcoltypmod = exprTypmod(rcolnode);
1980  Node *bestexpr;
1981  int bestlocation;
1982  Oid rescoltype;
1983  int32 rescoltypmod;
1984  Oid rescolcoll;
1985 
1986  /* select common type, same as CASE et al */
1987  rescoltype = select_common_type(pstate,
1988  list_make2(lcolnode, rcolnode),
1989  context,
1990  &bestexpr);
1991  bestlocation = exprLocation(bestexpr);
1992  /* if same type and same typmod, use typmod; else default */
1993  if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
1994  rescoltypmod = lcoltypmod;
1995  else
1996  rescoltypmod = -1;
1997 
1998  /*
1999  * Verify the coercions are actually possible. If not, we'd fail
2000  * later anyway, but we want to fail now while we have sufficient
2001  * context to produce an error cursor position.
2002  *
2003  * For all non-UNKNOWN-type cases, we verify coercibility but we
2004  * don't modify the child's expression, for fear of changing the
2005  * child query's semantics.
2006  *
2007  * If a child expression is an UNKNOWN-type Const or Param, we
2008  * want to replace it with the coerced expression. This can only
2009  * happen when the child is a leaf set-op node. It's safe to
2010  * replace the expression because if the child query's semantics
2011  * depended on the type of this output column, it'd have already
2012  * coerced the UNKNOWN to something else. We want to do this
2013  * because (a) we want to verify that a Const is valid for the
2014  * target type, or resolve the actual type of an UNKNOWN Param,
2015  * and (b) we want to avoid unnecessary discrepancies between the
2016  * output type of the child query and the resolved target type.
2017  * Such a discrepancy would disable optimization in the planner.
2018  *
2019  * If it's some other UNKNOWN-type node, eg a Var, we do nothing
2020  * (knowing that coerce_to_common_type would fail). The planner
2021  * is sometimes able to fold an UNKNOWN Var to a constant before
2022  * it has to coerce the type, so failing now would just break
2023  * cases that might work.
2024  */
2025  if (lcoltype != UNKNOWNOID)
2026  lcolnode = coerce_to_common_type(pstate, lcolnode,
2027  rescoltype, context);
2028  else if (IsA(lcolnode, Const) ||
2029  IsA(lcolnode, Param))
2030  {
2031  lcolnode = coerce_to_common_type(pstate, lcolnode,
2032  rescoltype, context);
2033  ltle->expr = (Expr *) lcolnode;
2034  }
2035 
2036  if (rcoltype != UNKNOWNOID)
2037  rcolnode = coerce_to_common_type(pstate, rcolnode,
2038  rescoltype, context);
2039  else if (IsA(rcolnode, Const) ||
2040  IsA(rcolnode, Param))
2041  {
2042  rcolnode = coerce_to_common_type(pstate, rcolnode,
2043  rescoltype, context);
2044  rtle->expr = (Expr *) rcolnode;
2045  }
2046 
2047  /*
2048  * Select common collation. A common collation is required for
2049  * all set operators except UNION ALL; see SQL:2008 7.13 <query
2050  * expression> Syntax Rule 15c. (If we fail to identify a common
2051  * collation for a UNION ALL column, the curCollations element
2052  * will be set to InvalidOid, which may result in a runtime error
2053  * if something at a higher query level wants to use the column's
2054  * collation.)
2055  */
2056  rescolcoll = select_common_collation(pstate,
2057  list_make2(lcolnode, rcolnode),
2058  (op->op == SETOP_UNION && op->all));
2059 
2060  /* emit results */
2061  op->colTypes = lappend_oid(op->colTypes, rescoltype);
2062  op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
2063  op->colCollations = lappend_oid(op->colCollations, rescolcoll);
2064 
2065  /*
2066  * For all cases except UNION ALL, identify the grouping operators
2067  * (and, if available, sorting operators) that will be used to
2068  * eliminate duplicates.
2069  */
2070  if (op->op != SETOP_UNION || !op->all)
2071  {
2073  Oid sortop;
2074  Oid eqop;
2075  bool hashable;
2076  ParseCallbackState pcbstate;
2077 
2078  setup_parser_errposition_callback(&pcbstate, pstate,
2079  bestlocation);
2080 
2081  /* determine the eqop and optional sortop */
2082  get_sort_group_operators(rescoltype,
2083  false, true, false,
2084  &sortop, &eqop, NULL,
2085  &hashable);
2086 
2088 
2089  /* we don't have a tlist yet, so can't assign sortgrouprefs */
2090  grpcl->tleSortGroupRef = 0;
2091  grpcl->eqop = eqop;
2092  grpcl->sortop = sortop;
2093  grpcl->nulls_first = false; /* OK with or without sortop */
2094  grpcl->hashable = hashable;
2095 
2096  op->groupClauses = lappend(op->groupClauses, grpcl);
2097  }
2098 
2099  /*
2100  * Construct a dummy tlist entry to return. We use a SetToDefault
2101  * node for the expression, since it carries exactly the fields
2102  * needed, but any other expression node type would do as well.
2103  */
2104  if (targetlist)
2105  {
2106  SetToDefault *rescolnode = makeNode(SetToDefault);
2107  TargetEntry *restle;
2108 
2109  rescolnode->typeId = rescoltype;
2110  rescolnode->typeMod = rescoltypmod;
2111  rescolnode->collation = rescolcoll;
2112  rescolnode->location = bestlocation;
2113  restle = makeTargetEntry((Expr *) rescolnode,
2114  0, /* no need to set resno */
2115  NULL,
2116  false);
2117  *targetlist = lappend(*targetlist, restle);
2118  }
2119  }
2120 
2121  return (Node *) op;
2122  }
2123 }
2124 
2125 /*
2126  * Process the outputs of the non-recursive term of a recursive union
2127  * to set up the parent CTE's columns
2128  */
2129 static void
2130 determineRecursiveColTypes(ParseState *pstate, Node *larg, List *nrtargetlist)
2131 {
2132  Node *node;
2133  int leftmostRTI;
2134  Query *leftmostQuery;
2135  List *targetList;
2136  ListCell *left_tlist;
2137  ListCell *nrtl;
2138  int next_resno;
2139 
2140  /*
2141  * Find leftmost leaf SELECT
2142  */
2143  node = larg;
2144  while (node && IsA(node, SetOperationStmt))
2145  node = ((SetOperationStmt *) node)->larg;
2146  Assert(node && IsA(node, RangeTblRef));
2147  leftmostRTI = ((RangeTblRef *) node)->rtindex;
2148  leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
2149  Assert(leftmostQuery != NULL);
2150 
2151  /*
2152  * Generate dummy targetlist using column names of leftmost select and
2153  * dummy result expressions of the non-recursive term.
2154  */
2155  targetList = NIL;
2156  left_tlist = list_head(leftmostQuery->targetList);
2157  next_resno = 1;
2158 
2159  foreach(nrtl, nrtargetlist)
2160  {
2161  TargetEntry *nrtle = (TargetEntry *) lfirst(nrtl);
2162  TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
2163  char *colName;
2164  TargetEntry *tle;
2165 
2166  Assert(!lefttle->resjunk);
2167  colName = pstrdup(lefttle->resname);
2168  tle = makeTargetEntry(nrtle->expr,
2169  next_resno++,
2170  colName,
2171  false);
2172  targetList = lappend(targetList, tle);
2173  left_tlist = lnext(left_tlist);
2174  }
2175 
2176  /* Now build CTE's output column info using dummy targetlist */
2177  analyzeCTETargetList(pstate, pstate->p_parent_cte, targetList);
2178 }
2179 
2180 
2181 /*
2182  * transformUpdateStmt -
2183  * transforms an update statement
2184  */
2185 static Query *
2187 {
2188  Query *qry = makeNode(Query);
2189  ParseNamespaceItem *nsitem;
2190  Node *qual;
2191 
2192  qry->commandType = CMD_UPDATE;
2193  pstate->p_is_insert = false;
2194 
2195  /* process the WITH clause independently of all else */
2196  if (stmt->withClause)
2197  {
2198  qry->hasRecursive = stmt->withClause->recursive;
2199  qry->cteList = transformWithClause(pstate, stmt->withClause);
2200  qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
2201  }
2202 
2203  qry->resultRelation = setTargetTable(pstate, stmt->relation,
2204  stmt->relation->inh,
2205  true,
2206  ACL_UPDATE);
2207 
2208  /* grab the namespace item made by setTargetTable */
2209  nsitem = (ParseNamespaceItem *) llast(pstate->p_namespace);
2210 
2211  /* subqueries in FROM cannot access the result relation */
2212  nsitem->p_lateral_only = true;
2213  nsitem->p_lateral_ok = false;
2214 
2215  /*
2216  * the FROM clause is non-standard SQL syntax. We used to be able to do
2217  * this with REPLACE in POSTQUEL so we keep the feature.
2218  */
2219  transformFromClause(pstate, stmt->fromClause);
2220 
2221  /* remaining clauses can reference the result relation normally */
2222  nsitem->p_lateral_only = false;
2223  nsitem->p_lateral_ok = true;
2224 
2225  qual = transformWhereClause(pstate, stmt->whereClause,
2226  EXPR_KIND_WHERE, "WHERE");
2227 
2228  qry->returningList = transformReturningList(pstate, stmt->returningList);
2229 
2230  /*
2231  * Now we are done with SELECT-like processing, and can get on with
2232  * transforming the target list to match the UPDATE target columns.
2233  */
2234  qry->targetList = transformUpdateTargetList(pstate, stmt->targetList);
2235 
2236  qry->rtable = pstate->p_rtable;
2237  qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2238 
2239  qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2240  qry->hasSubLinks = pstate->p_hasSubLinks;
2241 
2242  assign_query_collations(pstate, qry);
2243 
2244  return qry;
2245 }
2246 
2247 /*
2248  * transformUpdateTargetList -
2249  * handle SET clause in UPDATE/INSERT ... ON CONFLICT UPDATE
2250  */
2251 static List *
2253 {
2254  List *tlist = NIL;
2255  RangeTblEntry *target_rte;
2256  ListCell *orig_tl;
2257  ListCell *tl;
2258 
2259  tlist = transformTargetList(pstate, origTlist,
2261 
2262  /* Prepare to assign non-conflicting resnos to resjunk attributes */
2263  if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2264  pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2265 
2266  /* Prepare non-junk columns for assignment to target table */
2267  target_rte = pstate->p_target_rangetblentry;
2268  orig_tl = list_head(origTlist);
2269 
2270  foreach(tl, tlist)
2271  {
2272  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2273  ResTarget *origTarget;
2274  int attrno;
2275 
2276  if (tle->resjunk)
2277  {
2278  /*
2279  * Resjunk nodes need no additional processing, but be sure they
2280  * have resnos that do not match any target columns; else rewriter
2281  * or planner might get confused. They don't need a resname
2282  * either.
2283  */
2284  tle->resno = (AttrNumber) pstate->p_next_resno++;
2285  tle->resname = NULL;
2286  continue;
2287  }
2288  if (orig_tl == NULL)
2289  elog(ERROR, "UPDATE target count mismatch --- internal error");
2290  origTarget = castNode(ResTarget, lfirst(orig_tl));
2291 
2292  attrno = attnameAttNum(pstate->p_target_relation,
2293  origTarget->name, true);
2294  if (attrno == InvalidAttrNumber)
2295  ereport(ERROR,
2296  (errcode(ERRCODE_UNDEFINED_COLUMN),
2297  errmsg("column \"%s\" of relation \"%s\" does not exist",
2298  origTarget->name,
2300  parser_errposition(pstate, origTarget->location)));
2301 
2302  updateTargetListEntry(pstate, tle, origTarget->name,
2303  attrno,
2304  origTarget->indirection,
2305  origTarget->location);
2306 
2307  /* Mark the target column as requiring update permissions */
2308  target_rte->updatedCols = bms_add_member(target_rte->updatedCols,
2310 
2311  orig_tl = lnext(orig_tl);
2312  }
2313  if (orig_tl != NULL)
2314  elog(ERROR, "UPDATE target count mismatch --- internal error");
2315 
2316  return tlist;
2317 }
2318 
2319 /*
2320  * transformReturningList -
2321  * handle a RETURNING clause in INSERT/UPDATE/DELETE
2322  */
2323 static List *
2324 transformReturningList(ParseState *pstate, List *returningList)
2325 {
2326  List *rlist;
2327  int save_next_resno;
2328 
2329  if (returningList == NIL)
2330  return NIL; /* nothing to do */
2331 
2332  /*
2333  * We need to assign resnos starting at one in the RETURNING list. Save
2334  * and restore the main tlist's value of p_next_resno, just in case
2335  * someone looks at it later (probably won't happen).
2336  */
2337  save_next_resno = pstate->p_next_resno;
2338  pstate->p_next_resno = 1;
2339 
2340  /* transform RETURNING identically to a SELECT targetlist */
2341  rlist = transformTargetList(pstate, returningList, EXPR_KIND_RETURNING);
2342 
2343  /*
2344  * Complain if the nonempty tlist expanded to nothing (which is possible
2345  * if it contains only a star-expansion of a zero-column table). If we
2346  * allow this, the parsed Query will look like it didn't have RETURNING,
2347  * with results that would probably surprise the user.
2348  */
2349  if (rlist == NIL)
2350  ereport(ERROR,
2351  (errcode(ERRCODE_SYNTAX_ERROR),
2352  errmsg("RETURNING must have at least one column"),
2353  parser_errposition(pstate,
2354  exprLocation(linitial(returningList)))));
2355 
2356  /* mark column origins */
2357  markTargetListOrigins(pstate, rlist);
2358 
2359  /* resolve any still-unresolved output columns as being type text */
2360  if (pstate->p_resolve_unknowns)
2361  resolveTargetListUnknowns(pstate, rlist);
2362 
2363  /* restore state */
2364  pstate->p_next_resno = save_next_resno;
2365 
2366  return rlist;
2367 }
2368 
2369 
2370 /*
2371  * transformDeclareCursorStmt -
2372  * transform a DECLARE CURSOR Statement
2373  *
2374  * DECLARE CURSOR is like other utility statements in that we emit it as a
2375  * CMD_UTILITY Query node; however, we must first transform the contained
2376  * query. We used to postpone that until execution, but it's really necessary
2377  * to do it during the normal parse analysis phase to ensure that side effects
2378  * of parser hooks happen at the expected time.
2379  */
2380 static Query *
2382 {
2383  Query *result;
2384  Query *query;
2385 
2386  /*
2387  * Don't allow both SCROLL and NO SCROLL to be specified
2388  */
2389  if ((stmt->options & CURSOR_OPT_SCROLL) &&
2390  (stmt->options & CURSOR_OPT_NO_SCROLL))
2391  ereport(ERROR,
2392  (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
2393  errmsg("cannot specify both SCROLL and NO SCROLL")));
2394 
2395  /* Transform contained query, not allowing SELECT INTO */
2396  query = transformStmt(pstate, stmt->query);
2397  stmt->query = (Node *) query;
2398 
2399  /* Grammar should not have allowed anything but SELECT */
2400  if (!IsA(query, Query) ||
2401  query->commandType != CMD_SELECT)
2402  elog(ERROR, "unexpected non-SELECT command in DECLARE CURSOR");
2403 
2404  /*
2405  * We also disallow data-modifying WITH in a cursor. (This could be
2406  * allowed, but the semantics of when the updates occur might be
2407  * surprising.)
2408  */
2409  if (query->hasModifyingCTE)
2410  ereport(ERROR,
2411  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2412  errmsg("DECLARE CURSOR must not contain data-modifying statements in WITH")));
2413 
2414  /* FOR UPDATE and WITH HOLD are not compatible */
2415  if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
2416  ereport(ERROR,
2417  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2418  /*------
2419  translator: %s is a SQL row locking clause such as FOR UPDATE */
2420  errmsg("DECLARE CURSOR WITH HOLD ... %s is not supported",
2422  linitial(query->rowMarks))->strength)),
2423  errdetail("Holdable cursors must be READ ONLY.")));
2424 
2425  /* FOR UPDATE and SCROLL are not compatible */
2426  if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
2427  ereport(ERROR,
2428  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2429  /*------
2430  translator: %s is a SQL row locking clause such as FOR UPDATE */
2431  errmsg("DECLARE SCROLL CURSOR ... %s is not supported",
2433  linitial(query->rowMarks))->strength)),
2434  errdetail("Scrollable cursors must be READ ONLY.")));
2435 
2436  /* FOR UPDATE and INSENSITIVE are not compatible */
2437  if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
2438  ereport(ERROR,
2439  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2440  /*------
2441  translator: %s is a SQL row locking clause such as FOR UPDATE */
2442  errmsg("DECLARE INSENSITIVE CURSOR ... %s is not supported",
2444  linitial(query->rowMarks))->strength)),
2445  errdetail("Insensitive cursors must be READ ONLY.")));
2446 
2447  /* represent the command as a utility Query */
2448  result = makeNode(Query);
2449  result->commandType = CMD_UTILITY;
2450  result->utilityStmt = (Node *) stmt;
2451 
2452  return result;
2453 }
2454 
2455 
2456 /*
2457  * transformExplainStmt -
2458  * transform an EXPLAIN Statement
2459  *
2460  * EXPLAIN is like other utility statements in that we emit it as a
2461  * CMD_UTILITY Query node; however, we must first transform the contained
2462  * query. We used to postpone that until execution, but it's really necessary
2463  * to do it during the normal parse analysis phase to ensure that side effects
2464  * of parser hooks happen at the expected time.
2465  */
2466 static Query *
2468 {
2469  Query *result;
2470 
2471  /* transform contained query, allowing SELECT INTO */
2472  stmt->query = (Node *) transformOptionalSelectInto(pstate, stmt->query);
2473 
2474  /* represent the command as a utility Query */
2475  result = makeNode(Query);
2476  result->commandType = CMD_UTILITY;
2477  result->utilityStmt = (Node *) stmt;
2478 
2479  return result;
2480 }
2481 
2482 
2483 /*
2484  * transformCreateTableAsStmt -
2485  * transform a CREATE TABLE AS, SELECT ... INTO, or CREATE MATERIALIZED VIEW
2486  * Statement
2487  *
2488  * As with DECLARE CURSOR and EXPLAIN, transform the contained statement now.
2489  */
2490 static Query *
2492 {
2493  Query *result;
2494  Query *query;
2495 
2496  /* transform contained query, not allowing SELECT INTO */
2497  query = transformStmt(pstate, stmt->query);
2498  stmt->query = (Node *) query;
2499 
2500  /* additional work needed for CREATE MATERIALIZED VIEW */
2501  if (stmt->relkind == OBJECT_MATVIEW)
2502  {
2503  /*
2504  * Prohibit a data-modifying CTE in the query used to create a
2505  * materialized view. It's not sufficiently clear what the user would
2506  * want to happen if the MV is refreshed or incrementally maintained.
2507  */
2508  if (query->hasModifyingCTE)
2509  ereport(ERROR,
2510  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2511  errmsg("materialized views must not use data-modifying statements in WITH")));
2512 
2513  /*
2514  * Check whether any temporary database objects are used in the
2515  * creation query. It would be hard to refresh data or incrementally
2516  * maintain it if a source disappeared.
2517  */
2518  if (isQueryUsingTempRelation(query))
2519  ereport(ERROR,
2520  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2521  errmsg("materialized views must not use temporary tables or views")));
2522 
2523  /*
2524  * A materialized view would either need to save parameters for use in
2525  * maintaining/loading the data or prohibit them entirely. The latter
2526  * seems safer and more sane.
2527  */
2528  if (query_contains_extern_params(query))
2529  ereport(ERROR,
2530  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2531  errmsg("materialized views may not be defined using bound parameters")));
2532 
2533  /*
2534  * For now, we disallow unlogged materialized views, because it seems
2535  * like a bad idea for them to just go to empty after a crash. (If we
2536  * could mark them as unpopulated, that would be better, but that
2537  * requires catalog changes which crash recovery can't presently
2538  * handle.)
2539  */
2541  ereport(ERROR,
2542  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2543  errmsg("materialized views cannot be UNLOGGED")));
2544 
2545  /*
2546  * At runtime, we'll need a copy of the parsed-but-not-rewritten Query
2547  * for purposes of creating the view's ON SELECT rule. We stash that
2548  * in the IntoClause because that's where intorel_startup() can
2549  * conveniently get it from.
2550  */
2551  stmt->into->viewQuery = (Node *) copyObject(query);
2552  }
2553 
2554  /* represent the command as a utility Query */
2555  result = makeNode(Query);
2556  result->commandType = CMD_UTILITY;
2557  result->utilityStmt = (Node *) stmt;
2558 
2559  return result;
2560 }
2561 
2562 
2563 /*
2564  * Produce a string representation of a LockClauseStrength value.
2565  * This should only be applied to valid values (not LCS_NONE).
2566  */
2567 const char *
2569 {
2570  switch (strength)
2571  {
2572  case LCS_NONE:
2573  Assert(false);
2574  break;
2575  case LCS_FORKEYSHARE:
2576  return "FOR KEY SHARE";
2577  case LCS_FORSHARE:
2578  return "FOR SHARE";
2579  case LCS_FORNOKEYUPDATE:
2580  return "FOR NO KEY UPDATE";
2581  case LCS_FORUPDATE:
2582  return "FOR UPDATE";
2583  }
2584  return "FOR some"; /* shouldn't happen */
2585 }
2586 
2587 /*
2588  * Check for features that are not supported with FOR [KEY] UPDATE/SHARE.
2589  *
2590  * exported so planner can check again after rewriting, query pullup, etc
2591  */
2592 void
2594 {
2595  Assert(strength != LCS_NONE); /* else caller error */
2596 
2597  if (qry->setOperations)
2598  ereport(ERROR,
2599  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2600  /*------
2601  translator: %s is a SQL row locking clause such as FOR UPDATE */
2602  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
2603  LCS_asString(strength))));
2604  if (qry->distinctClause != NIL)
2605  ereport(ERROR,
2606  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2607  /*------
2608  translator: %s is a SQL row locking clause such as FOR UPDATE */
2609  errmsg("%s is not allowed with DISTINCT clause",
2610  LCS_asString(strength))));
2611  if (qry->groupClause != NIL)
2612  ereport(ERROR,
2613  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2614  /*------
2615  translator: %s is a SQL row locking clause such as FOR UPDATE */
2616  errmsg("%s is not allowed with GROUP BY clause",
2617  LCS_asString(strength))));
2618  if (qry->havingQual != NULL)
2619  ereport(ERROR,
2620  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2621  /*------
2622  translator: %s is a SQL row locking clause such as FOR UPDATE */
2623  errmsg("%s is not allowed with HAVING clause",
2624  LCS_asString(strength))));
2625  if (qry->hasAggs)
2626  ereport(ERROR,
2627  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2628  /*------
2629  translator: %s is a SQL row locking clause such as FOR UPDATE */
2630  errmsg("%s is not allowed with aggregate functions",
2631  LCS_asString(strength))));
2632  if (qry->hasWindowFuncs)
2633  ereport(ERROR,
2634  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2635  /*------
2636  translator: %s is a SQL row locking clause such as FOR UPDATE */
2637  errmsg("%s is not allowed with window functions",
2638  LCS_asString(strength))));
2639  if (qry->hasTargetSRFs)
2640  ereport(ERROR,
2641  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2642  /*------
2643  translator: %s is a SQL row locking clause such as FOR UPDATE */
2644  errmsg("%s is not allowed with set-returning functions in the target list",
2645  LCS_asString(strength))));
2646 }
2647 
2648 /*
2649  * Transform a FOR [KEY] UPDATE/SHARE clause
2650  *
2651  * This basically involves replacing names by integer relids.
2652  *
2653  * NB: if you need to change this, see also markQueryForLocking()
2654  * in rewriteHandler.c, and isLockedRefname() in parse_relation.c.
2655  */
2656 static void
2658  bool pushedDown)
2659 {
2660  List *lockedRels = lc->lockedRels;
2661  ListCell *l;
2662  ListCell *rt;
2663  Index i;
2664  LockingClause *allrels;
2665 
2666  CheckSelectLocking(qry, lc->strength);
2667 
2668  /* make a clause we can pass down to subqueries to select all rels */
2669  allrels = makeNode(LockingClause);
2670  allrels->lockedRels = NIL; /* indicates all rels */
2671  allrels->strength = lc->strength;
2672  allrels->waitPolicy = lc->waitPolicy;
2673 
2674  if (lockedRels == NIL)
2675  {
2676  /* all regular tables used in query */
2677  i = 0;
2678  foreach(rt, qry->rtable)
2679  {
2680  RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2681 
2682  ++i;
2683  switch (rte->rtekind)
2684  {
2685  case RTE_RELATION:
2686  applyLockingClause(qry, i, lc->strength, lc->waitPolicy,
2687  pushedDown);
2689  break;
2690  case RTE_SUBQUERY:
2691  applyLockingClause(qry, i, lc->strength, lc->waitPolicy,
2692  pushedDown);
2693 
2694  /*
2695  * FOR UPDATE/SHARE of subquery is propagated to all of
2696  * subquery's rels, too. We could do this later (based on
2697  * the marking of the subquery RTE) but it is convenient
2698  * to have local knowledge in each query level about which
2699  * rels need to be opened with RowShareLock.
2700  */
2701  transformLockingClause(pstate, rte->subquery,
2702  allrels, true);
2703  break;
2704  default:
2705  /* ignore JOIN, SPECIAL, FUNCTION, VALUES, CTE RTEs */
2706  break;
2707  }
2708  }
2709  }
2710  else
2711  {
2712  /* just the named tables */
2713  foreach(l, lockedRels)
2714  {
2715  RangeVar *thisrel = (RangeVar *) lfirst(l);
2716 
2717  /* For simplicity we insist on unqualified alias names here */
2718  if (thisrel->catalogname || thisrel->schemaname)
2719  ereport(ERROR,
2720  (errcode(ERRCODE_SYNTAX_ERROR),
2721  /*------
2722  translator: %s is a SQL row locking clause such as FOR UPDATE */
2723  errmsg("%s must specify unqualified relation names",
2724  LCS_asString(lc->strength)),
2725  parser_errposition(pstate, thisrel->location)));
2726 
2727  i = 0;
2728  foreach(rt, qry->rtable)
2729  {
2730  RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2731 
2732  ++i;
2733  if (strcmp(rte->eref->aliasname, thisrel->relname) == 0)
2734  {
2735  switch (rte->rtekind)
2736  {
2737  case RTE_RELATION:
2738  applyLockingClause(qry, i, lc->strength,
2739  lc->waitPolicy, pushedDown);
2741  break;
2742  case RTE_SUBQUERY:
2743  applyLockingClause(qry, i, lc->strength,
2744  lc->waitPolicy, pushedDown);
2745  /* see comment above */
2746  transformLockingClause(pstate, rte->subquery,
2747  allrels, true);
2748  break;
2749  case RTE_JOIN:
2750  ereport(ERROR,
2751  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2752  /*------
2753  translator: %s is a SQL row locking clause such as FOR UPDATE */
2754  errmsg("%s cannot be applied to a join",
2755  LCS_asString(lc->strength)),
2756  parser_errposition(pstate, thisrel->location)));
2757  break;
2758  case RTE_FUNCTION:
2759  ereport(ERROR,
2760  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2761  /*------
2762  translator: %s is a SQL row locking clause such as FOR UPDATE */
2763  errmsg("%s cannot be applied to a function",
2764  LCS_asString(lc->strength)),
2765  parser_errposition(pstate, thisrel->location)));
2766  break;
2767  case RTE_TABLEFUNC:
2768  ereport(ERROR,
2769  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2770  /*------
2771  translator: %s is a SQL row locking clause such as FOR UPDATE */
2772  errmsg("%s cannot be applied to a table function",
2773  LCS_asString(lc->strength)),
2774  parser_errposition(pstate, thisrel->location)));
2775  break;
2776  case RTE_VALUES:
2777  ereport(ERROR,
2778  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2779  /*------
2780  translator: %s is a SQL row locking clause such as FOR UPDATE */
2781  errmsg("%s cannot be applied to VALUES",
2782  LCS_asString(lc->strength)),
2783  parser_errposition(pstate, thisrel->location)));
2784  break;
2785  case RTE_CTE:
2786  ereport(ERROR,
2787  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2788  /*------
2789  translator: %s is a SQL row locking clause such as FOR UPDATE */
2790  errmsg("%s cannot be applied to a WITH query",
2791  LCS_asString(lc->strength)),
2792  parser_errposition(pstate, thisrel->location)));
2793  break;
2794  default:
2795  elog(ERROR, "unrecognized RTE type: %d",
2796  (int) rte->rtekind);
2797  break;
2798  }
2799  break; /* out of foreach loop */
2800  }
2801  }
2802  if (rt == NULL)
2803  ereport(ERROR,
2805  /*------
2806  translator: %s is a SQL row locking clause such as FOR UPDATE */
2807  errmsg("relation \"%s\" in %s clause not found in FROM clause",
2808  thisrel->relname,
2809  LCS_asString(lc->strength)),
2810  parser_errposition(pstate, thisrel->location)));
2811  }
2812  }
2813 }
2814 
2815 /*
2816  * Record locking info for a single rangetable item
2817  */
2818 void
2820  LockClauseStrength strength, LockWaitPolicy waitPolicy,
2821  bool pushedDown)
2822 {
2823  RowMarkClause *rc;
2824 
2825  Assert(strength != LCS_NONE); /* else caller error */
2826 
2827  /* If it's an explicit clause, make sure hasForUpdate gets set */
2828  if (!pushedDown)
2829  qry->hasForUpdate = true;
2830 
2831  /* Check for pre-existing entry for same rtindex */
2832  if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
2833  {
2834  /*
2835  * If the same RTE is specified with more than one locking strength,
2836  * use the strongest. (Reasonable, since you can't take both a shared
2837  * and exclusive lock at the same time; it'll end up being exclusive
2838  * anyway.)
2839  *
2840  * Similarly, if the same RTE is specified with more than one lock
2841  * wait policy, consider that NOWAIT wins over SKIP LOCKED, which in
2842  * turn wins over waiting for the lock (the default). This is a bit
2843  * more debatable but raising an error doesn't seem helpful. (Consider
2844  * for instance SELECT FOR UPDATE NOWAIT from a view that internally
2845  * contains a plain FOR UPDATE spec.) Having NOWAIT win over SKIP
2846  * LOCKED is reasonable since the former throws an error in case of
2847  * coming across a locked tuple, which may be undesirable in some
2848  * cases but it seems better than silently returning inconsistent
2849  * results.
2850  *
2851  * And of course pushedDown becomes false if any clause is explicit.
2852  */
2853  rc->strength = Max(rc->strength, strength);
2854  rc->waitPolicy = Max(rc->waitPolicy, waitPolicy);
2855  rc->pushedDown &= pushedDown;
2856  return;
2857  }
2858 
2859  /* Make a new RowMarkClause */
2860  rc = makeNode(RowMarkClause);
2861  rc->rti = rtindex;
2862  rc->strength = strength;
2863  rc->waitPolicy = waitPolicy;
2864  rc->pushedDown = pushedDown;
2865  qry->rowMarks = lappend(qry->rowMarks, rc);
2866 }
2867 
2868 /*
2869  * Coverage testing for raw_expression_tree_walker().
2870  *
2871  * When enabled, we run raw_expression_tree_walker() over every DML statement
2872  * submitted to parse analysis. Without this provision, that function is only
2873  * applied in limited cases involving CTEs, and we don't really want to have
2874  * to test everything inside as well as outside a CTE.
2875  */
2876 #ifdef RAW_EXPRESSION_COVERAGE_TEST
2877 
2878 static bool
2879 test_raw_expression_coverage(Node *node, void *context)
2880 {
2881  if (node == NULL)
2882  return false;
2883  return raw_expression_tree_walker(node,
2884  test_raw_expression_coverage,
2885  context);
2886 }
2887 
2888 #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:726
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:1496
Expr * refassgnexpr
Definition: primnodes.h:409
List * fromClause
Definition: parsenodes.h:1428
static void transformLockingClause(ParseState *pstate, Query *qry, LockingClause *lc, bool pushedDown)
Definition: analyze.c:2657
bool p_hasSubLinks
Definition: parse_node.h:195
static List * transformUpdateTargetList(ParseState *pstate, List *targetList)
Definition: analyze.c:2252
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:282
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
static Query * transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
Definition: analyze.c:2491
const char * LCS_asString(LockClauseStrength strength)
Definition: analyze.c:2568
Index varlevelsup
Definition: primnodes.h:173
int errhint(const char *fmt,...)
Definition: elog.c:987
static Query * transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
Definition: analyze.c:2381
#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:1463
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
#define RELPERSISTENCE_UNLOGGED
Definition: pg_class.h:171
List * fromClause
Definition: parsenodes.h:1465
RangeTblEntry * addRangeTableEntryForJoin(ParseState *pstate, List *colnames, JoinType jointype, List *aliasvars, Alias *alias, bool inFromCl)
RangeVar * relation
Definition: parsenodes.h:1411
FromExpr * jointree
Definition: parsenodes.h:129
char * name
Definition: parsenodes.h:431
#define castNode(_type_, nodeptr)
Definition: nodes.h:575
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:1486
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:183
char * pstrdup(const char *in)
Definition: mcxt.c:1077
bool hasAggs
Definition: parsenodes.h:116
#define CURSOR_OPT_HOLD
Definition: parsenodes.h:2574
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:2186
List * list_truncate(List *list, int new_size)
Definition: list.c:350
Index tleSortGroupRef
Definition: parsenodes.h:1141
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:1303
Definition: nodes.h:506
static int count_rowexpr_columns(ParseState *pstate, Node *expr)
Definition: analyze.c:1125
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:168
bool p_hasAggs
Definition: parse_node.h:192
#define CURSOR_OPT_INSENSITIVE
Definition: parsenodes.h:2573
return result
Definition: formatting.c:1618
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:1426
static List * transformReturningList(ParseState *pstate, List *returningList)
Definition: analyze.c:2324
AclMode requiredPerms
Definition: parsenodes.h:1004
Form_pg_class rd_rel
Definition: rel.h:114
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:454
List * rowMarks
Definition: parsenodes.h:152
char * resname
Definition: primnodes.h:1354
Node * utilityStmt
Definition: parsenodes.h:111
Definition: primnodes.h:163
Node * transformLimitClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
CommonTableExpr * p_parent_cte
Definition: parse_node.h:177
void parseCheckAggregates(ParseState *pstate, Query *qry)
Definition: parse_agg.c:977
WithClause * withClause
Definition: parsenodes.h:1401
#define CURSOR_OPT_NO_SCROLL
Definition: parsenodes.h:2572
#define RELKIND_COMPOSITE_TYPE
Definition: pg_class.h:166
LockClauseStrength strength
Definition: parsenodes.h:1259
bool hasDistinctOn
Definition: parsenodes.h:120
Node * whereClause
Definition: parsenodes.h:1427
signed int int32
Definition: c.h:256
OnConflictClause * onConflictClause
Definition: parsenodes.h:1399
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:1474
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:67
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
int location
Definition: parsenodes.h:434
#define list_make1(x1)
Definition: pg_list.h:133
int location
Definition: primnodes.h:73
List * transformTargetList(ParseState *pstate, List *targetlist, ParseExprKind exprKind)
Definition: parse_target.c:131
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:384
WithClause * withClause
Definition: parsenodes.h:1415
char * relname
Definition: primnodes.h:68
Node * query
Definition: parsenodes.h:3060
uint32 AclMode
Definition: parsenodes.h:63
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:437
List * distinctClause
Definition: parsenodes.h:1461
List * returningList
Definition: parsenodes.h:1414
void CheckSelectLocking(Query *qry, LockClauseStrength strength)
Definition: analyze.c:2593
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:159
bool resjunk
Definition: primnodes.h:1359
#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:114
bool raw_expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:3240
#define lfirst_int(lc)
Definition: pg_list.h:107
Node * selectStmt
Definition: parsenodes.h:1398
Oid vartype
Definition: primnodes.h:170
List * p_windowdefs
Definition: parse_node.h:181
bool p_resolve_unknowns
Definition: parse_node.h:188
List * cols
Definition: parsenodes.h:1397
int location
Definition: primnodes.h:178
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:1376
static Query * transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
Definition: analyze.c:2467
int32 typeMod
Definition: primnodes.h:1255
List * sortClause
Definition: parsenodes.h:1485
List * exclRelTlist
Definition: primnodes.h:1483
void check_stack_depth(void)
Definition: postgres.c:3098
List * targetList
Definition: parsenodes.h:1464
int errdetail(const char *fmt,...)
Definition: elog.c:873
LockClauseStrength strength
Definition: parsenodes.h:727
AttrNumber resno
Definition: primnodes.h:1353
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:437
static Query * transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1167
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:676
bool recursive
Definition: parsenodes.h:1275
List * valuesLists
Definition: parsenodes.h:1479
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:3082
#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:1782
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:235
List * lockingClause
Definition: parsenodes.h:1488
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:767
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:247
bool inh
Definition: primnodes.h:69
Node * coerce_to_common_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *context)
List * lappend(List *list, void *datum)
Definition: list.c:128
OnConflictAction action
Definition: primnodes.h:1471
RangeTblEntry * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
Index varno
Definition: primnodes.h:166
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
#define ACL_UPDATE
Definition: parsenodes.h:67
List * transformWindowDefinitions(ParseState *pstate, List *windowdefs, List **targetlist)
LockClauseStrength
Definition: lockoptions.h:21
List * colCollations
Definition: parsenodes.h:1533
void * palloc0(Size size)
Definition: mcxt.c:878
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:1396
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
RangeTblEntry * p_target_rangetblentry
Definition: parse_node.h:179
int stmt_len
Definition: parsenodes.h:1378
void transformFromClause(ParseState *pstate, List *frmList)
Definition: parse_clause.c:112
int stmt_location
Definition: parsenodes.h:1377
unsigned int Index
Definition: c.h:365
Node * whereClause
Definition: parsenodes.h:1413
List * usingClause
Definition: parsenodes.h:1412
TupleDesc rd_att
Definition: rel.h:115
static Query * transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
Definition: analyze.c:455
List * windowClause
Definition: parsenodes.h:1469
SetOperation op
Definition: parsenodes.h:1494
#define InvalidOid
Definition: postgres_ext.h:36
int setTargetTable(ParseState *pstate, RangeVar *relation, bool inh, bool alsoSource, AclMode requiredPerms)
Definition: parse_clause.c:178
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:1008
IntoClause * into
Definition: parsenodes.h:3081
CmdType commandType
Definition: parsenodes.h:103
bool hasTargetSRFs
Definition: parsenodes.h:118
#define Max(x, y)
Definition: c.h:800
#define makeNode(_type_)
Definition: nodes.h:554
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:229
QuerySource querySource
Definition: parsenodes.h:105
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
char * aliasname
Definition: primnodes.h:42
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:187
void markTargetListOrigins(ParseState *pstate, List *targetlist)
Definition: parse_target.c:329
void parse_fixed_parameters(ParseState *pstate, Oid *paramTypes, int numParams)
Definition: parse_param.c:67
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:369
Expr * expr
Definition: primnodes.h:1352
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:1425
bool canSetTag
Definition: parsenodes.h:109
struct SelectStmt * rarg
Definition: parsenodes.h:1497
List * checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
Definition: parse_target.c:952
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:1429
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:990
SetOperation op
Definition: parsenodes.h:1524
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
LockWaitPolicy waitPolicy
Definition: parsenodes.h:1260
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
static Query * transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1541
#define UNKNOWNOID
Definition: pg_type.h:427
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:511
List * groupClause
Definition: parsenodes.h:1467
char relpersistence
Definition: primnodes.h:71
RTEKind rtekind
Definition: parsenodes.h:916
Node * arbiterWhere
Definition: primnodes.h:1476
List * cteList
Definition: parsenodes.h:126
Node * setOperations
Definition: parsenodes.h:154
Query * subquery
Definition: parsenodes.h:934
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:109
void assign_query_collations(ParseState *pstate, Query *query)
Relation p_target_relation
Definition: parse_node.h:178
Node * havingClause
Definition: parsenodes.h:1468
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:2571
bool hasForUpdate
Definition: parsenodes.h:123
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
List * onConflictSet
Definition: primnodes.h:1480
#define NameStr(name)
Definition: c.h:499
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:1489
#define elog
Definition: elog.h:219
Alias * eref
Definition: parsenodes.h:1000
static void determineRecursiveColTypes(ParseState *pstate, Node *larg, List *nrtargetlist)
Definition: analyze.c:2130
#define copyObject(obj)
Definition: nodes.h:618
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:990
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:75
Node * onConflictWhere
Definition: primnodes.h:1481
OnConflictAction action
Definition: parsenodes.h:1303
Definition: pg_list.h:45
void updateTargetListEntry(ParseState *pstate, TargetEntry *tle, char *colname, int attrno, List *indirection, int location)
Definition: parse_target.c:616
int stmt_len
Definition: parsenodes.h:172
int16 AttrNumber
Definition: attnum.h:21
LockWaitPolicy waitPolicy
Definition: parsenodes.h:728
LockWaitPolicy
Definition: lockoptions.h:36
long val
Definition: informix.c:689
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:49
char * catalogname
Definition: primnodes.h:66
WithClause * withClause
Definition: parsenodes.h:1430
List * p_joinexprs
Definition: parse_node.h:169
Node * limitCount
Definition: parsenodes.h:1487
Node * whereClause
Definition: parsenodes.h:1466
#define lfirst_oid(lc)
Definition: pg_list.h:108
void applyLockingClause(Query *qry, Index rtindex, LockClauseStrength strength, LockWaitPolicy waitPolicy, bool pushedDown)
Definition: analyze.c:2819
static List * transformInsertRow(ParseState *pstate, List *exprlist, List *stmtcols, List *icolumns, List *attrnos, bool strip_indirection)
Definition: analyze.c:886
List * p_rtable
Definition: parse_node.h:168