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