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