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