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