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