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