PostgreSQL Source Code git master
analyze.h File Reference
#include "nodes/params.h"
#include "nodes/queryjumble.h"
#include "parser/parse_node.h"
Include dependency graph for analyze.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Typedefs

typedef void(* post_parse_analyze_hook_type) (ParseState *pstate, Query *query, JumbleState *jstate)
 

Functions

Queryparse_analyze_fixedparams (RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
 
Queryparse_analyze_varparams (RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
 
Queryparse_analyze_withcb (RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
 
Queryparse_sub_analyze (Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
 
ListtransformInsertRow (ParseState *pstate, List *exprlist, List *stmtcols, List *icolumns, List *attrnos, bool strip_indirection)
 
ListtransformUpdateTargetList (ParseState *pstate, List *origTlist)
 
void transformReturningClause (ParseState *pstate, Query *qry, ReturningClause *returningClause, ParseExprKind exprKind)
 
QuerytransformTopLevelStmt (ParseState *pstate, RawStmt *parseTree)
 
QuerytransformStmt (ParseState *pstate, Node *parseTree)
 
bool stmt_requires_parse_analysis (RawStmt *parseTree)
 
bool analyze_requires_snapshot (RawStmt *parseTree)
 
bool query_requires_rewrite_plan (Query *query)
 
const char * LCS_asString (LockClauseStrength strength)
 
void CheckSelectLocking (Query *qry, LockClauseStrength strength)
 
void applyLockingClause (Query *qry, Index rtindex, LockClauseStrength strength, LockWaitPolicy waitPolicy, bool pushedDown)
 
ListBuildOnConflictExcludedTargetlist (Relation targetrel, Index exclRelIndex)
 
SortGroupClausemakeSortGroupClauseForSetOp (Oid rescoltype, bool require_hash)
 

Variables

PGDLLIMPORT post_parse_analyze_hook_type post_parse_analyze_hook
 

Typedef Documentation

◆ post_parse_analyze_hook_type

typedef void(* post_parse_analyze_hook_type) (ParseState *pstate, Query *query, JumbleState *jstate)

Definition at line 22 of file analyze.h.

Function Documentation

◆ analyze_requires_snapshot()

bool analyze_requires_snapshot ( RawStmt parseTree)

Definition at line 571 of file analyze.c.

572{
573 /*
574 * Currently, this should return true in exactly the same cases that
575 * stmt_requires_parse_analysis() does, so we just invoke that function
576 * rather than duplicating it. We keep the two entry points separate for
577 * clarity of callers, since from the callers' standpoint these are
578 * different conditions.
579 *
580 * While there may someday be a statement type for which transformStmt()
581 * does something nontrivial and yet no snapshot is needed for that
582 * processing, it seems likely that making such a choice would be fragile.
583 * If you want to install an exception, document the reasoning for it in a
584 * comment.
585 */
586 return stmt_requires_parse_analysis(parseTree);
587}
bool stmt_requires_parse_analysis(RawStmt *parseTree)
Definition: analyze.c:527

References stmt_requires_parse_analysis().

Referenced by BuildingPlanRequiresSnapshot(), exec_bind_message(), exec_parse_message(), and exec_simple_query().

◆ applyLockingClause()

void applyLockingClause ( Query qry,
Index  rtindex,
LockClauseStrength  strength,
LockWaitPolicy  waitPolicy,
bool  pushedDown 
)

Definition at line 3757 of file analyze.c.

3760{
3761 RowMarkClause *rc;
3762
3763 Assert(strength != LCS_NONE); /* else caller error */
3764
3765 /* If it's an explicit clause, make sure hasForUpdate gets set */
3766 if (!pushedDown)
3767 qry->hasForUpdate = true;
3768
3769 /* Check for pre-existing entry for same rtindex */
3770 if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
3771 {
3772 /*
3773 * If the same RTE is specified with more than one locking strength,
3774 * use the strongest. (Reasonable, since you can't take both a shared
3775 * and exclusive lock at the same time; it'll end up being exclusive
3776 * anyway.)
3777 *
3778 * Similarly, if the same RTE is specified with more than one lock
3779 * wait policy, consider that NOWAIT wins over SKIP LOCKED, which in
3780 * turn wins over waiting for the lock (the default). This is a bit
3781 * more debatable but raising an error doesn't seem helpful. (Consider
3782 * for instance SELECT FOR UPDATE NOWAIT from a view that internally
3783 * contains a plain FOR UPDATE spec.) Having NOWAIT win over SKIP
3784 * LOCKED is reasonable since the former throws an error in case of
3785 * coming across a locked tuple, which may be undesirable in some
3786 * cases but it seems better than silently returning inconsistent
3787 * results.
3788 *
3789 * And of course pushedDown becomes false if any clause is explicit.
3790 */
3791 rc->strength = Max(rc->strength, strength);
3792 rc->waitPolicy = Max(rc->waitPolicy, waitPolicy);
3793 rc->pushedDown &= pushedDown;
3794 return;
3795 }
3796
3797 /* Make a new RowMarkClause */
3798 rc = makeNode(RowMarkClause);
3799 rc->rti = rtindex;
3800 rc->strength = strength;
3801 rc->waitPolicy = waitPolicy;
3802 rc->pushedDown = pushedDown;
3803 qry->rowMarks = lappend(qry->rowMarks, rc);
3804}
#define Max(x, y)
Definition: c.h:969
Assert(PointerIsAligned(start, uint64))
List * lappend(List *list, void *datum)
Definition: list.c:339
@ LCS_NONE
Definition: lockoptions.h:23
#define makeNode(_type_)
Definition: nodes.h:161
RowMarkClause * get_parse_rowmark(Query *qry, Index rtindex)
List * rowMarks
Definition: parsenodes.h:228
LockClauseStrength strength
Definition: parsenodes.h:1594
LockWaitPolicy waitPolicy
Definition: parsenodes.h:1595

References Assert(), get_parse_rowmark(), lappend(), LCS_NONE, makeNode, Max, RowMarkClause::pushedDown, Query::rowMarks, RowMarkClause::rti, RowMarkClause::strength, and RowMarkClause::waitPolicy.

Referenced by markQueryForLocking(), and transformLockingClause().

◆ BuildOnConflictExcludedTargetlist()

List * BuildOnConflictExcludedTargetlist ( Relation  targetrel,
Index  exclRelIndex 
)

Definition at line 1349 of file analyze.c.

1351{
1352 List *result = NIL;
1353 int attno;
1354 Var *var;
1355 TargetEntry *te;
1356
1357 /*
1358 * Note that resnos of the tlist must correspond to attnos of the
1359 * underlying relation, hence we need entries for dropped columns too.
1360 */
1361 for (attno = 0; attno < RelationGetNumberOfAttributes(targetrel); attno++)
1362 {
1363 Form_pg_attribute attr = TupleDescAttr(targetrel->rd_att, attno);
1364 char *name;
1365
1366 if (attr->attisdropped)
1367 {
1368 /*
1369 * can't use atttypid here, but it doesn't really matter what type
1370 * the Const claims to be.
1371 */
1372 var = (Var *) makeNullConst(INT4OID, -1, InvalidOid);
1373 name = NULL;
1374 }
1375 else
1376 {
1377 var = makeVar(exclRelIndex, attno + 1,
1378 attr->atttypid, attr->atttypmod,
1379 attr->attcollation,
1380 0);
1381 name = pstrdup(NameStr(attr->attname));
1382 }
1383
1384 te = makeTargetEntry((Expr *) var,
1385 attno + 1,
1386 name,
1387 false);
1388
1389 result = lappend(result, te);
1390 }
1391
1392 /*
1393 * Add a whole-row-Var entry to support references to "EXCLUDED.*". Like
1394 * the other entries in the EXCLUDED tlist, its resno must match the Var's
1395 * varattno, else the wrong things happen while resolving references in
1396 * setrefs.c. This is against normal conventions for targetlists, but
1397 * it's okay since we don't use this as a real tlist.
1398 */
1399 var = makeVar(exclRelIndex, InvalidAttrNumber,
1400 targetrel->rd_rel->reltype,
1401 -1, InvalidOid, 0);
1402 te = makeTargetEntry((Expr *) var, InvalidAttrNumber, NULL, true);
1403 result = lappend(result, te);
1404
1405 return result;
1406}
#define InvalidAttrNumber
Definition: attnum.h:23
#define NameStr(name)
Definition: c.h:717
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:388
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:289
char * pstrdup(const char *in)
Definition: mcxt.c:2327
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
#define NIL
Definition: pg_list.h:68
#define InvalidOid
Definition: postgres_ext.h:35
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:522
Definition: pg_list.h:54
TupleDesc rd_att
Definition: rel.h:112
Form_pg_class rd_rel
Definition: rel.h:111
Definition: primnodes.h:262
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160
const char * name

References InvalidAttrNumber, InvalidOid, lappend(), makeNullConst(), makeTargetEntry(), makeVar(), name, NameStr, NIL, pstrdup(), RelationData::rd_att, RelationData::rd_rel, RelationGetNumberOfAttributes, and TupleDescAttr().

Referenced by rewriteTargetView(), and transformOnConflictClause().

◆ CheckSelectLocking()

void CheckSelectLocking ( Query qry,
LockClauseStrength  strength 
)

Definition at line 3466 of file analyze.c.

3467{
3468 Assert(strength != LCS_NONE); /* else caller error */
3469
3470 if (qry->setOperations)
3471 ereport(ERROR,
3472 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3473 /*------
3474 translator: %s is a SQL row locking clause such as FOR UPDATE */
3475 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
3476 LCS_asString(strength))));
3477 if (qry->distinctClause != NIL)
3478 ereport(ERROR,
3479 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3480 /*------
3481 translator: %s is a SQL row locking clause such as FOR UPDATE */
3482 errmsg("%s is not allowed with DISTINCT clause",
3483 LCS_asString(strength))));
3484 if (qry->groupClause != NIL || qry->groupingSets != NIL)
3485 ereport(ERROR,
3486 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3487 /*------
3488 translator: %s is a SQL row locking clause such as FOR UPDATE */
3489 errmsg("%s is not allowed with GROUP BY clause",
3490 LCS_asString(strength))));
3491 if (qry->havingQual != NULL)
3492 ereport(ERROR,
3493 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3494 /*------
3495 translator: %s is a SQL row locking clause such as FOR UPDATE */
3496 errmsg("%s is not allowed with HAVING clause",
3497 LCS_asString(strength))));
3498 if (qry->hasAggs)
3499 ereport(ERROR,
3500 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3501 /*------
3502 translator: %s is a SQL row locking clause such as FOR UPDATE */
3503 errmsg("%s is not allowed with aggregate functions",
3504 LCS_asString(strength))));
3505 if (qry->hasWindowFuncs)
3506 ereport(ERROR,
3507 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3508 /*------
3509 translator: %s is a SQL row locking clause such as FOR UPDATE */
3510 errmsg("%s is not allowed with window functions",
3511 LCS_asString(strength))));
3512 if (qry->hasTargetSRFs)
3513 ereport(ERROR,
3514 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3515 /*------
3516 translator: %s is a SQL row locking clause such as FOR UPDATE */
3517 errmsg("%s is not allowed with set-returning functions in the target list",
3518 LCS_asString(strength))));
3519}
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
const char * LCS_asString(LockClauseStrength strength)
Definition: analyze.c:3441
Node * setOperations
Definition: parsenodes.h:230
List * groupClause
Definition: parsenodes.h:211
Node * havingQual
Definition: parsenodes.h:216
List * groupingSets
Definition: parsenodes.h:214
List * distinctClause
Definition: parsenodes.h:220

References Assert(), Query::distinctClause, ereport, errcode(), errmsg(), ERROR, Query::groupClause, Query::groupingSets, Query::havingQual, LCS_asString(), LCS_NONE, NIL, and Query::setOperations.

Referenced by preprocess_rowmarks(), and transformLockingClause().

◆ LCS_asString()

const char * LCS_asString ( LockClauseStrength  strength)

Definition at line 3441 of file analyze.c.

3442{
3443 switch (strength)
3444 {
3445 case LCS_NONE:
3446 Assert(false);
3447 break;
3448 case LCS_FORKEYSHARE:
3449 return "FOR KEY SHARE";
3450 case LCS_FORSHARE:
3451 return "FOR SHARE";
3452 case LCS_FORNOKEYUPDATE:
3453 return "FOR NO KEY UPDATE";
3454 case LCS_FORUPDATE:
3455 return "FOR UPDATE";
3456 }
3457 return "FOR some"; /* shouldn't happen */
3458}
@ LCS_FORUPDATE
Definition: lockoptions.h:27
@ LCS_FORSHARE
Definition: lockoptions.h:25
@ LCS_FORKEYSHARE
Definition: lockoptions.h:24
@ LCS_FORNOKEYUPDATE
Definition: lockoptions.h:26

References Assert(), LCS_FORKEYSHARE, LCS_FORNOKEYUPDATE, LCS_FORSHARE, LCS_FORUPDATE, and LCS_NONE.

Referenced by CheckSelectLocking(), grouping_planner(), make_outerjoininfo(), transformDeclareCursorStmt(), transformLockingClause(), transformSetOperationStmt(), transformSetOperationTree(), and transformValuesClause().

◆ makeSortGroupClauseForSetOp()

SortGroupClause * makeSortGroupClauseForSetOp ( Oid  rescoltype,
bool  require_hash 
)

Definition at line 2080 of file analyze.c.

2081{
2083 Oid sortop;
2084 Oid eqop;
2085 bool hashable;
2086
2087 /* determine the eqop and optional sortop */
2088 get_sort_group_operators(rescoltype,
2089 false, true, false,
2090 &sortop, &eqop, NULL,
2091 &hashable);
2092
2093 /*
2094 * The type cache doesn't believe that record is hashable (see
2095 * cache_record_field_properties()), but if the caller really needs hash
2096 * support, we can assume it does. Worst case, if any components of the
2097 * record don't support hashing, we will fail at execution.
2098 */
2099 if (require_hash && (rescoltype == RECORDOID || rescoltype == RECORDARRAYOID))
2100 hashable = true;
2101
2102 /* we don't have a tlist yet, so can't assign sortgrouprefs */
2103 grpcl->tleSortGroupRef = 0;
2104 grpcl->eqop = eqop;
2105 grpcl->sortop = sortop;
2106 grpcl->reverse_sort = false; /* Sort-op is "less than", or InvalidOid */
2107 grpcl->nulls_first = false; /* OK with or without sortop */
2108 grpcl->hashable = hashable;
2109
2110 return grpcl;
2111}
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:180
unsigned int Oid
Definition: postgres_ext.h:30
Index tleSortGroupRef
Definition: parsenodes.h:1452

References SortGroupClause::eqop, get_sort_group_operators(), makeNode, SortGroupClause::nulls_first, SortGroupClause::reverse_sort, SortGroupClause::sortop, and SortGroupClause::tleSortGroupRef.

Referenced by rewriteSearchAndCycle(), and transformSetOperationTree().

◆ parse_analyze_fixedparams()

Query * parse_analyze_fixedparams ( RawStmt parseTree,
const char *  sourceText,
const Oid paramTypes,
int  numParams,
QueryEnvironment queryEnv 
)

Definition at line 105 of file analyze.c.

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
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}
void pgstat_report_query_id(uint64 query_id, bool force)
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:72
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:39
void setup_parse_fixed_parameters(ParseState *pstate, const Oid *paramTypes, int numParams)
Definition: parse_param.c:68
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:59
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:327
static bool IsQueryIdEnabled(void)
Definition: queryjumble.h:95
JumbleState * JumbleQuery(Query *query)
QueryEnvironment * p_queryEnv
Definition: parse_node.h:239
const char * p_sourcetext
Definition: parse_node.h:209

References Assert(), free_parsestate(), IsQueryIdEnabled(), JumbleQuery(), make_parsestate(), ParseState::p_queryEnv, ParseState::p_sourcetext, pgstat_report_query_id(), post_parse_analyze_hook, setup_parse_fixed_parameters(), and transformTopLevelStmt().

Referenced by DefineView(), and pg_analyze_and_rewrite_fixedparams().

◆ parse_analyze_varparams()

Query * parse_analyze_varparams ( RawStmt parseTree,
const char *  sourceText,
Oid **  paramTypes,
int *  numParams,
QueryEnvironment queryEnv 
)

Definition at line 145 of file analyze.c.

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
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}
void check_variable_parameters(ParseState *pstate, Query *query)
Definition: parse_param.c:269
void setup_parse_variable_parameters(ParseState *pstate, Oid **paramTypes, int *numParams)
Definition: parse_param.c:84

References Assert(), check_variable_parameters(), free_parsestate(), IsQueryIdEnabled(), JumbleQuery(), make_parsestate(), ParseState::p_queryEnv, ParseState::p_sourcetext, pgstat_report_query_id(), post_parse_analyze_hook, setup_parse_variable_parameters(), and transformTopLevelStmt().

Referenced by pg_analyze_and_rewrite_varparams().

◆ parse_analyze_withcb()

Query * parse_analyze_withcb ( RawStmt parseTree,
const char *  sourceText,
ParserSetupHook  parserSetup,
void *  parserSetupArg,
QueryEnvironment queryEnv 
)

Definition at line 186 of file analyze.c.

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
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}

References Assert(), free_parsestate(), IsQueryIdEnabled(), JumbleQuery(), make_parsestate(), ParseState::p_queryEnv, ParseState::p_sourcetext, pgstat_report_query_id(), post_parse_analyze_hook, and transformTopLevelStmt().

Referenced by pg_analyze_and_rewrite_withcb().

◆ parse_sub_analyze()

Query * parse_sub_analyze ( Node parseTree,
ParseState parentParseState,
CommonTableExpr parentCTE,
bool  locked_from_parent,
bool  resolve_unknowns 
)

Definition at line 222 of file analyze.c.

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}
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:391
bool p_locked_from_parent
Definition: parse_node.h:234
bool p_resolve_unknowns
Definition: parse_node.h:236
CommonTableExpr * p_parent_cte
Definition: parse_node.h:224

References free_parsestate(), make_parsestate(), ParseState::p_locked_from_parent, ParseState::p_parent_cte, ParseState::p_resolve_unknowns, and transformStmt().

Referenced by analyzeCTE(), transformRangeSubselect(), transformSetOperationTree(), and transformSubLink().

◆ query_requires_rewrite_plan()

bool query_requires_rewrite_plan ( Query query)

Definition at line 600 of file analyze.c.

601{
602 bool result;
603
604 if (query->commandType != CMD_UTILITY)
605 {
606 /* All optimizable statements require rewriting/planning */
607 result = true;
608 }
609 else
610 {
611 /* This list should match stmt_requires_parse_analysis() */
612 switch (nodeTag(query->utilityStmt))
613 {
614 case T_DeclareCursorStmt:
615 case T_ExplainStmt:
616 case T_CreateTableAsStmt:
617 case T_CallStmt:
618 result = true;
619 break;
620 default:
621 result = false;
622 break;
623 }
624 }
625 return result;
626}
#define nodeTag(nodeptr)
Definition: nodes.h:139
@ CMD_UTILITY
Definition: nodes.h:276
CmdType commandType
Definition: parsenodes.h:121
Node * utilityStmt
Definition: parsenodes.h:136

References CMD_UTILITY, Query::commandType, nodeTag, and Query::utilityStmt.

Referenced by BuildingPlanRequiresSnapshot(), and StmtPlanRequiresRevalidation().

◆ stmt_requires_parse_analysis()

bool stmt_requires_parse_analysis ( RawStmt parseTree)

Definition at line 527 of file analyze.c.

528{
529 bool result;
530
531 switch (nodeTag(parseTree->stmt))
532 {
533 /*
534 * Optimizable statements
535 */
536 case T_InsertStmt:
537 case T_DeleteStmt:
538 case T_UpdateStmt:
539 case T_MergeStmt:
540 case T_SelectStmt:
541 case T_ReturnStmt:
542 case T_PLAssignStmt:
543 result = true;
544 break;
545
546 /*
547 * Special cases
548 */
549 case T_DeclareCursorStmt:
550 case T_ExplainStmt:
551 case T_CreateTableAsStmt:
552 case T_CallStmt:
553 result = true;
554 break;
555
556 default:
557 /* all other statements just get wrapped in a CMD_UTILITY Query */
558 result = false;
559 break;
560 }
561
562 return result;
563}
Node * stmt
Definition: parsenodes.h:2071

References nodeTag, and RawStmt::stmt.

Referenced by analyze_requires_snapshot(), and StmtPlanRequiresRevalidation().

◆ transformInsertRow()

List * transformInsertRow ( ParseState pstate,
List exprlist,
List stmtcols,
List icolumns,
List attrnos,
bool  strip_indirection 
)

Definition at line 1132 of file analyze.c.

1135{
1136 List *result;
1137 ListCell *lc;
1138 ListCell *icols;
1139 ListCell *attnos;
1140
1141 /*
1142 * Check length of expr list. It must not have more expressions than
1143 * there are target columns. We allow fewer, but only if no explicit
1144 * columns list was given (the remaining columns are implicitly
1145 * defaulted). Note we must check this *after* transformation because
1146 * that could expand '*' into multiple items.
1147 */
1148 if (list_length(exprlist) > list_length(icolumns))
1149 ereport(ERROR,
1150 (errcode(ERRCODE_SYNTAX_ERROR),
1151 errmsg("INSERT has more expressions than target columns"),
1152 parser_errposition(pstate,
1153 exprLocation(list_nth(exprlist,
1154 list_length(icolumns))))));
1155 if (stmtcols != NIL &&
1156 list_length(exprlist) < list_length(icolumns))
1157 {
1158 /*
1159 * We can get here for cases like INSERT ... SELECT (a,b,c) FROM ...
1160 * where the user accidentally created a RowExpr instead of separate
1161 * columns. Add a suitable hint if that seems to be the problem,
1162 * because the main error message is quite misleading for this case.
1163 * (If there's no stmtcols, you'll get something about data type
1164 * mismatch, which is less misleading so we don't worry about giving a
1165 * hint in that case.)
1166 */
1167 ereport(ERROR,
1168 (errcode(ERRCODE_SYNTAX_ERROR),
1169 errmsg("INSERT has more target columns than expressions"),
1170 ((list_length(exprlist) == 1 &&
1171 count_rowexpr_columns(pstate, linitial(exprlist)) ==
1172 list_length(icolumns)) ?
1173 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),
1174 parser_errposition(pstate,
1175 exprLocation(list_nth(icolumns,
1176 list_length(exprlist))))));
1177 }
1178
1179 /*
1180 * Prepare columns for assignment to target table.
1181 */
1182 result = NIL;
1183 forthree(lc, exprlist, icols, icolumns, attnos, attrnos)
1184 {
1185 Expr *expr = (Expr *) lfirst(lc);
1186 ResTarget *col = lfirst_node(ResTarget, icols);
1187 int attno = lfirst_int(attnos);
1188
1189 expr = transformAssignedExpr(pstate, expr,
1191 col->name,
1192 attno,
1193 col->indirection,
1194 col->location);
1195
1196 if (strip_indirection)
1197 {
1198 /*
1199 * We need to remove top-level FieldStores and SubscriptingRefs,
1200 * as well as any CoerceToDomain appearing above one of those ---
1201 * but not a CoerceToDomain that isn't above one of those.
1202 */
1203 while (expr)
1204 {
1205 Expr *subexpr = expr;
1206
1207 while (IsA(subexpr, CoerceToDomain))
1208 {
1209 subexpr = ((CoerceToDomain *) subexpr)->arg;
1210 }
1211 if (IsA(subexpr, FieldStore))
1212 {
1213 FieldStore *fstore = (FieldStore *) subexpr;
1214
1215 expr = (Expr *) linitial(fstore->newvals);
1216 }
1217 else if (IsA(subexpr, SubscriptingRef))
1218 {
1219 SubscriptingRef *sbsref = (SubscriptingRef *) subexpr;
1220
1221 if (sbsref->refassgnexpr == NULL)
1222 break;
1223
1224 expr = sbsref->refassgnexpr;
1225 }
1226 else
1227 break;
1228 }
1229 }
1230
1231 result = lappend(result, expr);
1232 }
1233
1234 return result;
1235}
int errhint(const char *fmt,...)
Definition: elog.c:1318
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1388
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
@ EXPR_KIND_INSERT_TARGET
Definition: parse_node.h:55
Expr * transformAssignedExpr(ParseState *pstate, Expr *expr, ParseExprKind exprKind, const char *colname, int attrno, List *indirection, int location)
Definition: parse_target.c:455
static int count_rowexpr_columns(ParseState *pstate, Node *expr)
Definition: analyze.c:1419
#define lfirst(lc)
Definition: pg_list.h:172
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static int list_length(const List *l)
Definition: pg_list.h:152
#define lfirst_int(lc)
Definition: pg_list.h:173
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:563
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
#define linitial(l)
Definition: pg_list.h:178
List * newvals
Definition: primnodes.h:1177
ParseLoc location
Definition: parsenodes.h:531
List * indirection
Definition: parsenodes.h:529
char * name
Definition: parsenodes.h:528
Expr * refassgnexpr
Definition: primnodes.h:720

References count_rowexpr_columns(), ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_INSERT_TARGET, exprLocation(), forthree, ResTarget::indirection, IsA, lappend(), lfirst, lfirst_int, lfirst_node, linitial, list_length(), list_nth(), ResTarget::location, ResTarget::name, FieldStore::newvals, NIL, parser_errposition(), SubscriptingRef::refassgnexpr, and transformAssignedExpr().

Referenced by transformInsertStmt(), and transformMergeStmt().

◆ transformReturningClause()

void transformReturningClause ( ParseState pstate,
Query qry,
ReturningClause returningClause,
ParseExprKind  exprKind 
)

Definition at line 2725 of file analyze.c.

2728{
2729 int save_nslen = list_length(pstate->p_namespace);
2730 int save_next_resno;
2731
2732 if (returningClause == NULL)
2733 return; /* nothing to do */
2734
2735 /*
2736 * Scan RETURNING WITH(...) options for OLD/NEW alias names. Complain if
2737 * there is any conflict with existing relations.
2738 */
2739 foreach_node(ReturningOption, option, returningClause->options)
2740 {
2741 switch (option->option)
2742 {
2744 if (qry->returningOldAlias != NULL)
2745 ereport(ERROR,
2746 errcode(ERRCODE_SYNTAX_ERROR),
2747 /* translator: %s is OLD or NEW */
2748 errmsg("%s cannot be specified multiple times", "OLD"),
2749 parser_errposition(pstate, option->location));
2750 qry->returningOldAlias = option->value;
2751 break;
2752
2754 if (qry->returningNewAlias != NULL)
2755 ereport(ERROR,
2756 errcode(ERRCODE_SYNTAX_ERROR),
2757 /* translator: %s is OLD or NEW */
2758 errmsg("%s cannot be specified multiple times", "NEW"),
2759 parser_errposition(pstate, option->location));
2760 qry->returningNewAlias = option->value;
2761 break;
2762
2763 default:
2764 elog(ERROR, "unrecognized returning option: %d", option->option);
2765 }
2766
2767 if (refnameNamespaceItem(pstate, NULL, option->value, -1, NULL) != NULL)
2768 ereport(ERROR,
2769 errcode(ERRCODE_DUPLICATE_ALIAS),
2770 errmsg("table name \"%s\" specified more than once",
2771 option->value),
2772 parser_errposition(pstate, option->location));
2773
2774 addNSItemForReturning(pstate, option->value,
2775 option->option == RETURNING_OPTION_OLD ?
2777 }
2778
2779 /*
2780 * If OLD/NEW alias names weren't explicitly specified, use "old"/"new"
2781 * unless masked by existing relations.
2782 */
2783 if (qry->returningOldAlias == NULL &&
2784 refnameNamespaceItem(pstate, NULL, "old", -1, NULL) == NULL)
2785 {
2786 qry->returningOldAlias = "old";
2788 }
2789 if (qry->returningNewAlias == NULL &&
2790 refnameNamespaceItem(pstate, NULL, "new", -1, NULL) == NULL)
2791 {
2792 qry->returningNewAlias = "new";
2794 }
2795
2796 /*
2797 * We need to assign resnos starting at one in the RETURNING list. Save
2798 * and restore the main tlist's value of p_next_resno, just in case
2799 * someone looks at it later (probably won't happen).
2800 */
2801 save_next_resno = pstate->p_next_resno;
2802 pstate->p_next_resno = 1;
2803
2804 /* transform RETURNING expressions identically to a SELECT targetlist */
2805 qry->returningList = transformTargetList(pstate,
2806 returningClause->exprs,
2807 exprKind);
2808
2809 /*
2810 * Complain if the nonempty tlist expanded to nothing (which is possible
2811 * if it contains only a star-expansion of a zero-column table). If we
2812 * allow this, the parsed Query will look like it didn't have RETURNING,
2813 * with results that would probably surprise the user.
2814 */
2815 if (qry->returningList == NIL)
2816 ereport(ERROR,
2817 (errcode(ERRCODE_SYNTAX_ERROR),
2818 errmsg("RETURNING must have at least one column"),
2819 parser_errposition(pstate,
2820 exprLocation(linitial(returningClause->exprs)))));
2821
2822 /* mark column origins */
2824
2825 /* resolve any still-unresolved output columns as being type text */
2826 if (pstate->p_resolve_unknowns)
2828
2829 /* restore state */
2830 pstate->p_namespace = list_truncate(pstate->p_namespace, save_nslen);
2831 pstate->p_next_resno = save_next_resno;
2832}
#define elog(elevel,...)
Definition: elog.h:225
List * list_truncate(List *list, int new_size)
Definition: list.c:631
ParseNamespaceItem * refnameNamespaceItem(ParseState *pstate, const char *schemaname, const char *refname, int location, int *sublevels_up)
List * transformTargetList(ParseState *pstate, List *targetlist, ParseExprKind exprKind)
Definition: parse_target.c:121
void resolveTargetListUnknowns(ParseState *pstate, List *targetlist)
Definition: parse_target.c:288
void markTargetListOrigins(ParseState *pstate, List *targetlist)
Definition: parse_target.c:318
@ RETURNING_OPTION_NEW
Definition: parsenodes.h:1752
@ RETURNING_OPTION_OLD
Definition: parsenodes.h:1751
static void addNSItemForReturning(ParseState *pstate, const char *aliasname, VarReturningType returning_type)
Definition: analyze.c:2685
#define foreach_node(type, var, lst)
Definition: pg_list.h:496
@ VAR_RETURNING_OLD
Definition: primnodes.h:257
@ VAR_RETURNING_NEW
Definition: primnodes.h:258
List * p_namespace
Definition: parse_node.h:219
int p_next_resno
Definition: parse_node.h:231
List * returningList
Definition: parsenodes.h:209

References addNSItemForReturning(), elog, ereport, errcode(), errmsg(), ERROR, exprLocation(), ReturningClause::exprs, foreach_node, linitial, list_length(), list_truncate(), markTargetListOrigins(), NIL, ReturningClause::options, ParseState::p_namespace, ParseState::p_next_resno, ParseState::p_resolve_unknowns, parser_errposition(), refnameNamespaceItem(), resolveTargetListUnknowns(), RETURNING_OPTION_NEW, RETURNING_OPTION_OLD, Query::returningList, transformTargetList(), VAR_RETURNING_NEW, and VAR_RETURNING_OLD.

Referenced by transformDeleteStmt(), transformMergeStmt(), and transformUpdateStmt().

◆ transformStmt()

Query * transformStmt ( ParseState pstate,
Node parseTree 
)

Definition at line 391 of file analyze.c.

392{
393 Query *result;
394
395#ifdef DEBUG_NODE_TESTS_ENABLED
396
397 /*
398 * We apply debug_raw_expression_coverage_test testing to basic DML
399 * statements; we can't just run it on everything because
400 * raw_expression_tree_walker() doesn't claim to handle utility
401 * statements.
402 */
403 if (Debug_raw_expression_coverage_test)
404 {
405 switch (nodeTag(parseTree))
406 {
407 case T_SelectStmt:
408 case T_InsertStmt:
409 case T_UpdateStmt:
410 case T_DeleteStmt:
411 case T_MergeStmt:
412 (void) test_raw_expression_coverage(parseTree, NULL);
413 break;
414 default:
415 break;
416 }
417 }
418#endif /* DEBUG_NODE_TESTS_ENABLED */
419
420 /*
421 * Caution: when changing the set of statement types that have non-default
422 * processing here, see also stmt_requires_parse_analysis() and
423 * analyze_requires_snapshot().
424 */
425 switch (nodeTag(parseTree))
426 {
427 /*
428 * Optimizable statements
429 */
430 case T_InsertStmt:
431 result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
432 break;
433
434 case T_DeleteStmt:
435 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
436 break;
437
438 case T_UpdateStmt:
439 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
440 break;
441
442 case T_MergeStmt:
443 result = transformMergeStmt(pstate, (MergeStmt *) parseTree);
444 break;
445
446 case T_SelectStmt:
447 {
448 SelectStmt *n = (SelectStmt *) parseTree;
449
450 if (n->valuesLists)
451 result = transformValuesClause(pstate, n);
452 else if (n->op == SETOP_NONE)
453 result = transformSelectStmt(pstate, n);
454 else
455 result = transformSetOperationStmt(pstate, n);
456 }
457 break;
458
459 case T_ReturnStmt:
460 result = transformReturnStmt(pstate, (ReturnStmt *) parseTree);
461 break;
462
463 case T_PLAssignStmt:
464 result = transformPLAssignStmt(pstate,
465 (PLAssignStmt *) parseTree);
466 break;
467
468 /*
469 * Special cases
470 */
471 case T_DeclareCursorStmt:
472 result = transformDeclareCursorStmt(pstate,
473 (DeclareCursorStmt *) parseTree);
474 break;
475
476 case T_ExplainStmt:
477 result = transformExplainStmt(pstate,
478 (ExplainStmt *) parseTree);
479 break;
480
481 case T_CreateTableAsStmt:
482 result = transformCreateTableAsStmt(pstate,
483 (CreateTableAsStmt *) parseTree);
484 break;
485
486 case T_CallStmt:
487 result = transformCallStmt(pstate,
488 (CallStmt *) parseTree);
489 break;
490
491 default:
492
493 /*
494 * other statements don't require any transformation; just return
495 * the original parsetree with a Query node plastered on top.
496 */
497 result = makeNode(Query);
498 result->commandType = CMD_UTILITY;
499 result->utilityStmt = (Node *) parseTree;
500 break;
501 }
502
503 /* Mark as original query until we learn differently */
504 result->querySource = QSRC_ORIGINAL;
505 result->canSetTag = true;
506 setQueryLocationAndLength(pstate, result, parseTree);
507
508 return result;
509}
Query * transformMergeStmt(ParseState *pstate, MergeStmt *stmt)
Definition: parse_merge.c:107
@ SETOP_NONE
Definition: parsenodes.h:2167
@ QSRC_ORIGINAL
Definition: parsenodes.h:36
static void setQueryLocationAndLength(ParseState *pstate, Query *qry, Node *parseTree)
Definition: analyze.c:260
static Query * transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
Definition: analyze.c:633
static Query * transformReturnStmt(ParseState *pstate, ReturnStmt *stmt)
Definition: analyze.c:2513
static Query * transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt)
Definition: analyze.c:2847
static Query * transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
Definition: analyze.c:3241
static Query * transformCallStmt(ParseState *pstate, CallStmt *stmt)
Definition: analyze.c:3316
static Query * transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1823
static Query * transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
Definition: analyze.c:2544
static Query * transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1461
static Query * transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
Definition: analyze.c:3189
static Query * transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
Definition: analyze.c:3096
static Query * transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
Definition: analyze.c:705
static Query * transformValuesClause(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1604
Definition: nodes.h:135
List * valuesLists
Definition: parsenodes.h:2199
SetOperation op
Definition: parsenodes.h:2215

References CMD_UTILITY, Query::commandType, makeNode, nodeTag, SelectStmt::op, QSRC_ORIGINAL, SETOP_NONE, setQueryLocationAndLength(), transformCallStmt(), transformCreateTableAsStmt(), transformDeclareCursorStmt(), transformDeleteStmt(), transformExplainStmt(), transformInsertStmt(), transformMergeStmt(), transformPLAssignStmt(), transformReturnStmt(), transformSelectStmt(), transformSetOperationStmt(), transformUpdateStmt(), transformValuesClause(), Query::utilityStmt, and SelectStmt::valuesLists.

Referenced by interpret_AS_clause(), parse_sub_analyze(), transformCreateTableAsStmt(), transformDeclareCursorStmt(), transformInsertStmt(), transformJsonArrayQueryConstructor(), transformOptionalSelectInto(), and transformRuleStmt().

◆ transformTopLevelStmt()

Query * transformTopLevelStmt ( ParseState pstate,
RawStmt parseTree 
)

Definition at line 327 of file analyze.c.

328{
329 Query *result;
330
331 /* Store RawStmt's length and location in pstate */
332 pstate->p_stmt_len = parseTree->stmt_len;
333 pstate->p_stmt_location = parseTree->stmt_location;
334
335 /* We're at top level, so allow SELECT INTO */
336 result = transformOptionalSelectInto(pstate, parseTree->stmt);
337
338 return result;
339}
static Query * transformOptionalSelectInto(ParseState *pstate, Node *parseTree)
Definition: analyze.c:352
ParseLoc p_stmt_location
Definition: parse_node.h:210
ParseLoc p_stmt_len
Definition: parse_node.h:211
ParseLoc stmt_location
Definition: parsenodes.h:2072
ParseLoc stmt_len
Definition: parsenodes.h:2073

References ParseState::p_stmt_len, ParseState::p_stmt_location, RawStmt::stmt, RawStmt::stmt_len, RawStmt::stmt_location, and transformOptionalSelectInto().

Referenced by inline_function(), parse_analyze_fixedparams(), parse_analyze_varparams(), and parse_analyze_withcb().

◆ transformUpdateTargetList()

List * transformUpdateTargetList ( ParseState pstate,
List origTlist 
)

Definition at line 2610 of file analyze.c.

2611{
2612 List *tlist = NIL;
2613 RTEPermissionInfo *target_perminfo;
2614 ListCell *orig_tl;
2615 ListCell *tl;
2616
2617 tlist = transformTargetList(pstate, origTlist,
2619
2620 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2623
2624 /* Prepare non-junk columns for assignment to target table */
2625 target_perminfo = pstate->p_target_nsitem->p_perminfo;
2626 orig_tl = list_head(origTlist);
2627
2628 foreach(tl, tlist)
2629 {
2630 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2631 ResTarget *origTarget;
2632 int attrno;
2633
2634 if (tle->resjunk)
2635 {
2636 /*
2637 * Resjunk nodes need no additional processing, but be sure they
2638 * have resnos that do not match any target columns; else rewriter
2639 * or planner might get confused. They don't need a resname
2640 * either.
2641 */
2642 tle->resno = (AttrNumber) pstate->p_next_resno++;
2643 tle->resname = NULL;
2644 continue;
2645 }
2646 if (orig_tl == NULL)
2647 elog(ERROR, "UPDATE target count mismatch --- internal error");
2648 origTarget = lfirst_node(ResTarget, orig_tl);
2649
2650 attrno = attnameAttNum(pstate->p_target_relation,
2651 origTarget->name, true);
2652 if (attrno == InvalidAttrNumber)
2653 ereport(ERROR,
2654 (errcode(ERRCODE_UNDEFINED_COLUMN),
2655 errmsg("column \"%s\" of relation \"%s\" does not exist",
2656 origTarget->name,
2658 (origTarget->indirection != NIL &&
2659 strcmp(origTarget->name, pstate->p_target_nsitem->p_names->aliasname) == 0) ?
2660 errhint("SET target columns cannot be qualified with the relation name.") : 0,
2661 parser_errposition(pstate, origTarget->location)));
2662
2663 updateTargetListEntry(pstate, tle, origTarget->name,
2664 attrno,
2665 origTarget->indirection,
2666 origTarget->location);
2667
2668 /* Mark the target column as requiring update permissions */
2669 target_perminfo->updatedCols = bms_add_member(target_perminfo->updatedCols,
2671
2672 orig_tl = lnext(origTlist, orig_tl);
2673 }
2674 if (orig_tl != NULL)
2675 elog(ERROR, "UPDATE target count mismatch --- internal error");
2676
2677 return tlist;
2678}
int16 AttrNumber
Definition: attnum.h:21
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
@ EXPR_KIND_UPDATE_SOURCE
Definition: parse_node.h:56
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
void updateTargetListEntry(ParseState *pstate, TargetEntry *tle, char *colname, int attrno, List *indirection, int location)
Definition: parse_target.c:622
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
#define RelationGetRelationName(relation)
Definition: rel.h:550
char * aliasname
Definition: primnodes.h:51
RTEPermissionInfo * p_perminfo
Definition: parse_node.h:313
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:226
Relation p_target_relation
Definition: parse_node.h:225
Bitmapset * updatedCols
Definition: parsenodes.h:1309
AttrNumber resno
Definition: primnodes.h:2221
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

References Alias::aliasname, attnameAttNum(), bms_add_member(), elog, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_UPDATE_SOURCE, FirstLowInvalidHeapAttributeNumber, ResTarget::indirection, InvalidAttrNumber, lfirst, lfirst_node, list_head(), lnext(), ResTarget::location, ResTarget::name, NIL, ParseNamespaceItem::p_names, ParseState::p_next_resno, ParseNamespaceItem::p_perminfo, ParseState::p_target_nsitem, ParseState::p_target_relation, parser_errposition(), RelationGetNumberOfAttributes, RelationGetRelationName, TargetEntry::resno, transformTargetList(), RTEPermissionInfo::updatedCols, and updateTargetListEntry().

Referenced by transformMergeStmt(), transformOnConflictClause(), and transformUpdateStmt().

Variable Documentation

◆ post_parse_analyze_hook