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