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