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