Age Owner 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 *
401 peter 107 GIC 545213 : parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText,
332 tgl 108 ECB : const Oid *paramTypes, int numParams,
109 : QueryEnvironment *queryEnv)
110 : {
7285 tgl 111 GIC 545213 : ParseState *pstate = make_parsestate(NULL);
5769 tgl 112 ECB : Query *query;
732 bruce 113 GIC 545213 : JumbleState *jstate = NULL;
7285 tgl 114 ECB :
5050 bruce 115 GIC 545213 : Assert(sourceText != NULL); /* required as of 8.4 */
5378 tgl 116 ECB :
6235 tgl 117 GIC 545213 : pstate->p_sourcetext = sourceText;
4908 tgl 118 ECB :
4908 tgl 119 GIC 545213 : if (numParams > 0)
401 peter 120 CBC 1781 : setup_parse_fixed_parameters(pstate, paramTypes, numParams);
7285 tgl 121 ECB :
2200 kgrittn 122 GIC 545213 : pstate->p_queryEnv = queryEnv;
2200 kgrittn 123 ECB :
4038 tgl 124 GIC 545213 : query = transformTopLevelStmt(pstate, parseTree);
7285 tgl 125 ECB :
694 alvherre 126 GIC 541749 : if (IsQueryIdEnabled())
732 bruce 127 CBC 52754 : jstate = JumbleQuery(query, sourceText);
732 bruce 128 ECB :
4030 tgl 129 GIC 541749 : if (post_parse_analyze_hook)
732 bruce 130 CBC 52749 : (*post_parse_analyze_hook) (pstate, query, jstate);
4030 tgl 131 ECB :
5769 tgl 132 GIC 541749 : free_parsestate(pstate);
7285 tgl 133 ECB :
719 bruce 134 GIC 541749 : pgstat_report_query_id(query->queryId, false);
732 bruce 135 ECB :
5769 tgl 136 GIC 541749 : return query;
7285 tgl 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 *
2276 tgl 147 GIC 4497 : parse_analyze_varparams(RawStmt *parseTree, const char *sourceText,
401 peter 148 ECB : Oid **paramTypes, int *numParams,
149 : QueryEnvironment *queryEnv)
150 : {
7285 tgl 151 GIC 4497 : ParseState *pstate = make_parsestate(NULL);
5769 tgl 152 ECB : Query *query;
732 bruce 153 GIC 4497 : JumbleState *jstate = NULL;
7285 tgl 154 ECB :
5050 bruce 155 GIC 4497 : Assert(sourceText != NULL); /* required as of 8.4 */
5378 tgl 156 ECB :
6235 tgl 157 GIC 4497 : pstate->p_sourcetext = sourceText;
4908 tgl 158 ECB :
401 peter 159 GIC 4497 : setup_parse_variable_parameters(pstate, paramTypes, numParams);
7285 tgl 160 ECB :
401 peter 161 GIC 4497 : pstate->p_queryEnv = queryEnv;
401 peter 162 ECB :
4038 tgl 163 GIC 4497 : query = transformTopLevelStmt(pstate, parseTree);
7285 tgl 164 ECB :
165 : /* make sure all is well with parameter types */
4908 tgl 166 GIC 4490 : check_variable_parameters(pstate, query);
7285 tgl 167 ECB :
694 alvherre 168 GIC 4490 : if (IsQueryIdEnabled())
732 bruce 169 CBC 107 : jstate = JumbleQuery(query, sourceText);
732 bruce 170 ECB :
4030 tgl 171 GIC 4490 : if (post_parse_analyze_hook)
732 bruce 172 CBC 107 : (*post_parse_analyze_hook) (pstate, query, jstate);
4030 tgl 173 ECB :
5769 tgl 174 GIC 4490 : free_parsestate(pstate);
7285 tgl 175 ECB :
719 bruce 176 GIC 4490 : pgstat_report_query_id(query->queryId, false);
732 bruce 177 ECB :
5769 tgl 178 GIC 4490 : return query;
7285 tgl 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 *
396 peter 188 GIC 23262 : parse_analyze_withcb(RawStmt *parseTree, const char *sourceText,
396 peter 189 ECB : ParserSetupHook parserSetup,
190 : void *parserSetupArg,
191 : QueryEnvironment *queryEnv)
192 : {
396 peter 193 GIC 23262 : ParseState *pstate = make_parsestate(NULL);
396 peter 194 ECB : Query *query;
396 peter 195 GIC 23262 : JumbleState *jstate = NULL;
396 peter 196 ECB :
396 peter 197 GIC 23262 : Assert(sourceText != NULL); /* required as of 8.4 */
396 peter 198 ECB :
396 peter 199 GIC 23262 : pstate->p_sourcetext = sourceText;
396 peter 200 CBC 23262 : pstate->p_queryEnv = queryEnv;
201 23262 : (*parserSetup) (pstate, parserSetupArg);
396 peter 202 ECB :
396 peter 203 GIC 23262 : query = transformTopLevelStmt(pstate, parseTree);
396 peter 204 ECB :
396 peter 205 GIC 23208 : if (IsQueryIdEnabled())
396 peter 206 CBC 5051 : jstate = JumbleQuery(query, sourceText);
396 peter 207 ECB :
396 peter 208 GIC 23208 : if (post_parse_analyze_hook)
396 peter 209 CBC 5051 : (*post_parse_analyze_hook) (pstate, query, jstate);
396 peter 210 ECB :
396 peter 211 GIC 23208 : free_parsestate(pstate);
396 peter 212 ECB :
396 peter 213 GIC 23208 : pgstat_report_query_id(query->queryId, false);
396 peter 214 ECB :
396 peter 215 GIC 23208 : return query;
396 peter 216 ECB : }
217 :
218 :
219 : /*
220 : * parse_sub_analyze
221 : * Entry point for recursively analyzing a sub-statement.
222 : */
223 : Query *
4960 tgl 224 GIC 71868 : parse_sub_analyze(Node *parseTree, ParseState *parentParseState,
4912 tgl 225 ECB : CommonTableExpr *parentCTE,
226 : bool locked_from_parent,
227 : bool resolve_unknowns)
228 : {
8219 tgl 229 GIC 71868 : ParseState *pstate = make_parsestate(parentParseState);
7712 tgl 230 ECB : Query *query;
231 :
4960 tgl 232 GIC 71868 : pstate->p_parent_cte = parentCTE;
4912 tgl 233 CBC 71868 : pstate->p_locked_from_parent = locked_from_parent;
2265 234 71868 : pstate->p_resolve_unknowns = resolve_unknowns;
4960 tgl 235 ECB :
5769 tgl 236 GIC 71868 : query = transformStmt(pstate, parseTree);
8665 tgl 237 ECB :
5769 tgl 238 GIC 71765 : free_parsestate(pstate);
9210 bruce 239 ECB :
5769 tgl 240 GIC 71765 : return query;
8244 tgl 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 *
2276 tgl 251 GIC 578507 : transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
2276 tgl 252 ECB : {
253 : Query *result;
254 :
255 : /* We're at top level, so allow SELECT INTO */
2276 tgl 256 GIC 578507 : result = transformOptionalSelectInto(pstate, parseTree->stmt);
2276 tgl 257 ECB :
2276 tgl 258 GIC 574975 : result->stmt_location = parseTree->stmt_location;
2276 tgl 259 CBC 574975 : result->stmt_len = parseTree->stmt_len;
2276 tgl 260 ECB :
2276 tgl 261 GIC 574975 : return result;
2276 tgl 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 *
2276 tgl 275 GIC 588440 : transformOptionalSelectInto(ParseState *pstate, Node *parseTree)
4038 tgl 276 ECB : {
4038 tgl 277 GIC 588440 : if (IsA(parseTree, SelectStmt))
4038 tgl 278 ECB : {
4038 tgl 279 GIC 188982 : SelectStmt *stmt = (SelectStmt *) parseTree;
4038 tgl 280 ECB :
281 : /* If it's a set-operation tree, drill down to leftmost SelectStmt */
4038 tgl 282 GIC 198020 : while (stmt && stmt->op != SETOP_NONE)
4038 tgl 283 CBC 9038 : stmt = stmt->larg;
1058 284 188982 : Assert(stmt && IsA(stmt, SelectStmt) && stmt->larg == NULL);
4038 tgl 285 ECB :
4038 tgl 286 GIC 188982 : if (stmt->intoClause)
4038 tgl 287 ECB : {
4038 tgl 288 GIC 49 : CreateTableAsStmt *ctas = makeNode(CreateTableAsStmt);
4038 tgl 289 ECB :
4038 tgl 290 GIC 49 : ctas->query = parseTree;
4038 tgl 291 CBC 49 : ctas->into = stmt->intoClause;
1002 michael 292 49 : ctas->objtype = OBJECT_TABLE;
4038 tgl 293 49 : ctas->is_select_into = true;
4038 tgl 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 : */
4038 tgl 300 GIC 49 : stmt->intoClause = NULL;
4038 tgl 301 ECB :
4038 tgl 302 GIC 49 : parseTree = (Node *) ctas;
4038 tgl 303 ECB : }
304 : }
305 :
4038 tgl 306 GIC 588440 : return transformStmt(pstate, parseTree);
4038 tgl 307 ECB : }
308 :
309 : /*
310 : * transformStmt -
311 : * recursively transform a Parse tree into a Query tree.
312 : */
313 : Query *
5769 tgl 314 GIC 686214 : transformStmt(ParseState *pstate, Node *parseTree)
9770 scrappy 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 :
9345 bruce 338 GIC 686214 : switch (nodeTag(parseTree))
9345 bruce 339 ECB : {
340 : /*
341 : * Optimizable statements
342 : */
9221 bruce 343 GIC 42925 : case T_InsertStmt:
5769 tgl 344 CBC 42925 : result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
9344 bruce 345 42242 : break;
9345 bruce 346 ECB :
9344 bruce 347 GIC 2043 : case T_DeleteStmt:
9344 bruce 348 CBC 2043 : result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
349 2016 : break;
9345 bruce 350 ECB :
9221 bruce 351 GIC 7521 : case T_UpdateStmt:
9221 bruce 352 CBC 7521 : result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
9344 353 7481 : break;
9345 bruce 354 ECB :
377 alvherre 355 GIC 504 : case T_MergeStmt:
377 alvherre 356 CBC 504 : result = transformMergeStmt(pstate, (MergeStmt *) parseTree);
357 468 : break;
377 alvherre 358 ECB :
9221 bruce 359 GIC 271222 : case T_SelectStmt:
6094 mail 360 ECB : {
6094 mail 361 GIC 271222 : SelectStmt *n = (SelectStmt *) parseTree;
6094 mail 362 ECB :
6094 mail 363 GIC 271222 : if (n->valuesLists)
6094 mail 364 CBC 2539 : result = transformValuesClause(pstate, n);
365 268683 : else if (n->op == SETOP_NONE)
366 259514 : result = transformSelectStmt(pstate, n);
6094 mail 367 ECB : else
6094 mail 368 GIC 9169 : result = transformSetOperationStmt(pstate, n);
6094 mail 369 ECB : }
9344 bruce 370 GIC 268392 : break;
9345 bruce 371 ECB :
732 peter 372 GIC 14882 : case T_ReturnStmt:
732 peter 373 CBC 14882 : result = transformReturnStmt(pstate, (ReturnStmt *) parseTree);
374 14879 : break;
732 peter 375 ECB :
825 tgl 376 GIC 2361 : case T_PLAssignStmt:
825 tgl 377 CBC 2361 : result = transformPLAssignStmt(pstate,
825 tgl 378 ECB : (PLAssignStmt *) parseTree);
825 tgl 379 GIC 2348 : break;
825 tgl 380 ECB :
381 : /*
382 : * Special cases
383 : */
5826 tgl 384 GIC 1375 : case T_DeclareCursorStmt:
5826 tgl 385 CBC 1375 : result = transformDeclareCursorStmt(pstate,
2118 tgl 386 ECB : (DeclareCursorStmt *) parseTree);
5826 tgl 387 GIC 1364 : break;
5826 tgl 388 ECB :
5826 tgl 389 GIC 9933 : case T_ExplainStmt:
5826 tgl 390 CBC 9933 : result = transformExplainStmt(pstate,
5826 tgl 391 ECB : (ExplainStmt *) parseTree);
5826 tgl 392 GIC 9930 : break;
5826 tgl 393 ECB :
4038 tgl 394 GIC 944 : case T_CreateTableAsStmt:
4038 tgl 395 CBC 944 : result = transformCreateTableAsStmt(pstate,
2118 tgl 396 ECB : (CreateTableAsStmt *) parseTree);
4038 tgl 397 GIC 944 : break;
4038 tgl 398 ECB :
1874 peter_e 399 GIC 208 : case T_CallStmt:
1874 peter_e 400 CBC 208 : result = transformCallStmt(pstate,
1874 peter_e 401 ECB : (CallStmt *) parseTree);
1847 peter_e 402 GIC 193 : break;
1874 peter_e 403 ECB :
9344 bruce 404 GIC 332296 : default:
9345 bruce 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 : */
9344 bruce 410 GIC 332296 : result = makeNode(Query);
9344 bruce 411 CBC 332296 : result->commandType = CMD_UTILITY;
412 332296 : result->utilityStmt = (Node *) parseTree;
413 332296 : break;
9345 bruce 414 ECB : }
415 :
416 : /* Mark as original query until we learn differently */
7282 tgl 417 GIC 682553 : result->querySource = QSRC_ORIGINAL;
7282 tgl 418 CBC 682553 : result->canSetTag = true;
7282 tgl 419 ECB :
9345 bruce 420 GIC 682553 : return result;
9770 scrappy 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
2276 tgl 431 GIC 487811 : analyze_requires_snapshot(RawStmt *parseTree)
5230 tgl 432 ECB : {
433 : bool result;
434 :
2276 tgl 435 GIC 487811 : switch (nodeTag(parseTree->stmt))
5230 tgl 436 ECB : {
437 : /*
438 : * Optimizable statements
439 : */
5230 tgl 440 GIC 152772 : case T_InsertStmt:
5230 tgl 441 ECB : case T_DeleteStmt:
442 : case T_UpdateStmt:
443 : case T_MergeStmt:
444 : case T_SelectStmt:
445 : case T_PLAssignStmt:
5230 tgl 446 GIC 152772 : result = true;
5230 tgl 447 CBC 152772 : break;
5230 tgl 448 ECB :
449 : /*
450 : * Special cases
451 : */
5230 tgl 452 GIC 8476 : case T_DeclareCursorStmt:
5230 tgl 453 ECB : case T_ExplainStmt:
454 : case T_CreateTableAsStmt:
455 : /* yes, because we must analyze the contained statement */
5230 tgl 456 GIC 8476 : result = true;
5230 tgl 457 CBC 8476 : break;
5230 tgl 458 ECB :
5230 tgl 459 GIC 326563 : default:
4832 tgl 460 ECB : /* other utility statements don't have any real parse analysis */
5230 tgl 461 GIC 326563 : result = false;
5230 tgl 462 CBC 326563 : break;
5230 tgl 463 ECB : }
464 :
5230 tgl 465 GIC 487811 : return result;
5230 tgl 466 ECB : }
467 :
468 : /*
469 : * transformDeleteStmt -
470 : * transforms a Delete Statement
471 : */
472 : static Query *
9344 bruce 473 GIC 2043 : transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
9770 scrappy 474 ECB : {
9344 bruce 475 GIC 2043 : Query *qry = makeNode(Query);
3379 tgl 476 ECB : ParseNamespaceItem *nsitem;
477 : Node *qual;
478 :
9345 bruce 479 GIC 2043 : qry->commandType = CMD_DELETE;
9770 scrappy 480 ECB :
481 : /* process the WITH clause independently of all else */
4559 tgl 482 GIC 2043 : if (stmt->withClause)
4559 tgl 483 ECB : {
4559 tgl 484 GIC 14 : qry->hasRecursive = stmt->withClause->recursive;
4559 tgl 485 CBC 14 : qry->cteList = transformWithClause(pstate, stmt->withClause);
4426 486 14 : qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
4559 tgl 487 ECB : }
488 :
489 : /* set up range table with just the result rel */
7688 tgl 490 GIC 4083 : qry->resultRelation = setTargetTable(pstate, stmt->relation,
2298 tgl 491 CBC 2043 : stmt->relation->inh,
7025 tgl 492 ECB : true,
493 : ACL_DELETE);
1193 tgl 494 GIC 2040 : nsitem = pstate->p_target_nsitem;
3379 tgl 495 ECB :
496 : /* there's no DISTINCT in DELETE */
8473 tgl 497 GIC 2040 : qry->distinctClause = NIL;
9770 scrappy 498 ECB :
499 : /* subqueries in USING cannot access the result relation */
3379 tgl 500 GIC 2040 : nsitem->p_lateral_only = true;
3375 tgl 501 CBC 2040 : nsitem->p_lateral_ok = false;
3379 tgl 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 : */
6576 neilc 509 GIC 2040 : transformFromClause(pstate, stmt->usingClause);
6576 neilc 510 ECB :
511 : /* remaining clauses can reference the result relation normally */
3379 tgl 512 GIC 2031 : nsitem->p_lateral_only = false;
3375 tgl 513 CBC 2031 : nsitem->p_lateral_ok = true;
3379 tgl 514 ECB :
3894 tgl 515 GIC 2031 : qual = transformWhereClause(pstate, stmt->whereClause,
3894 tgl 516 ECB : EXPR_KIND_WHERE, "WHERE");
517 :
6084 tgl 518 GIC 2019 : qry->returningList = transformReturningList(pstate, stmt->returningList);
6084 tgl 519 ECB :
520 : /* done building the range table and jointree */
9345 bruce 521 GIC 2016 : qry->rtable = pstate->p_rtable;
124 alvherre 522 GNC 2016 : qry->rteperminfos = pstate->p_rteperminfos;
8227 tgl 523 CBC 2016 : qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
9345 bruce 524 ECB :
8546 tgl 525 CBC 2016 : qry->hasSubLinks = pstate->p_hasSubLinks;
5215 tgl 526 GIC 2016 : qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
2399 tgl 527 CBC 2016 : qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
4078 528 2016 : qry->hasAggs = pstate->p_hasAggs;
9770 scrappy 529 ECB :
4404 tgl 530 CBC 2016 : assign_query_collations(pstate, qry);
531 :
1543 rhodiumtoad 532 ECB : /* this must be done after collations, for reliable comparison of exprs */
1543 rhodiumtoad 533 GIC 2016 : if (pstate->p_hasAggs)
1543 rhodiumtoad 534 UIC 0 : parseCheckAggregates(pstate, qry);
1543 rhodiumtoad 535 ECB :
8221 tgl 536 GBC 2016 : return qry;
537 : }
9770 scrappy 538 ECB :
539 : /*
540 : * transformInsertStmt -
541 : * transform an Insert Statement
542 : */
543 : static Query *
5769 tgl 544 GIC 42925 : transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
545 : {
8665 tgl 546 CBC 42925 : Query *qry = makeNode(Query);
6094 mail 547 GIC 42925 : SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
6094 mail 548 CBC 42925 : List *exprList = NIL;
6094 mail 549 ECB : bool isGeneralSelect;
8089 tgl 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 */
4559 tgl 564 GIC 42925 : Assert(pstate->p_ctenamespace == NIL);
565 :
9345 bruce 566 42925 : qry->commandType = CMD_INSERT;
9345 bruce 567 CBC 42925 : pstate->p_is_insert = true;
568 :
4559 tgl 569 ECB : /* process the WITH clause independently of all else */
4559 tgl 570 CBC 42925 : if (stmt->withClause)
571 : {
4559 tgl 572 GIC 392 : qry->hasRecursive = stmt->withClause->recursive;
4559 tgl 573 CBC 392 : qry->cteList = transformWithClause(pstate, stmt->withClause);
4426 tgl 574 GIC 392 : qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
4559 tgl 575 ECB : }
576 :
2194 peter_e 577 CBC 42925 : qry->override = stmt->override;
578 :
2893 andres 579 GIC 43658 : isOnConflictUpdate = (stmt->onConflictClause &&
2118 tgl 580 CBC 733 : stmt->onConflictClause->action == ONCONFLICT_UPDATE);
581 :
6094 mail 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 : */
4572 tgl 591 GIC 79679 : isGeneralSelect = (selectStmt && (selectStmt->valuesLists == NIL ||
592 36754 : selectStmt->sortClause != NIL ||
593 36754 : selectStmt->limitOffset != NULL ||
4572 tgl 594 CBC 36754 : selectStmt->limitCount != NULL ||
595 36754 : selectStmt->lockingClause != NIL ||
596 36754 : selectStmt->withClause != NULL));
6094 mail 597 ECB :
8187 tgl 598 : /*
8089 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 : */
6094 mail 607 GIC 42925 : if (isGeneralSelect)
608 : {
8089 tgl 609 5805 : sub_rtable = pstate->p_rtable;
8089 tgl 610 CBC 5805 : pstate->p_rtable = NIL;
124 alvherre 611 GNC 5805 : sub_rteperminfos = pstate->p_rteperminfos;
612 5805 : pstate->p_rteperminfos = NIL;
3896 tgl 613 GIC 5805 : sub_namespace = pstate->p_namespace;
3896 tgl 614 CBC 5805 : pstate->p_namespace = NIL;
8089 tgl 615 ECB : }
616 : else
617 : {
8089 tgl 618 CBC 37120 : sub_rtable = NIL; /* not used, but keep compiler quiet */
103 tgl 619 GNC 37120 : sub_rteperminfos = NIL;
3896 tgl 620 CBC 37120 : sub_namespace = NIL;
621 : }
622 :
623 : /*
6385 bruce 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 : */
2893 andres 629 GIC 42925 : targetPerms = ACL_INSERT;
630 42925 : if (isOnConflictUpdate)
631 572 : targetPerms |= ACL_UPDATE;
7688 tgl 632 42925 : qry->resultRelation = setTargetTable(pstate, stmt->relation,
633 : false, false, targetPerms);
634 :
6094 mail 635 ECB : /* Validate stmt->cols list, or build default list if no list given */
6094 mail 636 CBC 42916 : icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
637 42892 : Assert(list_length(icolumns) == list_length(attrnos));
6094 mail 638 ECB :
639 : /*
640 : * Determine which variant of INSERT we have.
641 : */
6094 mail 642 CBC 42892 : if (selectStmt == NULL)
6094 mail 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 : */
6094 mail 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
6385 bruce 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 : */
7285 tgl 660 GIC 5805 : ParseState *sub_pstate = make_parsestate(pstate);
661 : Query *selectQuery;
662 :
663 : /*
664 : * Process the source SELECT.
665 : *
6385 bruce 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 : */
8089 tgl 677 GIC 5805 : sub_pstate->p_rtable = sub_rtable;
124 alvherre 678 GNC 5805 : sub_pstate->p_rteperminfos = sub_rteperminfos;
5050 bruce 679 GIC 5805 : sub_pstate->p_joinexprs = NIL; /* sub_rtable has no joins */
69 tgl 680 GNC 5805 : sub_pstate->p_nullingrels = NIL;
3896 tgl 681 GIC 5805 : sub_pstate->p_namespace = sub_namespace;
2265 682 5805 : sub_pstate->p_resolve_unknowns = false;
683 :
5769 684 5805 : selectQuery = transformStmt(sub_pstate, stmt->selectStmt);
8089 tgl 685 ECB :
5769 tgl 686 CBC 5802 : free_parsestate(sub_pstate);
8221 tgl 687 ECB :
4038 688 : /* The grammar should have produced a SELECT */
5333 tgl 689 CBC 5802 : if (!IsA(selectQuery, Query) ||
2276 690 5802 : selectQuery->commandType != CMD_SELECT)
5333 tgl 691 UIC 0 : elog(ERROR, "unexpected non-SELECT command in INSERT ... SELECT");
8053 bruce 692 ECB :
693 : /*
6385 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 : */
1193 tgl 697 CBC 5802 : nsitem = addRangeTableEntryForSubquery(pstate,
1193 tgl 698 ECB : selectQuery,
1193 tgl 699 EUB : makeAlias("*SELECT*", NIL),
700 : false,
701 : false);
1193 tgl 702 GIC 5802 : addNSItemToQuery(pstate, nsitem, true, false, false);
703 :
704 : /*----------
6094 mail 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 : *
6577 tgl 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 : */
6094 mail 718 GIC 5802 : exprList = NIL;
719 26790 : foreach(lc, selectQuery->targetList)
720 : {
721 20988 : TargetEntry *tle = (TargetEntry *) lfirst(lc);
722 : Expr *expr;
723 :
6577 tgl 724 20988 : if (tle->resjunk)
8221 725 36 : continue;
7285 tgl 726 CBC 20952 : if (tle->expr &&
1058 727 27932 : (IsA(tle->expr, Const) || IsA(tle->expr, Param)) &&
7285 tgl 728 GIC 6980 : exprType((Node *) tle->expr) == UNKNOWNOID)
8221 tgl 729 CBC 2953 : expr = tle->expr;
730 : else
731 : {
1193 732 17999 : Var *var = makeVarFromTargetEntry(nsitem->p_rtindex, tle);
5050 bruce 733 ECB :
5297 tgl 734 CBC 17999 : var->location = exprLocation((Node *) tle->expr);
735 17999 : expr = (Expr *) var;
5297 tgl 736 ECB : }
6094 mail 737 CBC 20952 : exprList = lappend(exprList, expr);
738 : }
739 :
6094 mail 740 ECB : /* Prepare row for assignment to target table */
6094 mail 741 GIC 5802 : exprList = transformInsertRow(pstate, exprList,
6094 mail 742 ECB : stmt->cols,
2440 tgl 743 : icolumns, attrnos,
744 : false);
8221 745 : }
6094 mail 746 GIC 36721 : else if (list_length(selectStmt->valuesLists) > 1)
747 : {
748 : /*
6031 bruce 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 : */
6094 mail 754 CBC 2000 : List *exprsLists = NIL;
2313 tgl 755 GIC 2000 : List *coltypes = NIL;
756 2000 : List *coltypmods = NIL;
757 2000 : List *colcollations = NIL;
6094 mail 758 2000 : int sublist_length = -1;
3885 tgl 759 2000 : bool lateral = false;
760 :
4038 761 2000 : Assert(selectStmt->intoClause == NULL);
4038 tgl 762 ECB :
6094 mail 763 CBC 78690 : foreach(lc, selectStmt->valuesLists)
6094 mail 764 ECB : {
6031 bruce 765 CBC 76690 : List *sublist = (List *) lfirst(lc);
6094 mail 766 ECB :
2329 tgl 767 : /*
768 : * Do basic expression transformation (same as a ROW() expr, but
769 : * allow SetToDefault at top level)
770 : */
2329 tgl 771 CBC 76690 : sublist = transformExpressionList(pstate, sublist,
772 : EXPR_KIND_VALUES, true);
6094 mail 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 : */
6094 mail 779 CBC 76690 : if (sublist_length < 0)
780 : {
781 : /* Remember post-transformation length of first sublist */
6094 mail 782 GIC 2000 : sublist_length = list_length(sublist);
783 : }
784 74690 : else if (sublist_length != list_length(sublist))
785 : {
6094 mail 786 UIC 0 : ereport(ERROR,
6094 mail 787 ECB : (errcode(ERRCODE_SYNTAX_ERROR),
788 : errmsg("VALUES lists must all be the same length"),
789 : parser_errposition(pstate,
5333 tgl 790 : exprLocation((Node *) sublist))));
791 : }
6094 mail 792 :
793 : /*
2440 tgl 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 : */
6094 mail 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
4404 tgl 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 : */
4404 tgl 820 GIC 76690 : assign_list_collations(pstate, sublist);
821 :
6094 mail 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
2313 tgl 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 : */
2313 tgl 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 : }
4374 tgl 840 ECB :
841 : /*
3885 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.
6094 mail 846 : */
6094 tgl 847 GIC 2011 : if (list_length(pstate->p_rtable) != 1 &&
848 11 : contain_vars_of_level((Node *) exprsLists, 0))
3885 849 11 : lateral = true;
850 :
851 : /*
852 : * Generate the VALUES RTE
853 : */
1193 854 2000 : nsitem = addRangeTableEntryForValues(pstate, exprsLists,
1193 tgl 855 ECB : coltypes, coltypmods, colcollations,
856 : NULL, lateral, true);
1193 tgl 857 CBC 2000 : addNSItemToQuery(pstate, nsitem, true, false, false);
858 :
859 : /*
860 : * Generate list of Vars referencing the RTE
861 : */
69 tgl 862 GNC 2000 : exprList = expandNSItemVars(pstate, nsitem, 0, -1, NULL);
863 :
864 : /*
2440 tgl 865 ECB : * Re-apply any indirection on the target column specs to the Vars
866 : */
2440 tgl 867 GIC 2000 : exprList = transformInsertRow(pstate, exprList,
868 : stmt->cols,
869 : icolumns, attrnos,
2440 tgl 870 ECB : false);
871 : }
872 : else
873 : {
874 : /*
3260 bruce 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 : */
6094 mail 880 GIC 34721 : List *valuesLists = selectStmt->valuesLists;
881 :
882 34721 : Assert(list_length(valuesLists) == 1);
4038 tgl 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)
2329 tgl 888 ECB : */
6094 mail 889 GIC 34721 : exprList = transformExpressionList(pstate,
3894 tgl 890 CBC 34721 : (List *) linitial(valuesLists),
2274 tgl 891 ECB : EXPR_KIND_VALUES_SINGLE,
892 : true);
893 :
894 : /* Prepare row for assignment to target table */
6094 mail 895 GIC 34709 : exprList = transformInsertRow(pstate, exprList,
896 : stmt->cols,
2440 tgl 897 ECB : icolumns, attrnos,
898 : false);
899 : }
900 :
901 : /*
902 : * Generate query's target list using the computed list of expressions.
5190 903 : * Also, mark all the target columns as needing insert permissions.
904 : */
124 alvherre 905 GNC 42269 : perminfo = pstate->p_target_nsitem->p_perminfo;
6094 mail 906 GIC 42269 : qry->targetList = NIL;
1501 tgl 907 42269 : Assert(list_length(exprList) <= list_length(icolumns));
908 170207 : forthree(lc, exprList, icols, icolumns, attnos, attrnos)
909 : {
6031 bruce 910 127938 : Expr *expr = (Expr *) lfirst(lc);
1501 tgl 911 127938 : ResTarget *col = lfirst_node(ResTarget, icols);
912 127938 : AttrNumber attr_num = (AttrNumber) lfirst_int(attnos);
6094 mail 913 ECB : TargetEntry *tle;
7418 tgl 914 :
6094 mail 915 CBC 127938 : tle = makeTargetEntry(expr,
5190 tgl 916 ECB : attr_num,
917 : col->name,
6094 mail 918 : false);
6094 mail 919 CBC 127938 : qry->targetList = lappend(qry->targetList, tle);
7674 bruce 920 ECB :
124 alvherre 921 GNC 127938 : perminfo->insertedCols = bms_add_member(perminfo->insertedCols,
922 : attr_num - FirstLowInvalidHeapAttributeNumber);
8665 tgl 923 ECB : }
924 :
925 : /*
926 : * If we have any clauses yet to process, set the query namespace to
726 927 : * contain only the target relation, removing any entries added in a
928 : * sub-SELECT or VALUES list.
6084 929 : */
726 tgl 930 GIC 42269 : if (stmt->onConflictClause || stmt->returningList)
931 : {
3896 932 1171 : pstate->p_namespace = NIL;
1193 933 1171 : addNSItemToQuery(pstate, pstate->p_target_nsitem,
934 : false, true, true);
935 : }
936 :
937 : /* Process ON CONFLICT, if any. */
726 tgl 938 CBC 42269 : if (stmt->onConflictClause)
726 tgl 939 GIC 733 : qry->onConflict = transformOnConflictClause(pstate,
726 tgl 940 ECB : stmt->onConflictClause);
941 :
942 : /* Process RETURNING, if any. */
726 tgl 943 GIC 42251 : if (stmt->returningList)
6084 944 573 : qry->returningList = transformReturningList(pstate,
945 : stmt->returningList);
6084 tgl 946 ECB :
8221 947 : /* done building the range table and jointree */
8221 tgl 948 GIC 42242 : qry->rtable = pstate->p_rtable;
124 alvherre 949 GNC 42242 : qry->rteperminfos = pstate->p_rteperminfos;
5769 tgl 950 GIC 42242 : qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
951 :
2399 tgl 952 CBC 42242 : qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
5769 953 42242 : qry->hasSubLinks = pstate->p_hasSubLinks;
954 :
4404 tgl 955 GIC 42242 : assign_query_collations(pstate, qry);
956 :
5769 tgl 957 CBC 42242 : return qry;
5769 tgl 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
2440 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 *
5769 tgl 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 :
9000 scrappy 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 : */
5769 tgl 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))
4586 tgl 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
4382 bruce 1003 : * mismatch, which is less misleading so we don't worry about giving a
1004 : * hint in that case.)
1005 : */
5769 tgl 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,
2118 tgl 1015 ECB : list_length(exprlist))))));
1016 : }
1017 :
1018 : /*
1019 : * Prepare columns for assignment to target table.
1020 : */
5769 tgl 1021 GIC 119454 : result = NIL;
1501 1022 330996 : forthree(lc, exprlist, icols, icolumns, attnos, attrnos)
1023 : {
5769 1024 212132 : Expr *expr = (Expr *) lfirst(lc);
1501 1025 212132 : ResTarget *col = lfirst_node(ResTarget, icols);
1026 212132 : int attno = lfirst_int(attnos);
1027 :
5769 1028 212132 : expr = transformAssignedExpr(pstate, expr,
1029 : EXPR_KIND_INSERT_TARGET,
5769 tgl 1030 CBC 212132 : col->name,
1501 tgl 1031 ECB : attno,
1032 : col->indirection,
5769 1033 : col->location);
8244 1034 :
2440 tgl 1035 CBC 211542 : if (strip_indirection)
1036 : {
1037 83122 : while (expr)
1038 : {
1039 83122 : if (IsA(expr, FieldStore))
1040 : {
2440 tgl 1041 GIC 48 : FieldStore *fstore = (FieldStore *) expr;
1042 :
1043 48 : expr = (Expr *) linitial(fstore->newvals);
2440 tgl 1044 ECB : }
1528 alvherre 1045 GIC 83074 : else if (IsA(expr, SubscriptingRef))
2440 tgl 1046 ECB : {
1528 alvherre 1047 GIC 96 : SubscriptingRef *sbsref = (SubscriptingRef *) expr;
2440 tgl 1048 ECB :
1528 alvherre 1049 GIC 96 : if (sbsref->refassgnexpr == NULL)
2440 tgl 1050 LBC 0 : break;
1051 :
1528 alvherre 1052 CBC 96 : expr = sbsref->refassgnexpr;
1053 : }
2440 tgl 1054 ECB : else
2440 tgl 1055 GIC 82978 : break;
2440 tgl 1056 ECB : }
1057 : }
1058 :
5769 tgl 1059 GBC 211542 : result = lappend(result, expr);
1060 : }
9770 scrappy 1061 ECB :
5769 tgl 1062 GIC 118864 : return result;
1063 : }
9770 scrappy 1064 ECB :
1065 : /*
1066 : * transformOnConflictClause -
1067 : * transforms an OnConflictClause in an INSERT
2893 andres 1068 : */
1069 : static OnConflictExpr *
2893 andres 1070 GIC 733 : transformOnConflictClause(ParseState *pstate,
2893 andres 1071 ECB : OnConflictClause *onConflictClause)
1072 : {
726 tgl 1073 GIC 733 : ParseNamespaceItem *exclNSItem = NULL;
1074 : List *arbiterElems;
1075 : Node *arbiterWhere;
1076 : Oid arbiterConstraint;
2893 andres 1077 733 : List *onConflictSet = NIL;
1078 733 : Node *onConflictWhere = NULL;
2893 andres 1079 CBC 733 : int exclRelIndex = 0;
2893 andres 1080 GIC 733 : List *exclRelTlist = NIL;
1081 : OnConflictExpr *result;
2893 andres 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
726 tgl 1086 : * processing arbiter expressions. (You can't actually reference it from
1087 : * there, but this provides a useful error message if you try.)
1088 : */
2893 andres 1089 CBC 733 : if (onConflictClause->action == ONCONFLICT_UPDATE)
1090 : {
2745 andres 1091 GIC 572 : Relation targetrel = pstate->p_target_relation;
1092 : RangeTblEntry *exclRte;
1093 :
1193 tgl 1094 572 : exclNSItem = addRangeTableEntryForRelation(pstate,
1095 : targetrel,
1096 : RowExclusiveLock,
1097 : makeAlias("excluded", NIL),
1193 tgl 1098 ECB : false, false);
1193 tgl 1099 GIC 572 : exclRte = exclNSItem->p_rte;
1193 tgl 1100 CBC 572 : exclRelIndex = exclNSItem->p_rtindex;
1101 :
1102 : /*
726 tgl 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 : */
2745 andres 1107 GIC 572 : exclRte->relkind = RELKIND_COMPOSITE_TYPE;
1108 :
1109 : /* Create EXCLUDED rel's targetlist for use by EXPLAIN */
1709 tgl 1110 572 : exclRelTlist = BuildOnConflictExcludedTargetlist(targetrel,
1111 : exclRelIndex);
1112 : }
1113 :
726 tgl 1114 ECB : /* Process the arbiter clause, ON CONFLICT ON (...) */
726 tgl 1115 GIC 733 : transformOnConflictArbiter(pstate, onConflictClause, &arbiterElems,
1116 : &arbiterWhere, &arbiterConstraint);
726 tgl 1117 ECB :
1118 : /* Process DO UPDATE */
726 tgl 1119 GIC 727 : if (onConflictClause->action == ONCONFLICT_UPDATE)
1120 : {
1121 : /*
726 tgl 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 : */
726 tgl 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 : */
1193 tgl 1132 GIC 566 : addNSItemToQuery(pstate, exclNSItem, false, true, true);
2893 andres 1133 ECB :
1134 : /*
1135 : * Now transform the UPDATE subexpressions.
1136 : */
1137 : onConflictSet =
2893 andres 1138 GIC 566 : transformUpdateTargetList(pstate, onConflictClause->targetList);
2893 andres 1139 ECB :
2893 andres 1140 GIC 554 : onConflictWhere = transformWhereClause(pstate,
1141 : onConflictClause->whereClause,
1142 : EXPR_KIND_WHERE, "WHERE");
1143 :
1144 : /*
726 tgl 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 : */
726 tgl 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 */
2893 andres 1154 715 : result = makeNode(OnConflictExpr);
1155 :
2893 andres 1156 CBC 715 : result->action = onConflictClause->action;
1157 715 : result->arbiterElems = arbiterElems;
2893 andres 1158 GIC 715 : result->arbiterWhere = arbiterWhere;
1159 715 : result->constraint = arbiterConstraint;
1160 715 : result->onConflictSet = onConflictSet;
2893 andres 1161 CBC 715 : result->onConflictWhere = onConflictWhere;
2893 andres 1162 GIC 715 : result->exclRelIndex = exclRelIndex;
2893 andres 1163 CBC 715 : result->exclRelTlist = exclRelTlist;
2893 andres 1164 ECB :
2893 andres 1165 CBC 715 : return result;
2893 andres 1166 ECB : }
1167 :
1168 :
1709 tgl 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 *
1709 tgl 1177 GIC 644 : BuildOnConflictExcludedTargetlist(Relation targetrel,
1178 : Index exclRelIndex)
1179 : {
1180 644 : List *result = NIL;
1181 : int attno;
1182 : Var *var;
1183 : TargetEntry *te;
1709 tgl 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 : */
1709 tgl 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 : {
1709 tgl 1196 ECB : /*
1197 : * can't use atttypid here, but it doesn't really matter what type
1198 : * the Const claims to be.
1199 : */
1709 tgl 1200 GIC 32 : var = (Var *) makeNullConst(INT4OID, -1, InvalidOid);
1664 tgl 1201 CBC 32 : name = NULL;
1202 : }
1203 : else
1204 : {
1709 tgl 1205 GIC 1643 : var = makeVar(exclRelIndex, attno + 1,
1206 : attr->atttypid, attr->atttypmod,
1709 tgl 1207 ECB : attr->attcollation,
1208 : 0);
1709 tgl 1209 GIC 1643 : name = pstrdup(NameStr(attr->attname));
1210 : }
1211 :
1709 tgl 1212 CBC 1675 : te = makeTargetEntry((Expr *) var,
1709 tgl 1213 GIC 1675 : attno + 1,
1214 : name,
1215 : false);
1709 tgl 1216 ECB :
1709 tgl 1217 GIC 1675 : result = lappend(result, te);
1218 : }
1709 tgl 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 : */
1709 tgl 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;
1709 tgl 1234 ECB : }
1235 :
1236 :
4586 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
4586 tgl 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))
4586 tgl 1254 EUB : {
4586 tgl 1255 UIC 0 : Var *var = (Var *) expr;
4586 tgl 1256 UBC 0 : AttrNumber attnum = var->varattno;
4586 tgl 1257 EUB :
4586 tgl 1258 UBC 0 : if (attnum > 0 && var->vartype == RECORDOID)
4586 tgl 1259 EUB : {
1260 : RangeTblEntry *rte;
1261 :
4586 tgl 1262 UBC 0 : rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
1263 0 : if (rte->rtekind == RTE_SUBQUERY)
1264 : {
4586 tgl 1265 EUB : /* Subselect-in-FROM: examine sub-select's output expr */
4586 tgl 1266 UIC 0 : TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
1267 : attnum);
1268 :
4586 tgl 1269 UBC 0 : if (ste == NULL || ste->resjunk)
1270 0 : return -1;
4586 tgl 1271 UIC 0 : expr = (Node *) ste->expr;
1272 0 : if (IsA(expr, RowExpr))
4586 tgl 1273 UBC 0 : return list_length(((RowExpr *) expr)->args);
1274 : }
1275 : }
4586 tgl 1276 EUB : }
4586 tgl 1277 UBC 0 : return -1;
4586 tgl 1278 EUB : }
1279 :
9770 scrappy 1280 :
1281 : /*
1282 : * transformSelectStmt -
1283 : * transforms a Select Statement
5826 tgl 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 *
9221 bruce 1289 GIC 259514 : transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
1290 : {
9344 1291 259514 : Query *qry = makeNode(Query);
1292 : Node *qual;
1293 : ListCell *l;
1294 :
9345 1295 259514 : qry->commandType = CMD_SELECT;
9770 scrappy 1296 ECB :
1297 : /* process the WITH clause independently of all else */
5300 tgl 1298 CBC 259514 : if (stmt->withClause)
1299 : {
5300 tgl 1300 GIC 967 : qry->hasRecursive = stmt->withClause->recursive;
1301 967 : qry->cteList = transformWithClause(pstate, stmt->withClause);
4426 tgl 1302 CBC 828 : qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1303 : }
1304 :
4038 tgl 1305 ECB : /* Complain if we get called from someplace where INTO is not allowed */
4038 tgl 1306 GIC 259375 : if (stmt->intoClause)
4038 tgl 1307 CBC 9 : ereport(ERROR,
4038 tgl 1308 ECB : (errcode(ERRCODE_SYNTAX_ERROR),
1309 : errmsg("SELECT ... INTO is not allowed here"),
1310 : parser_errposition(pstate,
1311 : exprLocation((Node *) stmt->intoClause))));
1312 :
4804 1313 : /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
4804 tgl 1314 CBC 259366 : pstate->p_locking_clause = stmt->lockingClause;
1315 :
1316 : /* make WINDOW info available for window functions, too */
4804 tgl 1317 GIC 259366 : pstate->p_windowdefs = stmt->windowClause;
1318 :
1319 : /* process the FROM clause */
8089 1320 259366 : transformFromClause(pstate, stmt->fromClause);
9770 scrappy 1321 ECB :
1322 : /* transform targetlist */
3894 tgl 1323 GIC 259107 : qry->targetList = transformTargetList(pstate, stmt->targetList,
3894 tgl 1324 ECB : EXPR_KIND_SELECT_TARGET);
1325 :
1326 : /* mark column origins */
7278 tgl 1327 CBC 256976 : markTargetListOrigins(pstate, qry->targetList);
1328 :
1329 : /* transform WHERE */
3894 1330 256976 : qual = transformWhereClause(pstate, stmt->whereClause,
1331 : EXPR_KIND_WHERE, "WHERE");
1332 :
1333 : /* initial processing of HAVING clause is much like WHERE clause */
7220 1334 256922 : qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
1335 : EXPR_KIND_HAVING, "HAVING");
1336 :
7238 tgl 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
5050 bruce 1341 : * them by reference.
1342 : */
9345 bruce 1343 GIC 256919 : qry->sortClause = transformSortClause(pstate,
1344 : stmt->sortClause,
1345 : &qry->targetList,
1346 : EXPR_KIND_ORDER_BY,
1347 : false /* allow SQL92 rules */ );
1348 :
7238 tgl 1349 256904 : qry->groupClause = transformGroupClause(pstate,
7238 tgl 1350 ECB : stmt->groupClause,
1351 : &qry->groupingSets,
1352 : &qry->targetList,
1353 : qry->sortClause,
1354 : EXPR_KIND_GROUP_BY,
1355 : false /* allow SQL92 rules */ );
752 tomas.vondra 1356 CBC 256892 : qry->groupDistinct = stmt->groupDistinct;
1357 :
5363 tgl 1358 GIC 256892 : if (stmt->distinctClause == NIL)
1359 : {
1360 252896 : qry->distinctClause = NIL;
1361 252896 : qry->hasDistinctOn = false;
1362 : }
5363 tgl 1363 CBC 3996 : else if (linitial(stmt->distinctClause) == NULL)
1364 : {
5363 tgl 1365 ECB : /* We had SELECT DISTINCT */
5363 tgl 1366 GIC 3915 : qry->distinctClause = transformDistinctClause(pstate,
5363 tgl 1367 ECB : &qry->targetList,
4863 1368 : qry->sortClause,
1369 : false);
5363 tgl 1370 CBC 3915 : qry->hasDistinctOn = false;
1371 : }
1372 : else
5363 tgl 1373 ECB : {
1374 : /* We had SELECT DISTINCT ON */
5363 tgl 1375 GIC 81 : qry->distinctClause = transformDistinctOnClause(pstate,
1376 : stmt->distinctClause,
5363 tgl 1377 ECB : &qry->targetList,
1378 : qry->sortClause);
5363 tgl 1379 GIC 75 : qry->hasDistinctOn = true;
1380 : }
1381 :
5365 tgl 1382 ECB : /* transform LIMIT */
7220 tgl 1383 GIC 256886 : qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1384 : EXPR_KIND_OFFSET, "OFFSET",
1385 : stmt->limitOption);
7220 tgl 1386 CBC 256886 : qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1387 : EXPR_KIND_LIMIT, "LIMIT",
1388 : stmt->limitOption);
1097 alvherre 1389 GIC 256880 : qry->limitOption = stmt->limitOption;
8221 tgl 1390 ECB :
1391 : /* transform window clauses after we have seen all window functions */
5215 tgl 1392 GIC 256880 : qry->windowClause = transformWindowDefinitions(pstate,
5215 tgl 1393 ECB : pstate->p_windowdefs,
1394 : &qry->targetList);
1395 :
2265 1396 : /* resolve any still-unresolved output columns as being type text */
2265 tgl 1397 GIC 256847 : if (pstate->p_resolve_unknowns)
1398 225624 : resolveTargetListUnknowns(pstate, qry->targetList);
2265 tgl 1399 ECB :
7387 tgl 1400 GIC 256847 : qry->rtable = pstate->p_rtable;
124 alvherre 1401 GNC 256847 : qry->rteperminfos = pstate->p_rteperminfos;
7387 tgl 1402 GIC 256847 : qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1403 :
8665 1404 256847 : qry->hasSubLinks = pstate->p_hasSubLinks;
5215 tgl 1405 CBC 256847 : qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
2399 1406 256847 : qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
4078 tgl 1407 GIC 256847 : qry->hasAggs = pstate->p_hasAggs;
8221 tgl 1408 ECB :
6188 tgl 1409 CBC 259179 : foreach(l, stmt->lockingClause)
6188 tgl 1410 ECB : {
4911 tgl 1411 GIC 2353 : transformLockingClause(pstate, qry,
4911 tgl 1412 CBC 2353 : (LockingClause *) lfirst(l), false);
6188 tgl 1413 ECB : }
8221 1414 :
4404 tgl 1415 CBC 256826 : assign_query_collations(pstate, qry);
1416 :
1543 rhodiumtoad 1417 ECB : /* this must be done after collations, for reliable comparison of exprs */
1543 rhodiumtoad 1418 GIC 256796 : if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
1543 rhodiumtoad 1419 CBC 18317 : parseCheckAggregates(pstate, qry);
1543 rhodiumtoad 1420 ECB :
8221 tgl 1421 GIC 256742 : return qry;
1422 : }
8221 tgl 1423 ECB :
1424 : /*
1425 : * transformValuesClause -
6094 mail 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
4327 tgl 1429 : * SELECT * FROM (VALUES ...) AS "*VALUES*"
1430 : */
1431 : static Query *
6094 mail 1432 GIC 2539 : transformValuesClause(ParseState *pstate, SelectStmt *stmt)
1433 : {
1434 2539 : Query *qry = makeNode(Query);
335 tgl 1435 2539 : List *exprsLists = NIL;
2313 1436 2539 : List *coltypes = NIL;
1437 2539 : List *coltypmods = NIL;
1438 2539 : List *colcollations = NIL;
5337 1439 2539 : List **colexprs = NULL;
6094 mail 1440 CBC 2539 : int sublist_length = -1;
3885 tgl 1441 GIC 2539 : bool lateral = false;
1200 tgl 1442 ECB : ParseNamespaceItem *nsitem;
6094 mail 1443 : ListCell *lc;
6031 bruce 1444 : ListCell *lc2;
1445 : int i;
6094 mail 1446 :
6094 mail 1447 CBC 2539 : qry->commandType = CMD_SELECT;
6094 mail 1448 ECB :
1449 : /* Most SELECT stuff doesn't apply in a VALUES clause */
6094 mail 1450 GIC 2539 : Assert(stmt->distinctClause == NIL);
4038 tgl 1451 2539 : Assert(stmt->intoClause == NULL);
6094 mail 1452 2539 : Assert(stmt->targetList == NIL);
1453 2539 : Assert(stmt->fromClause == NIL);
1454 2539 : Assert(stmt->whereClause == NULL);
6094 mail 1455 CBC 2539 : Assert(stmt->groupClause == NIL);
6094 mail 1456 GIC 2539 : Assert(stmt->havingClause == NULL);
5215 tgl 1457 2539 : Assert(stmt->windowClause == NIL);
6094 mail 1458 CBC 2539 : Assert(stmt->op == SETOP_NONE);
6094 mail 1459 ECB :
4804 tgl 1460 : /* process the WITH clause independently of all else */
5300 tgl 1461 CBC 2539 : if (stmt->withClause)
5300 tgl 1462 ECB : {
5300 tgl 1463 CBC 24 : qry->hasRecursive = stmt->withClause->recursive;
1464 24 : qry->cteList = transformWithClause(pstate, stmt->withClause);
4426 1465 21 : qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
5300 tgl 1466 ECB : }
1467 :
1468 : /*
2329 1469 : * For each row of VALUES, transform the raw expressions.
1470 : *
4374 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 : */
6094 mail 1475 GIC 12452 : foreach(lc, stmt->valuesLists)
1476 : {
6031 bruce 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 : */
2329 tgl 1483 CBC 9920 : sublist = transformExpressionList(pstate, sublist,
1484 : EXPR_KIND_VALUES, false);
6094 mail 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 : */
6094 mail 1491 CBC 9916 : if (sublist_length < 0)
1492 : {
1493 : /* Remember post-transformation length of first sublist */
6094 mail 1494 GIC 2532 : sublist_length = list_length(sublist);
1495 : /* and allocate array for per-column lists */
5337 tgl 1496 2532 : colexprs = (List **) palloc0(sublist_length * sizeof(List *));
1497 : }
6094 mail 1498 7384 : else if (sublist_length != list_length(sublist))
6094 mail 1499 ECB : {
6094 mail 1500 UIC 0 : ereport(ERROR,
1501 : (errcode(ERRCODE_SYNTAX_ERROR),
5333 tgl 1502 ECB : errmsg("VALUES lists must all be the same length"),
1503 : parser_errposition(pstate,
1504 : exprLocation((Node *) sublist))));
1505 : }
6094 mail 1506 :
1507 : /* Build per-column expression lists */
6094 mail 1508 GBC 9916 : i = 0;
6094 mail 1509 GIC 24693 : foreach(lc2, sublist)
1510 : {
6031 bruce 1511 14777 : Node *col = (Node *) lfirst(lc2);
1512 :
5337 tgl 1513 14777 : colexprs[i] = lappend(colexprs[i], col);
6094 mail 1514 14777 : i++;
1515 : }
4374 tgl 1516 ECB :
1517 : /* Release sub-list's cells to save memory */
4374 tgl 1518 GIC 9916 : list_free(sublist);
335 tgl 1519 ECB :
1520 : /* Prepare an exprsLists element for this row */
335 tgl 1521 CBC 9916 : exprsLists = lappend(exprsLists, NIL);
6094 mail 1522 ECB : }
1523 :
1524 : /*
1525 : * Now resolve the common types of the columns, and coerce everything to
2313 tgl 1526 : * those types. Then identify the common typmod and common collation, if
1527 : * any, of each column.
1528 : *
4374 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 : */
6094 mail 1538 GIC 6355 : for (i = 0; i < sublist_length; i++)
1539 : {
1540 : Oid coltype;
1541 : int32 coltypmod;
1542 : Oid colcoll;
1543 :
4374 tgl 1544 3823 : coltype = select_common_type(pstate, colexprs[i], "VALUES", NULL);
1545 :
4374 tgl 1546 CBC 18600 : foreach(lc, colexprs[i])
1547 : {
4374 tgl 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;
6094 mail 1552 ECB : }
1553 :
894 peter 1554 CBC 3823 : coltypmod = select_common_typmod(pstate, colexprs[i], coltype);
4374 tgl 1555 GIC 3823 : colcoll = select_common_collation(pstate, colexprs[i], true);
4374 tgl 1556 ECB :
2313 tgl 1557 GIC 3823 : coltypes = lappend_oid(coltypes, coltype);
2313 tgl 1558 CBC 3823 : coltypmods = lappend_int(coltypmods, coltypmod);
1559 3823 : colcollations = lappend_oid(colcollations, colcoll);
1560 : }
1561 :
4374 tgl 1562 ECB : /*
1563 : * Finally, rearrange the coerced expressions into row-organized lists.
1564 : */
335 tgl 1565 CBC 6355 : for (i = 0; i < sublist_length; i++)
4374 tgl 1566 ECB : {
4374 tgl 1567 CBC 18600 : forboth(lc, colexprs[i], lc2, exprsLists)
1568 : {
4374 tgl 1569 GIC 14777 : Node *col = (Node *) lfirst(lc);
1570 14777 : List *sublist = lfirst(lc2);
1571 :
904 peter 1572 14777 : sublist = lappend(sublist, col);
335 tgl 1573 CBC 14777 : lfirst(lc2) = sublist;
1574 : }
4374 1575 3823 : list_free(colexprs[i]);
1576 : }
6094 mail 1577 ECB :
3885 tgl 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
3260 bruce 1581 : * RULE, then NEW/OLD references might appear. In that case we have to
1582 : * mark the VALUES RTE as LATERAL.
3885 tgl 1583 : */
3885 tgl 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 : */
1193 1591 2532 : nsitem = addRangeTableEntryForValues(pstate, exprsLists,
1193 tgl 1592 ECB : coltypes, coltypmods, colcollations,
1593 : NULL, lateral, true);
1193 tgl 1594 CBC 2532 : addNSItemToQuery(pstate, nsitem, true, true, true);
1595 :
1596 : /*
1597 : * Generate a targetlist as though expanding "*"
1598 : */
6094 mail 1599 2532 : Assert(pstate->p_next_resno == 1);
377 alvherre 1600 GIC 2532 : qry->targetList = expandNSItemAttrs(pstate, nsitem, 0, true, -1);
1601 :
6094 mail 1602 ECB : /*
1603 : * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
1604 : * VALUES, so cope.
1605 : */
6094 mail 1606 GIC 2532 : qry->sortClause = transformSortClause(pstate,
6094 mail 1607 ECB : stmt->sortClause,
1608 : &qry->targetList,
1609 : EXPR_KIND_ORDER_BY,
1610 : false /* allow SQL92 rules */ );
1611 :
6094 mail 1612 GIC 2532 : qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1613 : EXPR_KIND_OFFSET, "OFFSET",
1097 alvherre 1614 ECB : stmt->limitOption);
6094 mail 1615 GIC 2532 : qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1616 : EXPR_KIND_LIMIT, "LIMIT",
1617 : stmt->limitOption);
1097 alvherre 1618 2532 : qry->limitOption = stmt->limitOption;
1619 :
6094 mail 1620 CBC 2532 : if (stmt->lockingClause)
6094 mail 1621 UIC 0 : ereport(ERROR,
1622 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3260 bruce 1623 ECB : /*------
1624 : translator: %s is a SQL row locking clause such as FOR UPDATE */
1625 : errmsg("%s cannot be applied to VALUES",
3547 alvherre 1626 : LCS_asString(((LockingClause *)
1627 : linitial(stmt->lockingClause))->strength))));
6094 mail 1628 :
6094 mail 1629 GBC 2532 : qry->rtable = pstate->p_rtable;
124 alvherre 1630 GNC 2532 : qry->rteperminfos = pstate->p_rteperminfos;
6094 mail 1631 GIC 2532 : qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1632 :
1633 2532 : qry->hasSubLinks = pstate->p_hasSubLinks;
1634 :
4404 tgl 1635 2532 : assign_query_collations(pstate, qry);
1636 :
6094 mail 1637 2532 : return qry;
6094 mail 1638 ECB : }
1639 :
8221 tgl 1640 : /*
1641 : * transformSetOperationStmt -
8190 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-
8221 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 *
7836 bruce 1651 GIC 9169 : transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1652 : {
8221 tgl 1653 9169 : Query *qry = makeNode(Query);
1654 : SelectStmt *leftmostSelect;
1655 : int leftmostRTI;
1656 : Query *leftmostQuery;
1657 : SetOperationStmt *sostmt;
1658 : List *sortClause;
1659 : Node *limitOffset;
8221 tgl 1660 ECB : Node *limitCount;
1661 : List *lockingClause;
3904 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 :
8221 tgl 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.)
9081 lockhart 1687 ECB : */
8190 tgl 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);
4038 1693 9169 : if (leftmostSelect->intoClause)
4038 tgl 1694 UIC 0 : ereport(ERROR,
1695 : (errcode(ERRCODE_SYNTAX_ERROR),
1696 : errmsg("SELECT ... INTO is not allowed here"),
4038 tgl 1697 ECB : parser_errposition(pstate,
2118 1698 : exprLocation((Node *) leftmostSelect->intoClause))));
8221 1699 :
8190 1700 : /*
1701 : * We need to extract ORDER BY and other top-level clauses here and not
3955 bruce 1702 : * let transformSetOperationTree() see them --- else it'll just recurse
3955 bruce 1703 EUB : * right back here!
1704 : */
8190 tgl 1705 GIC 9169 : sortClause = stmt->sortClause;
1706 9169 : limitOffset = stmt->limitOffset;
1707 9169 : limitCount = stmt->limitCount;
6460 1708 9169 : lockingClause = stmt->lockingClause;
3904 1709 9169 : withClause = stmt->withClause;
1710 :
8190 1711 9169 : stmt->sortClause = NIL;
1712 9169 : stmt->limitOffset = NULL;
1713 9169 : stmt->limitCount = NULL;
6188 tgl 1714 CBC 9169 : stmt->lockingClause = NIL;
3904 1715 9169 : stmt->withClause = NULL;
8190 tgl 1716 ECB :
6555 1717 : /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
6460 tgl 1718 CBC 9169 : if (lockingClause)
7204 tgl 1719 GIC 3 : ereport(ERROR,
7204 tgl 1720 ECB : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3260 bruce 1721 : /*------
1722 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3547 alvherre 1723 : errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1724 : LCS_asString(((LockingClause *)
1725 : linitial(lockingClause))->strength))));
1726 :
3904 tgl 1727 : /* Process the WITH clause independently of all else */
3904 tgl 1728 CBC 9166 : if (withClause)
1729 : {
3904 tgl 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.
8720 bruce 1737 ECB : */
2238 peter_e 1738 GIC 9166 : sostmt = castNode(SetOperationStmt,
2153 bruce 1739 ECB : transformSetOperationTree(pstate, stmt, true, NULL));
2238 peter_e 1740 CBC 9121 : Assert(sostmt);
8190 tgl 1741 9121 : qry->setOperations = (Node *) sostmt;
1742 :
1743 : /*
1744 : * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1745 : */
8190 tgl 1746 GIC 9121 : node = sostmt->larg;
8221 tgl 1747 CBC 16501 : while (node && IsA(node, SetOperationStmt))
8221 tgl 1748 GIC 7380 : node = ((SetOperationStmt *) node)->larg;
8221 tgl 1749 CBC 9121 : Assert(node && IsA(node, RangeTblRef));
8190 1750 9121 : leftmostRTI = ((RangeTblRef *) node)->rtindex;
8190 tgl 1751 GIC 9121 : leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
8221 1752 9121 : Assert(leftmostQuery != NULL);
1753 :
1754 : /*
8221 tgl 1755 ECB : * Generate dummy targetlist for outer query using column names of
4370 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.
7362 1759 : *
6347 bruce 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 : */
8221 tgl 1765 GIC 9121 : qry->targetList = NIL;
7651 1766 9121 : targetvars = NIL;
8088 1767 9121 : targetnames = NIL;
1768 : sortnscolumns = (ParseNamespaceColumn *)
1193 1769 9121 : palloc0(list_length(sostmt->colTypes) * sizeof(ParseNamespaceColumn));
1770 9121 : sortcolindex = 0;
1771 :
1501 1772 42443 : forfour(lct, sostmt->colTypes,
1773 : lcm, sostmt->colTypmods,
1501 tgl 1774 ECB : lcc, sostmt->colCollations,
1775 : left_tlist, leftmostQuery->targetList)
8221 1776 : {
6086 tgl 1777 GIC 33322 : Oid colType = lfirst_oid(lct);
6086 tgl 1778 CBC 33322 : int32 colTypmod = lfirst_int(lcm);
4443 peter_e 1779 33322 : Oid colCollation = lfirst_oid(lcc);
6577 tgl 1780 GIC 33322 : TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
7181 tgl 1781 ECB : char *colName;
1782 : TargetEntry *tle;
1783 : Var *var;
1784 :
6577 tgl 1785 GIC 33322 : Assert(!lefttle->resjunk);
6577 tgl 1786 CBC 33322 : colName = pstrdup(lefttle->resname);
5300 1787 33322 : var = makeVar(leftmostRTI,
1788 33322 : lefttle->resno,
5300 tgl 1789 ECB : colType,
1790 : colTypmod,
1791 : colCollation,
1792 : 0);
5300 tgl 1793 GIC 33322 : var->location = exprLocation((Node *) lefttle->expr);
5300 tgl 1794 CBC 33322 : tle = makeTargetEntry((Expr *) var,
6577 1795 33322 : (AttrNumber) pstate->p_next_resno++,
6577 tgl 1796 ECB : colName,
1797 : false);
6577 tgl 1798 GIC 33322 : qry->targetList = lappend(qry->targetList, tle);
5300 1799 33322 : targetvars = lappend(targetvars, var);
8088 1800 33322 : targetnames = lappend(targetnames, makeString(colName));
1193 1801 33322 : sortnscolumns[sortcolindex].p_varno = leftmostRTI;
1193 tgl 1802 CBC 33322 : sortnscolumns[sortcolindex].p_varattno = lefttle->resno;
1803 33322 : sortnscolumns[sortcolindex].p_vartype = colType;
1804 33322 : sortnscolumns[sortcolindex].p_vartypmod = colTypmod;
1193 tgl 1805 GIC 33322 : sortnscolumns[sortcolindex].p_varcollid = colCollation;
1806 33322 : sortnscolumns[sortcolindex].p_varnosyn = leftmostRTI;
1193 tgl 1807 CBC 33322 : sortnscolumns[sortcolindex].p_varattnosyn = lefttle->resno;
1808 33322 : sortcolindex++;
8221 tgl 1809 ECB : }
8053 bruce 1810 :
8088 tgl 1811 : /*
6385 bruce 1812 : * As a first step towards supporting sort clauses that are expressions
3896 tgl 1813 : * using the output columns, generate a namespace entry that makes the
3260 bruce 1814 : * output columns visible. A Join RTE node is handy for this, since we
6385 1815 : * can easily control the Vars generated upon matches.
8088 tgl 1816 : *
6347 bruce 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 : */
5190 tgl 1821 GIC 9121 : sv_rtable_length = list_length(pstate->p_rtable);
1822 :
1193 1823 9121 : jnsitem = addRangeTableEntryForJoin(pstate,
1824 : targetnames,
1825 : sortnscolumns,
1826 : JOIN_INNER,
1827 : 0,
1828 : targetvars,
1829 : NIL,
1186 tgl 1830 ECB : NIL,
1831 : NULL,
739 peter 1832 : NULL,
1833 : false);
1834 :
3896 tgl 1835 GIC 9121 : sv_namespace = pstate->p_namespace;
1836 9121 : pstate->p_namespace = NIL;
1837 :
1838 : /* add jnsitem to column namespace only */
1193 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
6385 bruce 1844 ECB : * selecting an output column by name or number. Enforce by checking that
1845 : * transformSortClause doesn't add any items to tlist.
1846 : */
6888 neilc 1847 GIC 9121 : tllen = list_length(qry->targetList);
8221 tgl 1848 ECB :
8221 tgl 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 */
3896 tgl 1856 CBC 9118 : pstate->p_namespace = sv_namespace;
5190 tgl 1857 GIC 9118 : pstate->p_rtable = list_truncate(pstate->p_rtable, sv_rtable_length);
8088 tgl 1858 ECB :
6888 neilc 1859 GIC 9118 : if (tllen != list_length(qry->targetList))
7204 tgl 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."),
5333 tgl 1865 ECB : parser_errposition(pstate,
2118 1866 : exprLocation(list_nth(qry->targetList, tllen)))));
1867 :
7220 tgl 1868 CBC 9118 : qry->limitOffset = transformLimitClause(pstate, limitOffset,
1097 alvherre 1869 EUB : EXPR_KIND_OFFSET, "OFFSET",
1870 : stmt->limitOption);
7220 tgl 1871 GIC 9118 : qry->limitCount = transformLimitClause(pstate, limitCount,
1872 : EXPR_KIND_LIMIT, "LIMIT",
1873 : stmt->limitOption);
1097 alvherre 1874 9118 : qry->limitOption = stmt->limitOption;
1875 :
7387 tgl 1876 9118 : qry->rtable = pstate->p_rtable;
124 alvherre 1877 GNC 9118 : qry->rteperminfos = pstate->p_rteperminfos;
7387 tgl 1878 CBC 9118 : qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1879 :
8221 tgl 1880 GIC 9118 : qry->hasSubLinks = pstate->p_hasSubLinks;
5215 tgl 1881 CBC 9118 : qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
2399 tgl 1882 GIC 9118 : qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
4078 1883 9118 : qry->hasAggs = pstate->p_hasAggs;
9030 bruce 1884 ECB :
6188 tgl 1885 GIC 9118 : foreach(l, lockingClause)
6188 tgl 1886 ECB : {
4911 tgl 1887 LBC 0 : transformLockingClause(pstate, qry,
1888 0 : (LockingClause *) lfirst(l), false);
1889 : }
8844 vadim4o 1890 ECB :
4404 tgl 1891 CBC 9118 : assign_query_collations(pstate, qry);
4404 tgl 1892 ECB :
1543 rhodiumtoad 1893 : /* this must be done after collations, for reliable comparison of exprs */
1543 rhodiumtoad 1894 GIC 9118 : if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
1543 rhodiumtoad 1895 LBC 0 : parseCheckAggregates(pstate, qry);
1896 :
8221 tgl 1897 GBC 9118 : return qry;
8221 tgl 1898 EUB : }
1899 :
1900 : /*
797 peter 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
578 1904 : * support or they will fail. So look extra hard for hash support.
797 peter 1905 EUB : */
1906 : SortGroupClause *
578 peter 1907 CBC 16464 : makeSortGroupClauseForSetOp(Oid rescoltype, bool require_hash)
1908 : {
797 peter 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,
797 peter 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.
578 1925 : */
578 peter 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 */
797 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 :
797 peter 1936 CBC 16464 : return grpcl;
797 peter 1937 ECB : }
1938 :
1939 : /*
8221 tgl 1940 : * transformSetOperationTree
1941 : * Recursively transform leaves and internal nodes of a set-op tree
5337 1942 : *
4408 1943 : * In addition to returning the transformed node, if targetlist isn't NULL
3260 bruce 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
4408 tgl 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 *
5337 tgl 1954 GIC 42321 : transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
1955 : bool isTopLevel, List **targetlist)
1956 : {
1957 : bool isLeaf;
1958 :
8190 1959 42321 : Assert(stmt && IsA(stmt, SelectStmt));
1960 :
1961 : /* Guard against stack overflow due to overly complex set-expressions */
3801 1962 42321 : check_stack_depth();
1963 :
8190 tgl 1964 ECB : /*
1965 : * Validity-check both leaf and internal SELECTs for disallowed ops.
1966 : */
5826 tgl 1967 GIC 42321 : if (stmt->intoClause)
7204 tgl 1968 UIC 0 : ereport(ERROR,
7204 tgl 1969 ECB : (errcode(ERRCODE_SYNTAX_ERROR),
1970 : errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT"),
1971 : parser_errposition(pstate,
2118 1972 : exprLocation((Node *) stmt->intoClause))));
1973 :
1974 : /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
6460 tgl 1975 GIC 42321 : if (stmt->lockingClause)
7204 tgl 1976 UIC 0 : ereport(ERROR,
7204 tgl 1977 ECB : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3260 bruce 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 : /*
3904 tgl 1985 ECB : * If an internal node of a set-op tree has ORDER BY, LIMIT, FOR UPDATE,
3904 tgl 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 : */
8190 tgl 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 ||
3904 1999 16597 : stmt->lockingClause || stmt->withClause)
8190 tgl 2000 CBC 30 : isLeaf = true;
2001 : else
2002 16579 : isLeaf = false;
8190 tgl 2003 ECB : }
2004 :
8190 tgl 2005 GIC 42321 : if (isLeaf)
2006 : {
8190 tgl 2007 ECB : /* Process leaf SELECT */
8053 bruce 2008 : Query *selectQuery;
2009 : char selectName[32];
1193 tgl 2010 : ParseNamespaceItem *nsitem;
2011 : RangeTblRef *rtr;
5337 2012 : ListCell *tl;
2013 :
2014 : /*
8089 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 : */
2265 tgl 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 : */
3896 2037 25727 : if (pstate->p_namespace)
7360 tgl 2038 ECB : {
7360 tgl 2039 UIC 0 : if (contain_vars_of_level((Node *) selectQuery, 1))
7204 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 :
5337 tgl 2047 ECB : /*
2048 : * Extract a list of the non-junk TLEs for upper-level processing.
5337 tgl 2049 EUB : */
4408 tgl 2050 GBC 25727 : if (targetlist)
2051 : {
4408 tgl 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 : }
5337 tgl 2060 ECB : }
2061 :
8221 2062 : /*
2063 : * Make the leaf query be a subquery in the top-level rangetable.
2064 : */
7204 tgl 2065 CBC 25727 : snprintf(selectName, sizeof(selectName), "*SELECT* %d",
6888 neilc 2066 GIC 25727 : list_length(pstate->p_rtable) + 1);
1193 tgl 2067 CBC 25727 : nsitem = addRangeTableEntryForSubquery(pstate,
1193 tgl 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.
8221 2075 : */
8221 tgl 2076 CBC 25727 : rtr = makeNode(RangeTblRef);
1193 2077 25727 : rtr->rtindex = nsitem->p_rtindex;
8221 tgl 2078 GIC 25727 : return (Node *) rtr;
2079 : }
2080 : else
2081 : {
2082 : /* Process an internal node (set operation node) */
8190 2083 16579 : SetOperationStmt *op = makeNode(SetOperationStmt);
2084 : List *ltargetlist;
2085 : List *rtargetlist;
4408 tgl 2086 ECB : ListCell *ltl;
2087 : ListCell *rtl;
8221 2088 : const char *context;
332 tgl 2089 GIC 17074 : bool recursive = (pstate->p_parent_cte &&
2090 495 : pstate->p_parent_cte->cterecursive);
2091 :
8190 2092 16903 : context = (stmt->op == SETOP_UNION ? "UNION" :
8190 tgl 2093 CBC 324 : (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2094 : "EXCEPT"));
2095 :
8190 tgl 2096 GIC 16579 : op->op = stmt->op;
2097 16579 : op->all = stmt->all;
2098 :
8221 tgl 2099 ECB : /*
4960 2100 : * Recursively transform the left child node.
2101 : */
5337 tgl 2102 CBC 16579 : op->larg = transformSetOperationTree(pstate, stmt->larg,
4960 tgl 2103 ECB : false,
2104 : <argetlist);
2105 :
2106 : /*
4790 bruce 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 : */
578 peter 2112 CBC 16576 : if (isTopLevel && recursive)
4408 tgl 2113 GIC 426 : determineRecursiveColTypes(pstate, op->larg, ltargetlist);
2114 :
2115 : /*
2116 : * Recursively transform the right child node.
2117 : */
5337 2118 16576 : op->rarg = transformSetOperationTree(pstate, stmt->rarg,
2119 : false,
2120 : &rtargetlist);
2121 :
8221 tgl 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 : */
4408 tgl 2126 GIC 16564 : if (list_length(ltargetlist) != list_length(rtargetlist))
7204 tgl 2127 UIC 0 : ereport(ERROR,
7204 tgl 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 :
4408 tgl 2134 GIC 16564 : if (targetlist)
2135 7413 : *targetlist = NIL;
8221 tgl 2136 CBC 16564 : op->colTypes = NIL;
6086 tgl 2137 GBC 16564 : op->colTypmods = NIL;
4443 peter_e 2138 GIC 16564 : op->colCollations = NIL;
5358 tgl 2139 16564 : op->groupClauses = NIL;
4408 2140 96822 : forboth(ltl, ltargetlist, rtl, rtargetlist)
2141 : {
2142 80288 : TargetEntry *ltle = (TargetEntry *) lfirst(ltl);
2143 80288 : TargetEntry *rtle = (TargetEntry *) lfirst(rtl);
4408 tgl 2144 CBC 80288 : Node *lcolnode = (Node *) ltle->expr;
2145 80288 : Node *rcolnode = (Node *) rtle->expr;
4862 2146 80288 : Oid lcoltype = exprType(lcolnode);
2147 80288 : Oid rcoltype = exprType(rcolnode);
5337 tgl 2148 ECB : Node *bestexpr;
4408 2149 : int bestlocation;
8053 bruce 2150 : Oid rescoltype;
2151 : int32 rescoltypmod;
4443 peter_e 2152 : Oid rescolcoll;
8221 tgl 2153 :
6086 2154 : /* select common type, same as CASE et al */
5337 tgl 2155 CBC 80288 : rescoltype = select_common_type(pstate,
4862 2156 80288 : list_make2(lcolnode, rcolnode),
5337 tgl 2157 ECB : context,
2158 : &bestexpr);
4408 tgl 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.
4862 tgl 2165 ECB : *
4408 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 : */
4408 tgl 2188 GIC 80288 : if (lcoltype != UNKNOWNOID)
4404 2189 77693 : lcolnode = coerce_to_common_type(pstate, lcolnode,
2190 : rescoltype, context);
2191 2595 : else if (IsA(lcolnode, Const) ||
4404 tgl 2192 UIC 0 : IsA(lcolnode, Param))
2193 : {
4404 tgl 2194 GIC 2595 : lcolnode = coerce_to_common_type(pstate, lcolnode,
2195 : rescoltype, context);
2196 2595 : ltle->expr = (Expr *) lcolnode;
2197 : }
4408 tgl 2198 ECB :
4408 tgl 2199 CBC 80288 : if (rcoltype != UNKNOWNOID)
4404 tgl 2200 GIC 75508 : rcolnode = coerce_to_common_type(pstate, rcolnode,
4404 tgl 2201 ECB : rescoltype, context);
4404 tgl 2202 GBC 4780 : else if (IsA(rcolnode, Const) ||
4404 tgl 2203 UIC 0 : IsA(rcolnode, Param))
4404 tgl 2204 ECB : {
4404 tgl 2205 GIC 4780 : rcolnode = coerce_to_common_type(pstate, rcolnode,
4404 tgl 2206 ECB : rescoltype, context);
4404 tgl 2207 GIC 4777 : rtle->expr = (Expr *) rcolnode;
2208 : }
4404 tgl 2209 ECB :
894 peter 2210 CBC 80285 : rescoltypmod = select_common_typmod(pstate,
894 peter 2211 GIC 80285 : list_make2(lcolnode, rcolnode),
894 peter 2212 ECB : rescoltype);
894 peter 2213 EUB :
2214 : /*
4404 tgl 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 : */
4404 tgl 2223 GIC 80285 : rescolcoll = select_common_collation(pstate,
2118 2224 80285 : list_make2(lcolnode, rcolnode),
2225 80285 : (op->op == SETOP_UNION && op->all));
2226 :
2227 : /* emit results */
6888 neilc 2228 80258 : op->colTypes = lappend_oid(op->colTypes, rescoltype);
6086 tgl 2229 80258 : op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
4443 peter_e 2230 80258 : op->colCollations = lappend_oid(op->colCollations, rescolcoll);
2231 :
2232 : /*
5358 tgl 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 : */
5358 tgl 2237 GIC 80258 : if (op->op != SETOP_UNION || !op->all)
5358 tgl 2238 ECB : {
5333 2239 : ParseCallbackState pcbstate;
2240 :
5333 tgl 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.
332 tgl 2247 ECB : */
797 peter 2248 GIC 16452 : op->groupClauses = lappend(op->groupClauses,
578 2249 16452 : makeSortGroupClauseForSetOp(rescoltype, recursive));
2250 :
5333 tgl 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.
4408 tgl 2258 ECB : */
4408 tgl 2259 CBC 80258 : if (targetlist)
2260 : {
2261 46909 : SetToDefault *rescolnode = makeNode(SetToDefault);
2262 : TargetEntry *restle;
2263 :
4408 tgl 2264 GIC 46909 : rescolnode->typeId = rescoltype;
2265 46909 : rescolnode->typeMod = rescoltypmod;
4404 2266 46909 : rescolnode->collation = rescolcoll;
4408 2267 46909 : rescolnode->location = bestlocation;
2268 46909 : restle = makeTargetEntry((Expr *) rescolnode,
2118 tgl 2269 ECB : 0, /* no need to set resno */
2270 : NULL,
4408 2271 : false);
4408 tgl 2272 GIC 46909 : *targetlist = lappend(*targetlist, restle);
2273 : }
8221 tgl 2274 ECB : }
8190 2275 :
8221 tgl 2276 CBC 16534 : return (Node *) op;
8221 tgl 2277 ECB : }
9770 scrappy 2278 : }
2279 :
2280 : /*
2281 : * Process the outputs of the non-recursive term of a recursive union
4960 tgl 2282 : * to set up the parent CTE's columns
2283 : */
2284 : static void
4408 tgl 2285 GIC 426 : determineRecursiveColTypes(ParseState *pstate, Node *larg, List *nrtargetlist)
4960 tgl 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 : */
4960 tgl 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
4790 bruce 2308 ECB : * dummy result expressions of the non-recursive term.
4960 tgl 2309 : */
4960 tgl 2310 CBC 426 : targetList = NIL;
2311 426 : next_resno = 1;
4960 tgl 2312 ECB :
1501 tgl 2313 CBC 1359 : forboth(nrtl, nrtargetlist, left_tlist, leftmostQuery->targetList)
4960 tgl 2314 ECB : {
4408 tgl 2315 GIC 933 : TargetEntry *nrtle = (TargetEntry *) lfirst(nrtl);
4960 2316 933 : TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
2317 : char *colName;
2318 : TargetEntry *tle;
2319 :
4960 tgl 2320 CBC 933 : Assert(!lefttle->resjunk);
2321 933 : colName = pstrdup(lefttle->resname);
4408 tgl 2322 GIC 933 : tle = makeTargetEntry(nrtle->expr,
4960 tgl 2323 CBC 933 : next_resno++,
2324 : colName,
4960 tgl 2325 ECB : false);
4960 tgl 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 : }
4960 tgl 2332 ECB :
8221 2333 :
2334 : /*
2335 : * transformReturnStmt -
732 peter 2336 : * transforms a return statement
2337 : */
2338 : static Query *
732 peter 2339 GIC 14882 : transformReturnStmt(ParseState *pstate, ReturnStmt *stmt)
732 peter 2340 ECB : {
732 peter 2341 CBC 14882 : Query *qry = makeNode(Query);
2342 :
732 peter 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 :
732 peter 2349 CBC 14879 : if (pstate->p_resolve_unknowns)
732 peter 2350 GIC 14879 : resolveTargetListUnknowns(pstate, qry->targetList);
732 peter 2351 CBC 14879 : qry->rtable = pstate->p_rtable;
124 alvherre 2352 GNC 14879 : qry->rteperminfos = pstate->p_rteperminfos;
732 peter 2353 GIC 14879 : qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
732 peter 2354 CBC 14879 : qry->hasSubLinks = pstate->p_hasSubLinks;
2355 14879 : qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
732 peter 2356 GIC 14879 : qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
732 peter 2357 CBC 14879 : qry->hasAggs = pstate->p_hasAggs;
2358 :
732 peter 2359 GIC 14879 : assign_query_collations(pstate, qry);
732 peter 2360 ECB :
732 peter 2361 CBC 14879 : return qry;
732 peter 2362 ECB : }
2363 :
2364 :
9770 scrappy 2365 : /*
2366 : * transformUpdateStmt -
9345 bruce 2367 : * transforms an update statement
9770 scrappy 2368 : */
2369 : static Query *
9221 bruce 2370 CBC 7521 : transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2371 : {
9344 2372 7521 : Query *qry = makeNode(Query);
2373 : ParseNamespaceItem *nsitem;
2374 : Node *qual;
2375 :
9345 bruce 2376 GIC 7521 : qry->commandType = CMD_UPDATE;
2816 andres 2377 7521 : pstate->p_is_insert = false;
2378 :
2379 : /* process the WITH clause independently of all else */
4559 tgl 2380 7521 : if (stmt->withClause)
4559 tgl 2381 ECB : {
4559 tgl 2382 GIC 24 : qry->hasRecursive = stmt->withClause->recursive;
4559 tgl 2383 CBC 24 : qry->cteList = transformWithClause(pstate, stmt->withClause);
4426 tgl 2384 GIC 24 : qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
2385 : }
2386 :
7688 tgl 2387 CBC 15041 : qry->resultRelation = setTargetTable(pstate, stmt->relation,
2298 2388 7521 : stmt->relation->inh,
2389 : true,
2390 : ACL_UPDATE);
1193 2391 7520 : nsitem = pstate->p_target_nsitem;
2392 :
3375 tgl 2393 ECB : /* subqueries in FROM cannot access the result relation */
3379 tgl 2394 CBC 7520 : nsitem->p_lateral_only = true;
3375 2395 7520 : nsitem->p_lateral_ok = false;
2396 :
2397 : /*
6385 bruce 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 : */
8089 tgl 2401 GIC 7520 : transformFromClause(pstate, stmt->fromClause);
9770 scrappy 2402 ECB :
2403 : /* remaining clauses can reference the result relation normally */
3379 tgl 2404 GIC 7508 : nsitem->p_lateral_only = false;
3375 tgl 2405 CBC 7508 : nsitem->p_lateral_ok = true;
3379 tgl 2406 ECB :
3894 tgl 2407 GIC 7508 : qual = transformWhereClause(pstate, stmt->whereClause,
2408 : EXPR_KIND_WHERE, "WHERE");
2409 :
6084 2410 7502 : qry->returningList = transformReturningList(pstate, stmt->returningList);
2411 :
2893 andres 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 : */
2893 andres 2416 CBC 7502 : qry->targetList = transformUpdateTargetList(pstate, stmt->targetList);
2417 :
9345 bruce 2418 7481 : qry->rtable = pstate->p_rtable;
124 alvherre 2419 GNC 7481 : qry->rteperminfos = pstate->p_rteperminfos;
8227 tgl 2420 GIC 7481 : qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2421 :
2399 tgl 2422 CBC 7481 : qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
8244 tgl 2423 GIC 7481 : qry->hasSubLinks = pstate->p_hasSubLinks;
2424 :
2893 andres 2425 7481 : assign_query_collations(pstate, qry);
2426 :
2427 7481 : return qry;
2893 andres 2428 ECB : }
2429 :
2430 : /*
2431 : * transformUpdateTargetList -
377 alvherre 2432 : * handle SET clause in UPDATE/MERGE/INSERT ... ON CONFLICT UPDATE
2433 : */
2434 : List *
2893 andres 2435 CBC 8393 : transformUpdateTargetList(ParseState *pstate, List *origTlist)
2436 : {
2878 bruce 2437 8393 : List *tlist = NIL;
2438 : RTEPermissionInfo *target_perminfo;
2878 bruce 2439 ECB : ListCell *orig_tl;
2440 : ListCell *tl;
2441 :
2893 andres 2442 GIC 8393 : tlist = transformTargetList(pstate, origTlist,
2443 : EXPR_KIND_UPDATE_SOURCE);
2444 :
2445 : /* Prepare to assign non-conflicting resnos to resjunk attributes */
1828 teodor 2446 8369 : if (pstate->p_next_resno <= RelationGetNumberOfAttributes(pstate->p_target_relation))
1828 teodor 2447 CBC 7309 : pstate->p_next_resno = RelationGetNumberOfAttributes(pstate->p_target_relation) + 1;
2448 :
8665 tgl 2449 ECB : /* Prepare non-junk columns for assignment to target table */
124 alvherre 2450 GNC 8369 : target_perminfo = pstate->p_target_nsitem->p_perminfo;
2893 andres 2451 GIC 8369 : orig_tl = list_head(origTlist);
2452 :
2453 18819 : foreach(tl, tlist)
8665 tgl 2454 ECB : {
8665 tgl 2455 GIC 10462 : TargetEntry *tle = (TargetEntry *) lfirst(tl);
2456 : ResTarget *origTarget;
2457 : int attrno;
8665 tgl 2458 ECB :
6577 tgl 2459 CBC 10462 : if (tle->resjunk)
2460 : {
2461 : /*
6385 bruce 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 : */
6577 tgl 2467 CBC 66 : tle->resno = (AttrNumber) pstate->p_next_resno++;
6577 tgl 2468 GIC 66 : tle->resname = NULL;
8665 2469 66 : continue;
2470 : }
2893 andres 2471 CBC 10396 : if (orig_tl == NULL)
8665 tgl 2472 UIC 0 : elog(ERROR, "UPDATE target count mismatch --- internal error");
2190 tgl 2473 GIC 10396 : origTarget = lfirst_node(ResTarget, orig_tl);
2474 :
6226 2475 10396 : attrno = attnameAttNum(pstate->p_target_relation,
2476 10396 : origTarget->name, true);
2477 10396 : if (attrno == InvalidAttrNumber)
2478 6 : ereport(ERROR,
6226 tgl 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)));
6226 tgl 2484 EUB :
8560 tgl 2485 CBC 10390 : updateTargetListEntry(pstate, tle, origTarget->name,
2486 : attrno,
6226 tgl 2487 ECB : origTarget->indirection,
2488 : origTarget->location);
7228 bruce 2489 :
5190 tgl 2490 : /* Mark the target column as requiring update permissions */
124 alvherre 2491 GNC 10384 : target_perminfo->updatedCols = bms_add_member(target_perminfo->updatedCols,
2492 : attrno - FirstLowInvalidHeapAttributeNumber);
2493 :
1364 tgl 2494 GIC 10384 : orig_tl = lnext(origTlist, orig_tl);
2495 : }
2893 andres 2496 8357 : if (orig_tl != NULL)
8665 tgl 2497 LBC 0 : elog(ERROR, "UPDATE target count mismatch --- internal error");
2498 :
1147 peter 2499 GIC 8357 : return tlist;
2500 : }
2501 :
2502 : /*
6084 tgl 2503 ECB : * transformReturningList -
2504 : * handle a RETURNING clause in INSERT/UPDATE/DELETE
2505 : */
2506 : static List *
6084 tgl 2507 GIC 10094 : transformReturningList(ParseState *pstate, List *returningList)
6084 tgl 2508 ECB : {
6084 tgl 2509 EUB : List *rlist;
2510 : int save_next_resno;
6084 tgl 2511 ECB :
6084 tgl 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).
6084 tgl 2519 ECB : */
6084 tgl 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 */
3894 tgl 2524 CBC 1208 : rlist = transformTargetList(pstate, returningList, EXPR_KIND_RETURNING);
6084 tgl 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 : */
3403 tgl 2532 CBC 1196 : if (rlist == NIL)
3403 tgl 2533 LBC 0 : ereport(ERROR,
2534 : (errcode(ERRCODE_SYNTAX_ERROR),
2535 : errmsg("RETURNING must have at least one column"),
3403 tgl 2536 ECB : parser_errposition(pstate,
2537 : exprLocation(linitial(returningList)))));
2538 :
2539 : /* mark column origins */
6084 tgl 2540 GIC 1196 : markTargetListOrigins(pstate, rlist);
2541 :
2542 : /* resolve any still-unresolved output columns as being type text */
2265 2543 1196 : if (pstate->p_resolve_unknowns)
2265 tgl 2544 CBC 1196 : resolveTargetListUnknowns(pstate, rlist);
2265 tgl 2545 EUB :
2546 : /* restore state */
6084 tgl 2547 GIC 1196 : pstate->p_next_resno = save_next_resno;
2548 :
2549 1196 : return rlist;
2550 : }
2551 :
7530 tgl 2552 ECB :
2553 : /*
2554 : * transformPLAssignStmt -
825 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 *
825 tgl 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;
825 tgl 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 : */
825 tgl 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))
825 tgl 2598 UIC 0 : elog(ERROR, "invalid name count in PLAssignStmt");
825 tgl 2599 CBC 177 : cref->fields = lappend(cref->fields, ind);
2600 177 : indirection = list_delete_first(indirection);
825 tgl 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 : */
825 tgl 2608 GIC 2361 : target = transformExpr(pstate, (Node *) cref,
825 tgl 2609 ECB : EXPR_KIND_UPDATE_TARGET);
825 tgl 2610 GBC 2355 : targettype = exprType(target);
825 tgl 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 : */
825 tgl 2618 GIC 2355 : qry->commandType = CMD_SELECT;
2619 2355 : pstate->p_is_insert = false;
825 tgl 2620 ECB :
2621 : /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
825 tgl 2622 CBC 2355 : pstate->p_locking_clause = sstmt->lockingClause;
825 tgl 2623 ECB :
2624 : /* make WINDOW info available for window functions, too */
825 tgl 2625 GIC 2355 : pstate->p_windowdefs = sstmt->windowClause;
2626 :
2627 : /* process the FROM clause */
2628 2355 : transformFromClause(pstate, sstmt->fromClause);
2629 :
825 tgl 2630 ECB : /* initially transform the targetlist as if in SELECT */
825 tgl 2631 CBC 2355 : tlist = transformTargetList(pstate, sstmt->targetList,
2632 : EXPR_KIND_SELECT_TARGET);
2633 :
825 tgl 2634 ECB : /* we should have exactly one targetlist item */
825 tgl 2635 GIC 2355 : if (list_length(tlist) != 1)
2636 2 : ereport(ERROR,
825 tgl 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 :
825 tgl 2643 CBC 2353 : tle = linitial_node(TargetEntry, tlist);
2644 :
2645 : /*
2646 : * This next bit is similar to transformAssignedExpr; the key difference
825 tgl 2647 ECB : * is we use COERCION_PLPGSQL not COERCION_ASSIGNMENT.
2648 : */
825 tgl 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 : {
825 tgl 2655 CBC 43 : tle->expr = (Expr *)
825 tgl 2656 GIC 48 : transformAssignmentIndirection(pstate,
2657 : target,
2658 48 : stmt->name,
2659 : false,
2660 : targettype,
825 tgl 2661 ECB : targettypmod,
2662 : targetcollation,
2663 : indirection,
2664 : list_head(indirection),
825 tgl 2665 CBC 48 : (Node *) tle->expr,
2666 : COERCION_PLPGSQL,
825 tgl 2667 ECB : exprLocation(target));
2668 : }
825 tgl 2669 GIC 2305 : else if (targettype != type_id &&
825 tgl 2670 CBC 759 : (targettype == RECORDOID || ISCOMPLEX(targettype)) &&
825 tgl 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
825 tgl 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 : */
825 tgl 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)
825 tgl 2697 UIC 0 : ereport(ERROR,
825 tgl 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 :
825 tgl 2708 CBC 2348 : pstate->p_expr_kind = EXPR_KIND_NONE;
825 tgl 2709 EUB :
825 tgl 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 :
825 tgl 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 : */
825 tgl 2726 GIC 2348 : qry->sortClause = transformSortClause(pstate,
2727 : sstmt->sortClause,
2728 : &qry->targetList,
825 tgl 2729 ECB : EXPR_KIND_ORDER_BY,
2730 : false /* allow SQL92 rules */ );
2731 :
825 tgl 2732 GIC 2348 : qry->groupClause = transformGroupClause(pstate,
2733 : sstmt->groupClause,
2734 : &qry->groupingSets,
2735 : &qry->targetList,
2736 : qry->sortClause,
2737 : EXPR_KIND_GROUP_BY,
825 tgl 2738 ECB : false /* allow SQL92 rules */ );
2739 :
807 tgl 2740 GIC 2348 : if (sstmt->distinctClause == NIL)
2741 : {
2742 2348 : qry->distinctClause = NIL;
2743 2348 : qry->hasDistinctOn = false;
807 tgl 2744 ECB : }
807 tgl 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);
807 tgl 2752 LBC 0 : qry->hasDistinctOn = false;
2753 : }
807 tgl 2754 ECB : else
2755 : {
2756 : /* We had SELECT DISTINCT ON */
807 tgl 2757 UBC 0 : qry->distinctClause = transformDistinctOnClause(pstate,
2758 : sstmt->distinctClause,
2759 : &qry->targetList,
807 tgl 2760 EUB : qry->sortClause);
807 tgl 2761 UIC 0 : qry->hasDistinctOn = true;
2762 : }
2763 :
825 tgl 2764 EUB : /* transform LIMIT */
825 tgl 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,
825 tgl 2769 EUB : EXPR_KIND_LIMIT, "LIMIT",
2770 : sstmt->limitOption);
825 tgl 2771 GIC 2348 : qry->limitOption = sstmt->limitOption;
2772 :
825 tgl 2773 EUB : /* transform window clauses after we have seen all window functions */
825 tgl 2774 GIC 2348 : qry->windowClause = transformWindowDefinitions(pstate,
2775 : pstate->p_windowdefs,
2776 : &qry->targetList);
825 tgl 2777 ECB :
825 tgl 2778 GIC 2348 : qry->rtable = pstate->p_rtable;
124 alvherre 2779 GNC 2348 : qry->rteperminfos = pstate->p_rteperminfos;
825 tgl 2780 GIC 2348 : qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
825 tgl 2781 ECB :
825 tgl 2782 GIC 2348 : qry->hasSubLinks = pstate->p_hasSubLinks;
2783 2348 : qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
825 tgl 2784 CBC 2348 : qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
825 tgl 2785 GIC 2348 : qry->hasAggs = pstate->p_hasAggs;
2786 :
825 tgl 2787 CBC 2349 : foreach(l, sstmt->lockingClause)
2788 : {
825 tgl 2789 GIC 1 : transformLockingClause(pstate, qry,
2790 1 : (LockingClause *) lfirst(l), false);
825 tgl 2791 ECB : }
2792 :
825 tgl 2793 CBC 2348 : assign_query_collations(pstate, qry);
2794 :
825 tgl 2795 ECB : /* this must be done after collations, for reliable comparison of exprs */
825 tgl 2796 CBC 2348 : if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
2797 3 : parseCheckAggregates(pstate, qry);
825 tgl 2798 ECB :
825 tgl 2799 GIC 2348 : return qry;
825 tgl 2800 ECB : }
2801 :
2802 :
5826 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
2276 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.
5826 2812 : */
2813 : static Query *
5826 tgl 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))
5826 tgl 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 :
732 peter 2827 CBC 1375 : if ((stmt->options & CURSOR_OPT_ASENSITIVE) &&
732 peter 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 */
732 peter 2832 ECB : errmsg("cannot specify both %s and %s",
2833 : "ASENSITIVE", "INSENSITIVE")));
5826 tgl 2834 EUB :
2835 : /* Transform contained query, not allowing SELECT INTO */
2276 tgl 2836 GIC 1375 : query = transformStmt(pstate, stmt->query);
2837 1364 : stmt->query = (Node *) query;
2838 :
2839 : /* Grammar should not have allowed anything but SELECT */
2276 tgl 2840 CBC 1364 : if (!IsA(query, Query) ||
2276 tgl 2841 GBC 1364 : query->commandType != CMD_SELECT)
5333 tgl 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 : */
2276 tgl 2849 CBC 1364 : if (query->hasModifyingCTE)
4426 tgl 2850 LBC 0 : ereport(ERROR,
2851 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2852 : errmsg("DECLARE CURSOR must not contain data-modifying statements in WITH")));
4426 tgl 2853 ECB :
5781 2854 : /* FOR UPDATE and WITH HOLD are not compatible */
2276 tgl 2855 GBC 1364 : if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
5826 tgl 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 *)
2276 tgl 2862 ECB : linitial(query->rowMarks))->strength)),
5781 tgl 2863 EUB : errdetail("Holdable cursors must be READ ONLY.")));
2864 :
2865 : /* FOR UPDATE and SCROLL are not compatible */
2276 tgl 2866 GIC 1364 : if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
5646 tgl 2867 UIC 0 : ereport(ERROR,
5646 tgl 2868 ECB : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3260 bruce 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 */
2276 tgl 2877 GIC 1364 : if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
5646 tgl 2878 UIC 0 : ereport(ERROR,
732 peter 2879 ECB : (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
3260 bruce 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 */
2276 tgl 2888 GIC 1364 : result = makeNode(Query);
2889 1364 : result->commandType = CMD_UTILITY;
5826 tgl 2890 CBC 1364 : result->utilityStmt = (Node *) stmt;
5826 tgl 2891 EUB :
5826 tgl 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
4832 tgl 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.
5826 2905 : */
2906 : static Query *
5826 tgl 2907 GIC 9933 : transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
2908 : {
2909 : Query *result;
16 tgl 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 */
2276 tgl 2936 GIC 9933 : stmt->query = (Node *) transformOptionalSelectInto(pstate, stmt->query);
2937 :
2938 : /* make sure all is well with parameter types */
16 tgl 2939 GNC 9930 : if (generic_plan)
2940 9 : check_variable_parameters(pstate, (Query *) stmt->query);
2941 :
2942 : /* represent the command as a utility Query */
4038 tgl 2943 GIC 9930 : result = makeNode(Query);
2944 9930 : result->commandType = CMD_UTILITY;
2945 9930 : result->utilityStmt = (Node *) stmt;
2946 :
2947 9930 : return result;
4038 tgl 2948 ECB : }
2949 :
2950 :
2951 : /*
2952 : * transformCreateTableAsStmt -
3689 kgrittn 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 *
4038 tgl 2959 GIC 944 : transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
4038 tgl 2960 ECB : {
2961 : Query *result;
2962 : Query *query;
2963 :
2276 2964 : /* transform contained query, not allowing SELECT INTO */
3649 tgl 2965 GIC 944 : query = transformStmt(pstate, stmt->query);
3649 tgl 2966 CBC 944 : stmt->query = (Node *) query;
2967 :
3649 tgl 2968 ECB : /* additional work needed for CREATE MATERIALIZED VIEW */
1002 michael 2969 CBC 944 : if (stmt->objtype == OBJECT_MATVIEW)
2970 : {
2971 : /*
3649 tgl 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 : */
3649 tgl 2976 GIC 265 : if (query->hasModifyingCTE)
3649 tgl 2977 LBC 0 : ereport(ERROR,
2978 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2979 : errmsg("materialized views must not use data-modifying statements in WITH")));
3689 kgrittn 2980 ECB :
3649 tgl 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 : */
3649 tgl 2986 CBC 265 : if (isQueryUsingTempRelation(query))
3649 tgl 2987 UIC 0 : ereport(ERROR,
3649 tgl 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 : */
3649 tgl 2996 GIC 265 : if (query_contains_extern_params(query))
3649 tgl 2997 UIC 0 : ereport(ERROR,
2998 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2999 : errmsg("materialized views may not be defined using bound parameters")));
3649 tgl 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
3625 3006 : * handle.)
3007 : */
3625 tgl 3008 GIC 265 : if (stmt->into->rel->relpersistence == RELPERSISTENCE_UNLOGGED)
3625 tgl 3009 UIC 0 : ereport(ERROR,
3625 tgl 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
3649 3017 : * conveniently get it from.
3649 tgl 3018 EUB : */
2222 peter_e 3019 GIC 265 : stmt->into->viewQuery = (Node *) copyObject(query);
3020 : }
3021 :
3022 : /* represent the command as a utility Query */
5826 tgl 3023 944 : result = makeNode(Query);
3024 944 : result->commandType = CMD_UTILITY;
3025 944 : result->utilityStmt = (Node *) stmt;
3026 :
5826 tgl 3027 CBC 944 : return result;
5826 tgl 3028 EUB : }
3029 :
3030 : /*
3031 : * transform a CallStmt
3032 : */
3033 : static Query *
1874 peter_e 3034 GIC 208 : transformCallStmt(ParseState *pstate, CallStmt *stmt)
3035 : {
3036 : List *targs;
1874 peter_e 3037 ECB : ListCell *lc;
1874 peter_e 3038 EUB : Node *node;
3039 : FuncExpr *fexpr;
3040 : HeapTuple proctup;
3041 : Datum proargmodes;
3042 : bool isNull;
668 tgl 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.
668 tgl 3049 ECB : */
1874 peter_e 3050 GBC 208 : targs = NIL;
1874 peter_e 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,
1874 peter_e 3060 ECB : targs,
3061 : pstate->p_last_srf,
3062 : stmt->funccall,
3063 : true,
1874 peter_e 3064 CBC 208 : stmt->funccall->location);
1874 peter_e 3065 ECB :
1524 peter 3066 CBC 193 : assign_expr_collations(pstate, node);
3067 :
668 tgl 3068 193 : fexpr = castNode(FuncExpr, node);
3069 :
668 tgl 3070 GIC 193 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fexpr->funcid));
3071 193 : if (!HeapTupleIsValid(proctup))
668 tgl 3072 UIC 0 : elog(ERROR, "cache lookup failed for function %u", fexpr->funcid);
3073 :
3074 : /*
668 tgl 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 : */
668 tgl 3080 GIC 193 : fexpr->args = expand_function_arguments(fexpr->args,
3081 : true,
3082 : fexpr->funcresulttype,
3083 : proctup);
668 tgl 3084 ECB :
3085 : /* Fetch proargmodes; if it's null, there are no output args */
668 tgl 3086 GIC 193 : proargmodes = SysCacheGetAttr(PROCOID, proctup,
3087 : Anum_pg_proc_proargmodes,
3088 : &isNull);
3089 193 : if (!isNull)
3090 : {
668 tgl 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 :
668 tgl 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 ||
668 tgl 3105 CBC 76 : ARR_HASNULL(arr) ||
668 tgl 3106 GIC 76 : ARR_ELEMTYPE(arr) != CHAROID)
668 tgl 3107 LBC 0 : elog(ERROR, "proargmodes is not a 1-D char array of length %d or it contains nulls",
3108 : numargs);
668 tgl 3109 CBC 76 : argmodes = (char *) ARR_DATA_PTR(arr);
3110 :
3111 76 : inargs = NIL;
3112 76 : i = 0;
668 tgl 3113 GBC 258 : foreach(lc, fexpr->args)
3114 : {
668 tgl 3115 GIC 182 : Node *n = lfirst(lc);
3116 :
3117 182 : switch (argmodes[i])
3118 : {
3119 69 : case PROARGMODE_IN:
3120 : case PROARGMODE_VARIADIC:
668 tgl 3121 CBC 69 : inargs = lappend(inargs, n);
668 tgl 3122 GIC 69 : break;
3123 36 : case PROARGMODE_OUT:
3124 36 : outargs = lappend(outargs, n);
3125 36 : break;
3126 77 : case PROARGMODE_INOUT:
668 tgl 3127 CBC 77 : inargs = lappend(inargs, n);
668 tgl 3128 GIC 77 : outargs = lappend(outargs, copyObject(n));
3129 77 : break;
668 tgl 3130 LBC 0 : default:
3131 : /* note we don't support PROARGMODE_TABLE */
668 tgl 3132 UIC 0 : elog(ERROR, "invalid argmode %c for procedure",
3133 : argmodes[i]);
3134 : break;
3135 : }
668 tgl 3136 GIC 182 : i++;
3137 : }
3138 76 : fexpr->args = inargs;
3139 : }
3140 :
3141 193 : stmt->funcexpr = fexpr;
668 tgl 3142 CBC 193 : stmt->outargs = outargs;
668 tgl 3143 ECB :
668 tgl 3144 CBC 193 : ReleaseSysCache(proctup);
668 tgl 3145 ECB :
3146 : /* represent the command as a utility Query */
1874 peter_e 3147 CBC 193 : result = makeNode(Query);
1874 peter_e 3148 GBC 193 : result->commandType = CMD_UTILITY;
1874 peter_e 3149 GIC 193 : result->utilityStmt = (Node *) stmt;
1874 peter_e 3150 ECB :
1874 peter_e 3151 GIC 193 : return result;
1874 peter_e 3152 ECB : }
5826 tgl 3153 :
2947 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 *
3547 alvherre 3159 GIC 24 : LCS_asString(LockClauseStrength strength)
3547 alvherre 3160 ECB : {
3547 alvherre 3161 GIC 24 : switch (strength)
3547 alvherre 3162 ECB : {
2947 tgl 3163 LBC 0 : case LCS_NONE:
3164 0 : Assert(false);
2947 tgl 3165 ECB : break;
3547 alvherre 3166 LBC 0 : case LCS_FORKEYSHARE:
3167 0 : return "FOR KEY SHARE";
3168 0 : case LCS_FORSHARE:
3169 0 : return "FOR SHARE";
3547 alvherre 3170 CBC 3 : case LCS_FORNOKEYUPDATE:
3547 alvherre 3171 GBC 3 : return "FOR NO KEY UPDATE";
3547 alvherre 3172 GIC 21 : case LCS_FORUPDATE:
3547 alvherre 3173 GBC 21 : return "FOR UPDATE";
3174 : }
3260 bruce 3175 UIC 0 : return "FOR some"; /* shouldn't happen */
3176 : }
3547 alvherre 3177 ECB :
3178 : /*
3682 tgl 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
4913 3182 : */
8840 vadim4o 3183 : void
3537 alvherre 3184 GIC 5731 : CheckSelectLocking(Query *qry, LockClauseStrength strength)
8840 vadim4o 3185 ECB : {
2118 tgl 3186 GIC 5731 : Assert(strength != LCS_NONE); /* else caller error */
3187 :
8221 tgl 3188 CBC 5731 : if (qry->setOperations)
7204 tgl 3189 LBC 0 : ereport(ERROR,
7204 tgl 3190 ECB : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3191 : /*------
3260 bruce 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))));
8473 tgl 3195 GIC 5731 : if (qry->distinctClause != NIL)
7204 tgl 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 */
3547 alvherre 3200 ECB : errmsg("%s is not allowed with DISTINCT clause",
3201 : LCS_asString(strength))));
677 tgl 3202 CBC 5731 : if (qry->groupClause != NIL || qry->groupingSets != NIL)
7204 tgl 3203 GIC 6 : ereport(ERROR,
7204 tgl 3204 EUB : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3260 bruce 3205 : /*------
3206 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3547 alvherre 3207 : errmsg("%s is not allowed with GROUP BY clause",
3537 3208 : LCS_asString(strength))));
6604 tgl 3209 GBC 5725 : if (qry->havingQual != NULL)
6604 tgl 3210 UBC 0 : ereport(ERROR,
6604 tgl 3211 ECB : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3260 bruce 3212 : /*------
3213 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3547 alvherre 3214 : errmsg("%s is not allowed with HAVING clause",
3215 : LCS_asString(strength))));
8840 vadim4o 3216 GBC 5725 : if (qry->hasAggs)
7204 tgl 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))));
5215 3223 5722 : if (qry->hasWindowFuncs)
5215 tgl 3224 UIC 0 : ereport(ERROR,
5215 tgl 3225 ECB : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3226 : /*------
3260 bruce 3227 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3228 : errmsg("%s is not allowed with window functions",
3537 alvherre 3229 : LCS_asString(strength))));
2399 tgl 3230 GBC 5722 : if (qry->hasTargetSRFs)
4913 tgl 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",
3537 alvherre 3236 ECB : LCS_asString(strength))));
8840 vadim4o 3237 GBC 5722 : }
3238 :
3239 : /*
3240 : * Transform a FOR [KEY] UPDATE/SHARE clause
3241 : *
3242 : * This basically involves replacing names by integer relids.
7095 tgl 3243 ECB : *
6555 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
4911 tgl 3248 GIC 2360 : transformLockingClause(ParseState *pstate, Query *qry, LockingClause *lc,
3249 : bool pushedDown)
8844 vadim4o 3250 ECB : {
6460 tgl 3251 GBC 2360 : List *lockedRels = lc->lockedRels;
3252 : ListCell *l;
3253 : ListCell *rt;
3254 : Index i;
3255 : LockingClause *allrels;
3256 :
3537 alvherre 3257 CBC 2360 : CheckSelectLocking(qry, lc->strength);
6460 tgl 3258 ECB :
3259 : /* make a clause we can pass down to subqueries to select all rels */
6460 tgl 3260 GIC 2351 : allrels = makeNode(LockingClause);
6385 bruce 3261 2351 : allrels->lockedRels = NIL; /* indicates all rels */
3728 alvherre 3262 2351 : allrels->strength = lc->strength;
3106 3263 2351 : allrels->waitPolicy = lc->waitPolicy;
8840 vadim4o 3264 ECB :
6460 tgl 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
598 tgl 3271 ECB : * it's convenient. We can't rely on the namespace mechanism that has
598 tgl 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 : */
8227 tgl 3275 GIC 847 : i = 0;
3276 1731 : foreach(rt, qry->rtable)
3277 : {
8227 tgl 3278 CBC 884 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3279 :
8227 tgl 3280 GIC 884 : ++i;
598 3281 884 : if (!rte->inFromCl)
3282 6 : continue;
7095 3283 878 : switch (rte->rtekind)
3284 : {
3285 863 : case RTE_RELATION:
3286 : {
3287 : RTEPermissionInfo *perminfo;
3288 :
124 alvherre 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 : }
7095 tgl 3296 CBC 863 : break;
7095 tgl 3297 UIC 0 : case RTE_SUBQUERY:
3106 alvherre 3298 0 : applyLockingClause(qry, i, lc->strength, lc->waitPolicy,
3106 alvherre 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
4790 bruce 3305 : * to have local knowledge in each query level about which
3306 : * rels need to be opened with RowShareLock.
3307 : */
4911 tgl 3308 LBC 0 : transformLockingClause(pstate, rte->subquery,
4911 tgl 3309 ECB : allrels, true);
7095 tgl 3310 LBC 0 : break;
7095 tgl 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.
598 tgl 3323 ECB : */
6555 tgl 3324 CBC 3002 : foreach(l, lockedRels)
3325 : {
5333 3326 1510 : RangeVar *thisrel = (RangeVar *) lfirst(l);
3327 :
5333 tgl 3328 ECB : /* For simplicity we insist on unqualified alias names here */
5333 tgl 3329 CBC 1510 : if (thisrel->catalogname || thisrel->schemaname)
5333 tgl 3330 LBC 0 : ereport(ERROR,
5333 tgl 3331 ECB : (errcode(ERRCODE_SYNTAX_ERROR),
3332 : /*------
3260 bruce 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)));
8227 tgl 3337 :
8227 tgl 3338 GIC 1510 : i = 0;
3339 1680 : foreach(rt, qry->rtable)
3340 : {
8227 tgl 3341 CBC 1674 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
263 dean.a.rasheed 3342 GNC 1674 : char *rtename = rte->eref->aliasname;
3343 :
8227 tgl 3344 CBC 1674 : ++i;
598 tgl 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 : */
263 dean.a.rasheed 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)
276 dean.a.rasheed 3367 GIC 3 : continue;
276 dean.a.rasheed 3368 ECB : }
3369 :
276 dean.a.rasheed 3370 GIC 1629 : if (strcmp(rtename, thisrel->relname) == 0)
3371 : {
7095 tgl 3372 1504 : switch (rte->rtekind)
3373 : {
3374 1492 : case RTE_RELATION:
3375 : {
3376 : RTEPermissionInfo *perminfo;
3377 :
124 alvherre 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 : }
7095 tgl 3385 GIC 1492 : break;
7095 tgl 3386 CBC 6 : case RTE_SUBQUERY:
3106 alvherre 3387 GIC 6 : applyLockingClause(qry, i, lc->strength,
3106 alvherre 3388 ECB : lc->waitPolicy, pushedDown);
3389 : /* see comment above */
4911 tgl 3390 GIC 6 : transformLockingClause(pstate, rte->subquery,
4911 tgl 3391 ECB : allrels, true);
7095 tgl 3392 GBC 6 : break;
7095 tgl 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)),
2118 tgl 3400 ECB : parser_errposition(pstate, thisrel->location)));
7095 3401 : break;
7095 tgl 3402 UIC 0 : case RTE_FUNCTION:
7095 tgl 3403 LBC 0 : ereport(ERROR,
6385 bruce 3404 ECB : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3405 : /*------
3260 3406 : translator: %s is a SQL row locking clause such as FOR UPDATE */
2118 tgl 3407 : errmsg("%s cannot be applied to a function",
3408 : LCS_asString(lc->strength)),
3409 : parser_errposition(pstate, thisrel->location)));
3410 : break;
2223 alvherre 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)));
2223 alvherre 3419 ECB : break;
6094 mail 3420 UIC 0 : case RTE_VALUES:
6094 mail 3421 LBC 0 : ereport(ERROR,
3422 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3260 bruce 3423 ECB : /*------
3424 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3547 alvherre 3425 : errmsg("%s cannot be applied to VALUES",
3426 : LCS_asString(lc->strength)),
2118 tgl 3427 : parser_errposition(pstate, thisrel->location)));
6094 mail 3428 : break;
5300 tgl 3429 LBC 0 : case RTE_CTE:
4912 tgl 3430 UIC 0 : ereport(ERROR,
3431 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3260 bruce 3432 ECB : /*------
3433 : translator: %s is a SQL row locking clause such as FOR UPDATE */
2118 tgl 3434 : errmsg("%s cannot be applied to a WITH query",
3435 : LCS_asString(lc->strength)),
3436 : parser_errposition(pstate, thisrel->location)));
3437 : break;
2200 kgrittn 3438 UIC 0 : case RTE_NAMEDTUPLESTORE:
3439 0 : ereport(ERROR,
2200 kgrittn 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",
2153 bruce 3444 : LCS_asString(lc->strength)),
2118 tgl 3445 : parser_errposition(pstate, thisrel->location)));
3446 : break;
1532 3447 :
3448 : /* Shouldn't be possible to see RTE_RESULT here */
3449 :
7095 tgl 3450 UIC 0 : default:
3451 0 : elog(ERROR, "unrecognized RTE type: %d",
7095 tgl 3452 ECB : (int) rte->rtekind);
3453 : break;
8227 3454 : }
7095 tgl 3455 CBC 1498 : break; /* out of foreach loop */
8844 vadim4o 3456 ECB : }
3457 : }
6892 neilc 3458 GIC 1504 : if (rt == NULL)
7204 tgl 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",
3547 alvherre 3464 EUB : thisrel->relname,
3465 : LCS_asString(lc->strength)),
3466 : parser_errposition(pstate, thisrel->location)));
3467 : }
3468 : }
6188 tgl 3469 GIC 2339 : }
3470 :
3471 : /*
3472 : * Record locking info for a single rangetable item
6188 tgl 3473 EUB : */
3474 : void
4911 tgl 3475 GIC 2409 : applyLockingClause(Query *qry, Index rtindex,
3476 : LockClauseStrength strength, LockWaitPolicy waitPolicy,
3477 : bool pushedDown)
3478 : {
3479 : RowMarkClause *rc;
3480 :
2118 3481 2409 : Assert(strength != LCS_NONE); /* else caller error */
2947 tgl 3482 EUB :
4911 3483 : /* If it's an explicit clause, make sure hasForUpdate gets set */
4911 tgl 3484 GIC 2409 : if (!pushedDown)
3485 2359 : qry->hasForUpdate = true;
3486 :
3487 : /* Check for pre-existing entry for same rtindex */
4913 3488 2409 : if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
3489 : {
3490 : /*
2947 tgl 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
3106 alvherre 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 : */
3728 alvherre 3509 UIC 0 : rc->strength = Max(rc->strength, strength);
3106 3510 0 : rc->waitPolicy = Max(rc->waitPolicy, waitPolicy);
4911 tgl 3511 0 : rc->pushedDown &= pushedDown;
6188 tgl 3512 UBC 0 : return;
6188 tgl 3513 EUB : }
3514 :
3515 : /* Make a new RowMarkClause */
6188 tgl 3516 GIC 2409 : rc = makeNode(RowMarkClause);
6188 tgl 3517 CBC 2409 : rc->rti = rtindex;
3728 alvherre 3518 GIC 2409 : rc->strength = strength;
3106 3519 2409 : rc->waitPolicy = waitPolicy;
4911 tgl 3520 CBC 2409 : rc->pushedDown = pushedDown;
6188 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.
2512 tgl 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 */
|