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 503 of file analyze.c.

504{
505 /*
506 * Currently, this should return true in exactly the same cases that
507 * stmt_requires_parse_analysis() does, so we just invoke that function
508 * rather than duplicating it. We keep the two entry points separate for
509 * clarity of callers, since from the callers' standpoint these are
510 * different conditions.
511 *
512 * While there may someday be a statement type for which transformStmt()
513 * does something nontrivial and yet no snapshot is needed for that
514 * processing, it seems likely that making such a choice would be fragile.
515 * If you want to install an exception, document the reasoning for it in a
516 * comment.
517 */
518 return stmt_requires_parse_analysis(parseTree);
519}
bool stmt_requires_parse_analysis(RawStmt *parseTree)
Definition: analyze.c:459

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 3641 of file analyze.c.

3644{
3645 RowMarkClause *rc;
3646
3647 Assert(strength != LCS_NONE); /* else caller error */
3648
3649 /* If it's an explicit clause, make sure hasForUpdate gets set */
3650 if (!pushedDown)
3651 qry->hasForUpdate = true;
3652
3653 /* Check for pre-existing entry for same rtindex */
3654 if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
3655 {
3656 /*
3657 * If the same RTE is specified with more than one locking strength,
3658 * use the strongest. (Reasonable, since you can't take both a shared
3659 * and exclusive lock at the same time; it'll end up being exclusive
3660 * anyway.)
3661 *
3662 * Similarly, if the same RTE is specified with more than one lock
3663 * wait policy, consider that NOWAIT wins over SKIP LOCKED, which in
3664 * turn wins over waiting for the lock (the default). This is a bit
3665 * more debatable but raising an error doesn't seem helpful. (Consider
3666 * for instance SELECT FOR UPDATE NOWAIT from a view that internally
3667 * contains a plain FOR UPDATE spec.) Having NOWAIT win over SKIP
3668 * LOCKED is reasonable since the former throws an error in case of
3669 * coming across a locked tuple, which may be undesirable in some
3670 * cases but it seems better than silently returning inconsistent
3671 * results.
3672 *
3673 * And of course pushedDown becomes false if any clause is explicit.
3674 */
3675 rc->strength = Max(rc->strength, strength);
3676 rc->waitPolicy = Max(rc->waitPolicy, waitPolicy);
3677 rc->pushedDown &= pushedDown;
3678 return;
3679 }
3680
3681 /* Make a new RowMarkClause */
3682 rc = makeNode(RowMarkClause);
3683 rc->rti = rtindex;
3684 rc->strength = strength;
3685 rc->waitPolicy = waitPolicy;
3686 rc->pushedDown = pushedDown;
3687 qry->rowMarks = lappend(qry->rowMarks, rc);
3688}
#define Max(x, y)
Definition: c.h:1000
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:234
LockClauseStrength strength
Definition: parsenodes.h:1611
LockWaitPolicy waitPolicy
Definition: parsenodes.h:1612

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 1281 of file analyze.c.

1283{
1284 List *result = NIL;
1285 int attno;
1286 Var *var;
1287 TargetEntry *te;
1288
1289 /*
1290 * Note that resnos of the tlist must correspond to attnos of the
1291 * underlying relation, hence we need entries for dropped columns too.
1292 */
1293 for (attno = 0; attno < RelationGetNumberOfAttributes(targetrel); attno++)
1294 {
1295 Form_pg_attribute attr = TupleDescAttr(targetrel->rd_att, attno);
1296 char *name;
1297
1298 if (attr->attisdropped)
1299 {
1300 /*
1301 * can't use atttypid here, but it doesn't really matter what type
1302 * the Const claims to be.
1303 */
1304 var = (Var *) makeNullConst(INT4OID, -1, InvalidOid);
1305 name = NULL;
1306 }
1307 else
1308 {
1309 var = makeVar(exclRelIndex, attno + 1,
1310 attr->atttypid, attr->atttypmod,
1311 attr->attcollation,
1312 0);
1313 name = pstrdup(NameStr(attr->attname));
1314 }
1315
1316 te = makeTargetEntry((Expr *) var,
1317 attno + 1,
1318 name,
1319 false);
1320
1321 result = lappend(result, te);
1322 }
1323
1324 /*
1325 * Add a whole-row-Var entry to support references to "EXCLUDED.*". Like
1326 * the other entries in the EXCLUDED tlist, its resno must match the Var's
1327 * varattno, else the wrong things happen while resolving references in
1328 * setrefs.c. This is against normal conventions for targetlists, but
1329 * it's okay since we don't use this as a real tlist.
1330 */
1331 var = makeVar(exclRelIndex, InvalidAttrNumber,
1332 targetrel->rd_rel->reltype,
1333 -1, InvalidOid, 0);
1334 te = makeTargetEntry((Expr *) var, InvalidAttrNumber, NULL, true);
1335 result = lappend(result, te);
1336
1337 return result;
1338}
#define InvalidAttrNumber
Definition: attnum.h:23
#define NameStr(name)
Definition: c.h:754
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:1759
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
#define NIL
Definition: pg_list.h:68
#define InvalidOid
Definition: postgres_ext.h:37
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:521
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 3350 of file analyze.c.

3351{
3352 Assert(strength != LCS_NONE); /* else caller error */
3353
3354 if (qry->setOperations)
3355 ereport(ERROR,
3356 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3357 /*------
3358 translator: %s is a SQL row locking clause such as FOR UPDATE */
3359 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
3360 LCS_asString(strength))));
3361 if (qry->distinctClause != NIL)
3362 ereport(ERROR,
3363 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3364 /*------
3365 translator: %s is a SQL row locking clause such as FOR UPDATE */
3366 errmsg("%s is not allowed with DISTINCT clause",
3367 LCS_asString(strength))));
3368 if (qry->groupClause != NIL || qry->groupingSets != NIL)
3369 ereport(ERROR,
3370 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3371 /*------
3372 translator: %s is a SQL row locking clause such as FOR UPDATE */
3373 errmsg("%s is not allowed with GROUP BY clause",
3374 LCS_asString(strength))));
3375 if (qry->havingQual != NULL)
3376 ereport(ERROR,
3377 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3378 /*------
3379 translator: %s is a SQL row locking clause such as FOR UPDATE */
3380 errmsg("%s is not allowed with HAVING clause",
3381 LCS_asString(strength))));
3382 if (qry->hasAggs)
3383 ereport(ERROR,
3384 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3385 /*------
3386 translator: %s is a SQL row locking clause such as FOR UPDATE */
3387 errmsg("%s is not allowed with aggregate functions",
3388 LCS_asString(strength))));
3389 if (qry->hasWindowFuncs)
3390 ereport(ERROR,
3391 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3392 /*------
3393 translator: %s is a SQL row locking clause such as FOR UPDATE */
3394 errmsg("%s is not allowed with window functions",
3395 LCS_asString(strength))));
3396 if (qry->hasTargetSRFs)
3397 ereport(ERROR,
3398 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3399 /*------
3400 translator: %s is a SQL row locking clause such as FOR UPDATE */
3401 errmsg("%s is not allowed with set-returning functions in the target list",
3402 LCS_asString(strength))));
3403}
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:150
const char * LCS_asString(LockClauseStrength strength)
Definition: analyze.c:3325
Node * setOperations
Definition: parsenodes.h:236
List * groupClause
Definition: parsenodes.h:216
Node * havingQual
Definition: parsenodes.h:222
List * groupingSets
Definition: parsenodes.h:220
List * distinctClause
Definition: parsenodes.h:226

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 3325 of file analyze.c.

3326{
3327 switch (strength)
3328 {
3329 case LCS_NONE:
3330 Assert(false);
3331 break;
3332 case LCS_FORKEYSHARE:
3333 return "FOR KEY SHARE";
3334 case LCS_FORSHARE:
3335 return "FOR SHARE";
3336 case LCS_FORNOKEYUPDATE:
3337 return "FOR NO KEY UPDATE";
3338 case LCS_FORUPDATE:
3339 return "FOR UPDATE";
3340 }
3341 return "FOR some"; /* shouldn't happen */
3342}
@ 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 2030 of file analyze.c.

2031{
2033 Oid sortop;
2034 Oid eqop;
2035 bool hashable;
2036
2037 /* determine the eqop and optional sortop */
2038 get_sort_group_operators(rescoltype,
2039 false, true, false,
2040 &sortop, &eqop, NULL,
2041 &hashable);
2042
2043 /*
2044 * The type cache doesn't believe that record is hashable (see
2045 * cache_record_field_properties()), but if the caller really needs hash
2046 * support, we can assume it does. Worst case, if any components of the
2047 * record don't support hashing, we will fail at execution.
2048 */
2049 if (require_hash && (rescoltype == RECORDOID || rescoltype == RECORDARRAYOID))
2050 hashable = true;
2051
2052 /* we don't have a tlist yet, so can't assign sortgrouprefs */
2053 grpcl->tleSortGroupRef = 0;
2054 grpcl->eqop = eqop;
2055 grpcl->sortop = sortop;
2056 grpcl->reverse_sort = false; /* Sort-op is "less than", or InvalidOid */
2057 grpcl->nulls_first = false; /* OK with or without sortop */
2058 grpcl->hashable = hashable;
2059
2060 return grpcl;
2061}
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:181
unsigned int Oid
Definition: postgres_ext.h:32
Index tleSortGroupRef
Definition: parsenodes.h:1469

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 117 of file analyze.c.

120{
121 ParseState *pstate = make_parsestate(NULL);
122 Query *query;
123 JumbleState *jstate = NULL;
124
125 Assert(sourceText != NULL); /* required as of 8.4 */
126
127 pstate->p_sourcetext = sourceText;
128
129 if (numParams > 0)
130 setup_parse_fixed_parameters(pstate, paramTypes, numParams);
131
132 pstate->p_queryEnv = queryEnv;
133
134 query = transformTopLevelStmt(pstate, parseTree);
135
136 if (IsQueryIdEnabled())
137 jstate = JumbleQuery(query);
138
140 (*post_parse_analyze_hook) (pstate, query, jstate);
141
142 free_parsestate(pstate);
143
144 pgstat_report_query_id(query->queryId, false);
145
146 return query;
147}
void pgstat_report_query_id(int64 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:68
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:261
static bool IsQueryIdEnabled(void)
Definition: queryjumble.h:104
JumbleState * JumbleQuery(Query *query)
QueryEnvironment * p_queryEnv
Definition: parse_node.h:223
const char * p_sourcetext
Definition: parse_node.h:195

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 157 of file analyze.c.

160{
161 ParseState *pstate = make_parsestate(NULL);
162 Query *query;
163 JumbleState *jstate = NULL;
164
165 Assert(sourceText != NULL); /* required as of 8.4 */
166
167 pstate->p_sourcetext = sourceText;
168
169 setup_parse_variable_parameters(pstate, paramTypes, numParams);
170
171 pstate->p_queryEnv = queryEnv;
172
173 query = transformTopLevelStmt(pstate, parseTree);
174
175 /* make sure all is well with parameter types */
176 check_variable_parameters(pstate, query);
177
178 if (IsQueryIdEnabled())
179 jstate = JumbleQuery(query);
180
182 (*post_parse_analyze_hook) (pstate, query, jstate);
183
184 free_parsestate(pstate);
185
186 pgstat_report_query_id(query->queryId, false);
187
188 return query;
189}
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 198 of file analyze.c.

202{
203 ParseState *pstate = make_parsestate(NULL);
204 Query *query;
205 JumbleState *jstate = NULL;
206
207 Assert(sourceText != NULL); /* required as of 8.4 */
208
209 pstate->p_sourcetext = sourceText;
210 pstate->p_queryEnv = queryEnv;
211 (*parserSetup) (pstate, parserSetupArg);
212
213 query = transformTopLevelStmt(pstate, parseTree);
214
215 if (IsQueryIdEnabled())
216 jstate = JumbleQuery(query);
217
219 (*post_parse_analyze_hook) (pstate, query, jstate);
220
221 free_parsestate(pstate);
222
223 pgstat_report_query_id(query->queryId, false);
224
225 return query;
226}

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 234 of file analyze.c.

238{
239 ParseState *pstate = make_parsestate(parentParseState);
240 Query *query;
241
242 pstate->p_parent_cte = parentCTE;
243 pstate->p_locked_from_parent = locked_from_parent;
244 pstate->p_resolve_unknowns = resolve_unknowns;
245
246 query = transformStmt(pstate, parseTree);
247
248 free_parsestate(pstate);
249
250 return query;
251}
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:324
bool p_locked_from_parent
Definition: parse_node.h:218
bool p_resolve_unknowns
Definition: parse_node.h:220
CommonTableExpr * p_parent_cte
Definition: parse_node.h:208

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 532 of file analyze.c.

533{
534 bool result;
535
536 if (query->commandType != CMD_UTILITY)
537 {
538 /* All optimizable statements require rewriting/planning */
539 result = true;
540 }
541 else
542 {
543 /* This list should match stmt_requires_parse_analysis() */
544 switch (nodeTag(query->utilityStmt))
545 {
546 case T_DeclareCursorStmt:
547 case T_ExplainStmt:
548 case T_CreateTableAsStmt:
549 case T_CallStmt:
550 result = true;
551 break;
552 default:
553 result = false;
554 break;
555 }
556 }
557 return result;
558}
#define nodeTag(nodeptr)
Definition: nodes.h:139
@ CMD_UTILITY
Definition: nodes.h:280
CmdType commandType
Definition: parsenodes.h:121
Node * utilityStmt
Definition: parsenodes.h:141

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 459 of file analyze.c.

460{
461 bool result;
462
463 switch (nodeTag(parseTree->stmt))
464 {
465 /*
466 * Optimizable statements
467 */
468 case T_InsertStmt:
469 case T_DeleteStmt:
470 case T_UpdateStmt:
471 case T_MergeStmt:
472 case T_SelectStmt:
473 case T_ReturnStmt:
474 case T_PLAssignStmt:
475 result = true;
476 break;
477
478 /*
479 * Special cases
480 */
481 case T_DeclareCursorStmt:
482 case T_ExplainStmt:
483 case T_CreateTableAsStmt:
484 case T_CallStmt:
485 result = true;
486 break;
487
488 default:
489 /* all other statements just get wrapped in a CMD_UTILITY Query */
490 result = false;
491 break;
492 }
493
494 return result;
495}
Node * stmt
Definition: parsenodes.h:2088

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 1064 of file analyze.c.

1067{
1068 List *result;
1069 ListCell *lc;
1070 ListCell *icols;
1071 ListCell *attnos;
1072
1073 /*
1074 * Check length of expr list. It must not have more expressions than
1075 * there are target columns. We allow fewer, but only if no explicit
1076 * columns list was given (the remaining columns are implicitly
1077 * defaulted). Note we must check this *after* transformation because
1078 * that could expand '*' into multiple items.
1079 */
1080 if (list_length(exprlist) > list_length(icolumns))
1081 ereport(ERROR,
1082 (errcode(ERRCODE_SYNTAX_ERROR),
1083 errmsg("INSERT has more expressions than target columns"),
1084 parser_errposition(pstate,
1085 exprLocation(list_nth(exprlist,
1086 list_length(icolumns))))));
1087 if (stmtcols != NIL &&
1088 list_length(exprlist) < list_length(icolumns))
1089 {
1090 /*
1091 * We can get here for cases like INSERT ... SELECT (a,b,c) FROM ...
1092 * where the user accidentally created a RowExpr instead of separate
1093 * columns. Add a suitable hint if that seems to be the problem,
1094 * because the main error message is quite misleading for this case.
1095 * (If there's no stmtcols, you'll get something about data type
1096 * mismatch, which is less misleading so we don't worry about giving a
1097 * hint in that case.)
1098 */
1099 ereport(ERROR,
1100 (errcode(ERRCODE_SYNTAX_ERROR),
1101 errmsg("INSERT has more target columns than expressions"),
1102 ((list_length(exprlist) == 1 &&
1103 count_rowexpr_columns(pstate, linitial(exprlist)) ==
1104 list_length(icolumns)) ?
1105 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),
1106 parser_errposition(pstate,
1107 exprLocation(list_nth(icolumns,
1108 list_length(exprlist))))));
1109 }
1110
1111 /*
1112 * Prepare columns for assignment to target table.
1113 */
1114 result = NIL;
1115 forthree(lc, exprlist, icols, icolumns, attnos, attrnos)
1116 {
1117 Expr *expr = (Expr *) lfirst(lc);
1118 ResTarget *col = lfirst_node(ResTarget, icols);
1119 int attno = lfirst_int(attnos);
1120
1121 expr = transformAssignedExpr(pstate, expr,
1123 col->name,
1124 attno,
1125 col->indirection,
1126 col->location);
1127
1128 if (strip_indirection)
1129 {
1130 /*
1131 * We need to remove top-level FieldStores and SubscriptingRefs,
1132 * as well as any CoerceToDomain appearing above one of those ---
1133 * but not a CoerceToDomain that isn't above one of those.
1134 */
1135 while (expr)
1136 {
1137 Expr *subexpr = expr;
1138
1139 while (IsA(subexpr, CoerceToDomain))
1140 {
1141 subexpr = ((CoerceToDomain *) subexpr)->arg;
1142 }
1143 if (IsA(subexpr, FieldStore))
1144 {
1145 FieldStore *fstore = (FieldStore *) subexpr;
1146
1147 expr = (Expr *) linitial(fstore->newvals);
1148 }
1149 else if (IsA(subexpr, SubscriptingRef))
1150 {
1151 SubscriptingRef *sbsref = (SubscriptingRef *) subexpr;
1152
1153 if (sbsref->refassgnexpr == NULL)
1154 break;
1155
1156 expr = sbsref->refassgnexpr;
1157 }
1158 else
1159 break;
1160 }
1161 }
1162
1163 result = lappend(result, expr);
1164 }
1165
1166 return result;
1167}
int errhint(const char *fmt,...)
Definition: elog.c:1330
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1384
#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:454
static int count_rowexpr_columns(ParseState *pstate, Node *expr)
Definition: analyze.c:1351
#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:1193
ParseLoc location
Definition: parsenodes.h:548
List * indirection
Definition: parsenodes.h:546
char * name
Definition: parsenodes.h:545
Expr * refassgnexpr
Definition: primnodes.h:735

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 2672 of file analyze.c.

2675{
2676 int save_nslen = list_length(pstate->p_namespace);
2677 int save_next_resno;
2678
2679 if (returningClause == NULL)
2680 return; /* nothing to do */
2681
2682 /*
2683 * Scan RETURNING WITH(...) options for OLD/NEW alias names. Complain if
2684 * there is any conflict with existing relations.
2685 */
2686 foreach_node(ReturningOption, option, returningClause->options)
2687 {
2688 switch (option->option)
2689 {
2691 if (qry->returningOldAlias != NULL)
2692 ereport(ERROR,
2693 errcode(ERRCODE_SYNTAX_ERROR),
2694 /* translator: %s is OLD or NEW */
2695 errmsg("%s cannot be specified multiple times", "OLD"),
2696 parser_errposition(pstate, option->location));
2697 qry->returningOldAlias = option->value;
2698 break;
2699
2701 if (qry->returningNewAlias != NULL)
2702 ereport(ERROR,
2703 errcode(ERRCODE_SYNTAX_ERROR),
2704 /* translator: %s is OLD or NEW */
2705 errmsg("%s cannot be specified multiple times", "NEW"),
2706 parser_errposition(pstate, option->location));
2707 qry->returningNewAlias = option->value;
2708 break;
2709
2710 default:
2711 elog(ERROR, "unrecognized returning option: %d", option->option);
2712 }
2713
2714 if (refnameNamespaceItem(pstate, NULL, option->value, -1, NULL) != NULL)
2715 ereport(ERROR,
2716 errcode(ERRCODE_DUPLICATE_ALIAS),
2717 errmsg("table name \"%s\" specified more than once",
2718 option->value),
2719 parser_errposition(pstate, option->location));
2720
2721 addNSItemForReturning(pstate, option->value,
2722 option->option == RETURNING_OPTION_OLD ?
2724 }
2725
2726 /*
2727 * If OLD/NEW alias names weren't explicitly specified, use "old"/"new"
2728 * unless masked by existing relations.
2729 */
2730 if (qry->returningOldAlias == NULL &&
2731 refnameNamespaceItem(pstate, NULL, "old", -1, NULL) == NULL)
2732 {
2733 qry->returningOldAlias = "old";
2735 }
2736 if (qry->returningNewAlias == NULL &&
2737 refnameNamespaceItem(pstate, NULL, "new", -1, NULL) == NULL)
2738 {
2739 qry->returningNewAlias = "new";
2741 }
2742
2743 /*
2744 * We need to assign resnos starting at one in the RETURNING list. Save
2745 * and restore the main tlist's value of p_next_resno, just in case
2746 * someone looks at it later (probably won't happen).
2747 */
2748 save_next_resno = pstate->p_next_resno;
2749 pstate->p_next_resno = 1;
2750
2751 /* transform RETURNING expressions identically to a SELECT targetlist */
2752 qry->returningList = transformTargetList(pstate,
2753 returningClause->exprs,
2754 exprKind);
2755
2756 /*
2757 * Complain if the nonempty tlist expanded to nothing (which is possible
2758 * if it contains only a star-expansion of a zero-column table). If we
2759 * allow this, the parsed Query will look like it didn't have RETURNING,
2760 * with results that would probably surprise the user.
2761 */
2762 if (qry->returningList == NIL)
2763 ereport(ERROR,
2764 (errcode(ERRCODE_SYNTAX_ERROR),
2765 errmsg("RETURNING must have at least one column"),
2766 parser_errposition(pstate,
2767 exprLocation(linitial(returningClause->exprs)))));
2768
2769 /* mark column origins */
2771
2772 /* resolve any still-unresolved output columns as being type text */
2773 if (pstate->p_resolve_unknowns)
2775
2776 /* restore state */
2777 pstate->p_namespace = list_truncate(pstate->p_namespace, save_nslen);
2778 pstate->p_next_resno = save_next_resno;
2779}
#define elog(elevel,...)
Definition: elog.h:226
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:120
void resolveTargetListUnknowns(ParseState *pstate, List *targetlist)
Definition: parse_target.c:287
void markTargetListOrigins(ParseState *pstate, List *targetlist)
Definition: parse_target.c:317
@ RETURNING_OPTION_NEW
Definition: parsenodes.h:1769
@ RETURNING_OPTION_OLD
Definition: parsenodes.h:1768
static void addNSItemForReturning(ParseState *pstate, const char *aliasname, VarReturningType returning_type)
Definition: analyze.c:2632
#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:203
int p_next_resno
Definition: parse_node.h:215
List * returningList
Definition: parsenodes.h:214

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 324 of file analyze.c.

325{
326 Query *result;
327
328#ifdef DEBUG_NODE_TESTS_ENABLED
329
330 /*
331 * We apply debug_raw_expression_coverage_test testing to basic DML
332 * statements; we can't just run it on everything because
333 * raw_expression_tree_walker() doesn't claim to handle utility
334 * statements.
335 */
336 if (Debug_raw_expression_coverage_test)
337 {
338 switch (nodeTag(parseTree))
339 {
340 case T_SelectStmt:
341 case T_InsertStmt:
342 case T_UpdateStmt:
343 case T_DeleteStmt:
344 case T_MergeStmt:
345 (void) test_raw_expression_coverage(parseTree, NULL);
346 break;
347 default:
348 break;
349 }
350 }
351#endif /* DEBUG_NODE_TESTS_ENABLED */
352
353 /*
354 * Caution: when changing the set of statement types that have non-default
355 * processing here, see also stmt_requires_parse_analysis() and
356 * analyze_requires_snapshot().
357 */
358 switch (nodeTag(parseTree))
359 {
360 /*
361 * Optimizable statements
362 */
363 case T_InsertStmt:
364 result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
365 break;
366
367 case T_DeleteStmt:
368 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
369 break;
370
371 case T_UpdateStmt:
372 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
373 break;
374
375 case T_MergeStmt:
376 result = transformMergeStmt(pstate, (MergeStmt *) parseTree);
377 break;
378
379 case T_SelectStmt:
380 {
381 SelectStmt *n = (SelectStmt *) parseTree;
382
383 if (n->valuesLists)
384 result = transformValuesClause(pstate, n);
385 else if (n->op == SETOP_NONE)
386 result = transformSelectStmt(pstate, n, NULL);
387 else
388 result = transformSetOperationStmt(pstate, n);
389 }
390 break;
391
392 case T_ReturnStmt:
393 result = transformReturnStmt(pstate, (ReturnStmt *) parseTree);
394 break;
395
396 case T_PLAssignStmt:
397 result = transformPLAssignStmt(pstate,
398 (PLAssignStmt *) parseTree);
399 break;
400
401 /*
402 * Special cases
403 */
404 case T_DeclareCursorStmt:
405 result = transformDeclareCursorStmt(pstate,
406 (DeclareCursorStmt *) parseTree);
407 break;
408
409 case T_ExplainStmt:
410 result = transformExplainStmt(pstate,
411 (ExplainStmt *) parseTree);
412 break;
413
414 case T_CreateTableAsStmt:
415 result = transformCreateTableAsStmt(pstate,
416 (CreateTableAsStmt *) parseTree);
417 break;
418
419 case T_CallStmt:
420 result = transformCallStmt(pstate,
421 (CallStmt *) parseTree);
422 break;
423
424 default:
425
426 /*
427 * other statements don't require any transformation; just return
428 * the original parsetree with a Query node plastered on top.
429 */
430 result = makeNode(Query);
431 result->commandType = CMD_UTILITY;
432 result->utilityStmt = parseTree;
433 break;
434 }
435
436 /* Mark as original query until we learn differently */
437 result->querySource = QSRC_ORIGINAL;
438 result->canSetTag = true;
439
440 return result;
441}
Query * transformMergeStmt(ParseState *pstate, MergeStmt *stmt)
Definition: parse_merge.c:107
@ SETOP_NONE
Definition: parsenodes.h:2176
@ QSRC_ORIGINAL
Definition: parsenodes.h:36
static Query * transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
Definition: analyze.c:565
static Query * transformReturnStmt(ParseState *pstate, ReturnStmt *stmt)
Definition: analyze.c:2460
static Query * transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt)
Definition: analyze.c:2794
static Query * transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
Definition: analyze.c:3121
static Query * transformCallStmt(ParseState *pstate, CallStmt *stmt)
Definition: analyze.c:3200
static Query * transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1773
static Query * transformSelectStmt(ParseState *pstate, SelectStmt *stmt, SelectStmtPassthrough *passthru)
Definition: analyze.c:1400
static Query * transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
Definition: analyze.c:2491
static Query * transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
Definition: analyze.c:3069
static Query * transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
Definition: analyze.c:2976
static Query * transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
Definition: analyze.c:637
static Query * transformValuesClause(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1554
List * valuesLists
Definition: parsenodes.h:2209
SetOperation op
Definition: parsenodes.h:2225

References CMD_UTILITY, Query::commandType, makeNode, nodeTag, SelectStmt::op, QSRC_ORIGINAL, SETOP_NONE, 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 261 of file analyze.c.

262{
263 Query *result;
264
265 /* We're at top level, so allow SELECT INTO */
266 result = transformOptionalSelectInto(pstate, parseTree->stmt);
267
268 result->stmt_location = parseTree->stmt_location;
269 result->stmt_len = parseTree->stmt_len;
270
271 return result;
272}
static Query * transformOptionalSelectInto(ParseState *pstate, Node *parseTree)
Definition: analyze.c:285
ParseLoc stmt_location
Definition: parsenodes.h:255
ParseLoc stmt_location
Definition: parsenodes.h:2089
ParseLoc stmt_len
Definition: parsenodes.h:2090

References RawStmt::stmt, RawStmt::stmt_len, Query::stmt_location, 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 2557 of file analyze.c.

2558{
2559 List *tlist = NIL;
2560 RTEPermissionInfo *target_perminfo;
2561 ListCell *orig_tl;
2562 ListCell *tl;
2563
2564 tlist = transformTargetList(pstate, origTlist,
2566
2567 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2570
2571 /* Prepare non-junk columns for assignment to target table */
2572 target_perminfo = pstate->p_target_nsitem->p_perminfo;
2573 orig_tl = list_head(origTlist);
2574
2575 foreach(tl, tlist)
2576 {
2577 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2578 ResTarget *origTarget;
2579 int attrno;
2580
2581 if (tle->resjunk)
2582 {
2583 /*
2584 * Resjunk nodes need no additional processing, but be sure they
2585 * have resnos that do not match any target columns; else rewriter
2586 * or planner might get confused. They don't need a resname
2587 * either.
2588 */
2589 tle->resno = (AttrNumber) pstate->p_next_resno++;
2590 tle->resname = NULL;
2591 continue;
2592 }
2593 if (orig_tl == NULL)
2594 elog(ERROR, "UPDATE target count mismatch --- internal error");
2595 origTarget = lfirst_node(ResTarget, orig_tl);
2596
2597 attrno = attnameAttNum(pstate->p_target_relation,
2598 origTarget->name, true);
2599 if (attrno == InvalidAttrNumber)
2600 ereport(ERROR,
2601 (errcode(ERRCODE_UNDEFINED_COLUMN),
2602 errmsg("column \"%s\" of relation \"%s\" does not exist",
2603 origTarget->name,
2605 (origTarget->indirection != NIL &&
2606 strcmp(origTarget->name, pstate->p_target_nsitem->p_names->aliasname) == 0) ?
2607 errhint("SET target columns cannot be qualified with the relation name.") : 0,
2608 parser_errposition(pstate, origTarget->location)));
2609
2610 updateTargetListEntry(pstate, tle, origTarget->name,
2611 attrno,
2612 origTarget->indirection,
2613 origTarget->location);
2614
2615 /* Mark the target column as requiring update permissions */
2616 target_perminfo->updatedCols = bms_add_member(target_perminfo->updatedCols,
2618
2619 orig_tl = lnext(origTlist, orig_tl);
2620 }
2621 if (orig_tl != NULL)
2622 elog(ERROR, "UPDATE target count mismatch --- internal error");
2623
2624 return tlist;
2625}
int16 AttrNumber
Definition: attnum.h:21
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:814
@ 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:621
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:549
char * aliasname
Definition: primnodes.h:51
RTEPermissionInfo * p_perminfo
Definition: parse_node.h:297
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:210
Relation p_target_relation
Definition: parse_node.h:209
Bitmapset * updatedCols
Definition: parsenodes.h:1326
AttrNumber resno
Definition: primnodes.h:2241
#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