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

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

References stmt_requires_parse_analysis().

Referenced by BuildCachedPlan(), 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 3723 of file analyze.c.

3726{
3727 RowMarkClause *rc;
3728
3729 Assert(strength != LCS_NONE); /* else caller error */
3730
3731 /* If it's an explicit clause, make sure hasForUpdate gets set */
3732 if (!pushedDown)
3733 qry->hasForUpdate = true;
3734
3735 /* Check for pre-existing entry for same rtindex */
3736 if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
3737 {
3738 /*
3739 * If the same RTE is specified with more than one locking strength,
3740 * use the strongest. (Reasonable, since you can't take both a shared
3741 * and exclusive lock at the same time; it'll end up being exclusive
3742 * anyway.)
3743 *
3744 * Similarly, if the same RTE is specified with more than one lock
3745 * wait policy, consider that NOWAIT wins over SKIP LOCKED, which in
3746 * turn wins over waiting for the lock (the default). This is a bit
3747 * more debatable but raising an error doesn't seem helpful. (Consider
3748 * for instance SELECT FOR UPDATE NOWAIT from a view that internally
3749 * contains a plain FOR UPDATE spec.) Having NOWAIT win over SKIP
3750 * LOCKED is reasonable since the former throws an error in case of
3751 * coming across a locked tuple, which may be undesirable in some
3752 * cases but it seems better than silently returning inconsistent
3753 * results.
3754 *
3755 * And of course pushedDown becomes false if any clause is explicit.
3756 */
3757 rc->strength = Max(rc->strength, strength);
3758 rc->waitPolicy = Max(rc->waitPolicy, waitPolicy);
3759 rc->pushedDown &= pushedDown;
3760 return;
3761 }
3762
3763 /* Make a new RowMarkClause */
3764 rc = makeNode(RowMarkClause);
3765 rc->rti = rtindex;
3766 rc->strength = strength;
3767 rc->waitPolicy = waitPolicy;
3768 rc->pushedDown = pushedDown;
3769 qry->rowMarks = lappend(qry->rowMarks, rc);
3770}
#define Max(x, y)
Definition: c.h:955
#define Assert(condition)
Definition: c.h:815
List * lappend(List *list, void *datum)
Definition: list.c:339
@ LCS_NONE
Definition: lockoptions.h:23
#define makeNode(_type_)
Definition: nodes.h:155
RowMarkClause * get_parse_rowmark(Query *qry, Index rtindex)
List * rowMarks
Definition: parsenodes.h:228
LockClauseStrength strength
Definition: parsenodes.h:1589
LockWaitPolicy waitPolicy
Definition: parsenodes.h:1590

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

1317{
1318 List *result = NIL;
1319 int attno;
1320 Var *var;
1321 TargetEntry *te;
1322
1323 /*
1324 * Note that resnos of the tlist must correspond to attnos of the
1325 * underlying relation, hence we need entries for dropped columns too.
1326 */
1327 for (attno = 0; attno < RelationGetNumberOfAttributes(targetrel); attno++)
1328 {
1329 Form_pg_attribute attr = TupleDescAttr(targetrel->rd_att, attno);
1330 char *name;
1331
1332 if (attr->attisdropped)
1333 {
1334 /*
1335 * can't use atttypid here, but it doesn't really matter what type
1336 * the Const claims to be.
1337 */
1338 var = (Var *) makeNullConst(INT4OID, -1, InvalidOid);
1339 name = NULL;
1340 }
1341 else
1342 {
1343 var = makeVar(exclRelIndex, attno + 1,
1344 attr->atttypid, attr->atttypmod,
1345 attr->attcollation,
1346 0);
1347 name = pstrdup(NameStr(attr->attname));
1348 }
1349
1350 te = makeTargetEntry((Expr *) var,
1351 attno + 1,
1352 name,
1353 false);
1354
1355 result = lappend(result, te);
1356 }
1357
1358 /*
1359 * Add a whole-row-Var entry to support references to "EXCLUDED.*". Like
1360 * the other entries in the EXCLUDED tlist, its resno must match the Var's
1361 * varattno, else the wrong things happen while resolving references in
1362 * setrefs.c. This is against normal conventions for targetlists, but
1363 * it's okay since we don't use this as a real tlist.
1364 */
1365 var = makeVar(exclRelIndex, InvalidAttrNumber,
1366 targetrel->rd_rel->reltype,
1367 -1, InvalidOid, 0);
1368 te = makeTargetEntry((Expr *) var, InvalidAttrNumber, NULL, true);
1369 result = lappend(result, te);
1370
1371 return result;
1372}
#define InvalidAttrNumber
Definition: attnum.h:23
#define NameStr(name)
Definition: c.h:703
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:341
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:242
char * pstrdup(const char *in)
Definition: mcxt.c:1696
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define NIL
Definition: pg_list.h:68
#define InvalidOid
Definition: postgres_ext.h:37
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:511
Definition: pg_list.h:54
TupleDesc rd_att
Definition: rel.h:112
Form_pg_class rd_rel
Definition: rel.h:111
Definition: primnodes.h:261
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:153
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 3432 of file analyze.c.

3433{
3434 Assert(strength != LCS_NONE); /* else caller error */
3435
3436 if (qry->setOperations)
3437 ereport(ERROR,
3438 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3439 /*------
3440 translator: %s is a SQL row locking clause such as FOR UPDATE */
3441 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
3442 LCS_asString(strength))));
3443 if (qry->distinctClause != NIL)
3444 ereport(ERROR,
3445 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3446 /*------
3447 translator: %s is a SQL row locking clause such as FOR UPDATE */
3448 errmsg("%s is not allowed with DISTINCT clause",
3449 LCS_asString(strength))));
3450 if (qry->groupClause != NIL || qry->groupingSets != NIL)
3451 ereport(ERROR,
3452 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3453 /*------
3454 translator: %s is a SQL row locking clause such as FOR UPDATE */
3455 errmsg("%s is not allowed with GROUP BY clause",
3456 LCS_asString(strength))));
3457 if (qry->havingQual != NULL)
3458 ereport(ERROR,
3459 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3460 /*------
3461 translator: %s is a SQL row locking clause such as FOR UPDATE */
3462 errmsg("%s is not allowed with HAVING clause",
3463 LCS_asString(strength))));
3464 if (qry->hasAggs)
3465 ereport(ERROR,
3466 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3467 /*------
3468 translator: %s is a SQL row locking clause such as FOR UPDATE */
3469 errmsg("%s is not allowed with aggregate functions",
3470 LCS_asString(strength))));
3471 if (qry->hasWindowFuncs)
3472 ereport(ERROR,
3473 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3474 /*------
3475 translator: %s is a SQL row locking clause such as FOR UPDATE */
3476 errmsg("%s is not allowed with window functions",
3477 LCS_asString(strength))));
3478 if (qry->hasTargetSRFs)
3479 ereport(ERROR,
3480 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3481 /*------
3482 translator: %s is a SQL row locking clause such as FOR UPDATE */
3483 errmsg("%s is not allowed with set-returning functions in the target list",
3484 LCS_asString(strength))));
3485}
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
const char * LCS_asString(LockClauseStrength strength)
Definition: analyze.c:3407
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 3407 of file analyze.c.

3408{
3409 switch (strength)
3410 {
3411 case LCS_NONE:
3412 Assert(false);
3413 break;
3414 case LCS_FORKEYSHARE:
3415 return "FOR KEY SHARE";
3416 case LCS_FORSHARE:
3417 return "FOR SHARE";
3418 case LCS_FORNOKEYUPDATE:
3419 return "FOR NO KEY UPDATE";
3420 case LCS_FORUPDATE:
3421 return "FOR UPDATE";
3422 }
3423 return "FOR some"; /* shouldn't happen */
3424}
@ 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 2046 of file analyze.c.

2047{
2049 Oid sortop;
2050 Oid eqop;
2051 bool hashable;
2052
2053 /* determine the eqop and optional sortop */
2054 get_sort_group_operators(rescoltype,
2055 false, true, false,
2056 &sortop, &eqop, NULL,
2057 &hashable);
2058
2059 /*
2060 * The type cache doesn't believe that record is hashable (see
2061 * cache_record_field_properties()), but if the caller really needs hash
2062 * support, we can assume it does. Worst case, if any components of the
2063 * record don't support hashing, we will fail at execution.
2064 */
2065 if (require_hash && (rescoltype == RECORDOID || rescoltype == RECORDARRAYOID))
2066 hashable = true;
2067
2068 /* we don't have a tlist yet, so can't assign sortgrouprefs */
2069 grpcl->tleSortGroupRef = 0;
2070 grpcl->eqop = eqop;
2071 grpcl->sortop = sortop;
2072 grpcl->reverse_sort = false; /* Sort-op is "less than", or InvalidOid */
2073 grpcl->nulls_first = false; /* OK with or without sortop */
2074 grpcl->hashable = hashable;
2075
2076 return grpcl;
2077}
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:32
Index tleSortGroupRef
Definition: parsenodes.h:1447

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:332
static bool IsQueryIdEnabled(void)
Definition: queryjumble.h:77
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:396
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().

◆ stmt_requires_parse_analysis()

bool stmt_requires_parse_analysis ( RawStmt parseTree)

Definition at line 532 of file analyze.c.

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

References nodeTag, and RawStmt::stmt.

Referenced by analyze_requires_snapshot().

◆ transformInsertRow()

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

Definition at line 1098 of file analyze.c.

1101{
1102 List *result;
1103 ListCell *lc;
1104 ListCell *icols;
1105 ListCell *attnos;
1106
1107 /*
1108 * Check length of expr list. It must not have more expressions than
1109 * there are target columns. We allow fewer, but only if no explicit
1110 * columns list was given (the remaining columns are implicitly
1111 * defaulted). Note we must check this *after* transformation because
1112 * that could expand '*' into multiple items.
1113 */
1114 if (list_length(exprlist) > list_length(icolumns))
1115 ereport(ERROR,
1116 (errcode(ERRCODE_SYNTAX_ERROR),
1117 errmsg("INSERT has more expressions than target columns"),
1118 parser_errposition(pstate,
1119 exprLocation(list_nth(exprlist,
1120 list_length(icolumns))))));
1121 if (stmtcols != NIL &&
1122 list_length(exprlist) < list_length(icolumns))
1123 {
1124 /*
1125 * We can get here for cases like INSERT ... SELECT (a,b,c) FROM ...
1126 * where the user accidentally created a RowExpr instead of separate
1127 * columns. Add a suitable hint if that seems to be the problem,
1128 * because the main error message is quite misleading for this case.
1129 * (If there's no stmtcols, you'll get something about data type
1130 * mismatch, which is less misleading so we don't worry about giving a
1131 * hint in that case.)
1132 */
1133 ereport(ERROR,
1134 (errcode(ERRCODE_SYNTAX_ERROR),
1135 errmsg("INSERT has more target columns than expressions"),
1136 ((list_length(exprlist) == 1 &&
1137 count_rowexpr_columns(pstate, linitial(exprlist)) ==
1138 list_length(icolumns)) ?
1139 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),
1140 parser_errposition(pstate,
1141 exprLocation(list_nth(icolumns,
1142 list_length(exprlist))))));
1143 }
1144
1145 /*
1146 * Prepare columns for assignment to target table.
1147 */
1148 result = NIL;
1149 forthree(lc, exprlist, icols, icolumns, attnos, attrnos)
1150 {
1151 Expr *expr = (Expr *) lfirst(lc);
1152 ResTarget *col = lfirst_node(ResTarget, icols);
1153 int attno = lfirst_int(attnos);
1154
1155 expr = transformAssignedExpr(pstate, expr,
1157 col->name,
1158 attno,
1159 col->indirection,
1160 col->location);
1161
1162 if (strip_indirection)
1163 {
1164 /*
1165 * We need to remove top-level FieldStores and SubscriptingRefs,
1166 * as well as any CoerceToDomain appearing above one of those ---
1167 * but not a CoerceToDomain that isn't above one of those.
1168 */
1169 while (expr)
1170 {
1171 Expr *subexpr = expr;
1172
1173 while (IsA(subexpr, CoerceToDomain))
1174 {
1175 subexpr = ((CoerceToDomain *) subexpr)->arg;
1176 }
1177 if (IsA(subexpr, FieldStore))
1178 {
1179 FieldStore *fstore = (FieldStore *) subexpr;
1180
1181 expr = (Expr *) linitial(fstore->newvals);
1182 }
1183 else if (IsA(subexpr, SubscriptingRef))
1184 {
1185 SubscriptingRef *sbsref = (SubscriptingRef *) subexpr;
1186
1187 if (sbsref->refassgnexpr == NULL)
1188 break;
1189
1190 expr = sbsref->refassgnexpr;
1191 }
1192 else
1193 break;
1194 }
1195 }
1196
1197 result = lappend(result, expr);
1198 }
1199
1200 return result;
1201}
int errhint(const char *fmt,...)
Definition: elog.c:1317
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1388
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
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:1385
#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:1176
ParseLoc location
Definition: parsenodes.h:531
List * indirection
Definition: parsenodes.h:529
char * name
Definition: parsenodes.h:528
Expr * refassgnexpr
Definition: primnodes.h:719

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

2694{
2695 int save_nslen = list_length(pstate->p_namespace);
2696 int save_next_resno;
2697
2698 if (returningClause == NULL)
2699 return; /* nothing to do */
2700
2701 /*
2702 * Scan RETURNING WITH(...) options for OLD/NEW alias names. Complain if
2703 * there is any conflict with existing relations.
2704 */
2705 foreach_node(ReturningOption, option, returningClause->options)
2706 {
2707 switch (option->option)
2708 {
2710 if (qry->returningOldAlias != NULL)
2711 ereport(ERROR,
2712 errcode(ERRCODE_SYNTAX_ERROR),
2713 /* translator: %s is OLD or NEW */
2714 errmsg("%s cannot be specified multiple times", "OLD"),
2715 parser_errposition(pstate, option->location));
2716 qry->returningOldAlias = option->value;
2717 break;
2718
2720 if (qry->returningNewAlias != NULL)
2721 ereport(ERROR,
2722 errcode(ERRCODE_SYNTAX_ERROR),
2723 /* translator: %s is OLD or NEW */
2724 errmsg("%s cannot be specified multiple times", "NEW"),
2725 parser_errposition(pstate, option->location));
2726 qry->returningNewAlias = option->value;
2727 break;
2728
2729 default:
2730 elog(ERROR, "unrecognized returning option: %d", option->option);
2731 }
2732
2733 if (refnameNamespaceItem(pstate, NULL, option->value, -1, NULL) != NULL)
2734 ereport(ERROR,
2735 errcode(ERRCODE_DUPLICATE_ALIAS),
2736 errmsg("table name \"%s\" specified more than once",
2737 option->value),
2738 parser_errposition(pstate, option->location));
2739
2740 addNSItemForReturning(pstate, option->value,
2741 option->option == RETURNING_OPTION_OLD ?
2743 }
2744
2745 /*
2746 * If OLD/NEW alias names weren't explicitly specified, use "old"/"new"
2747 * unless masked by existing relations.
2748 */
2749 if (qry->returningOldAlias == NULL &&
2750 refnameNamespaceItem(pstate, NULL, "old", -1, NULL) == NULL)
2751 {
2752 qry->returningOldAlias = "old";
2754 }
2755 if (qry->returningNewAlias == NULL &&
2756 refnameNamespaceItem(pstate, NULL, "new", -1, NULL) == NULL)
2757 {
2758 qry->returningNewAlias = "new";
2760 }
2761
2762 /*
2763 * We need to assign resnos starting at one in the RETURNING list. Save
2764 * and restore the main tlist's value of p_next_resno, just in case
2765 * someone looks at it later (probably won't happen).
2766 */
2767 save_next_resno = pstate->p_next_resno;
2768 pstate->p_next_resno = 1;
2769
2770 /* transform RETURNING expressions identically to a SELECT targetlist */
2771 qry->returningList = transformTargetList(pstate,
2772 returningClause->exprs,
2773 exprKind);
2774
2775 /*
2776 * Complain if the nonempty tlist expanded to nothing (which is possible
2777 * if it contains only a star-expansion of a zero-column table). If we
2778 * allow this, the parsed Query will look like it didn't have RETURNING,
2779 * with results that would probably surprise the user.
2780 */
2781 if (qry->returningList == NIL)
2782 ereport(ERROR,
2783 (errcode(ERRCODE_SYNTAX_ERROR),
2784 errmsg("RETURNING must have at least one column"),
2785 parser_errposition(pstate,
2786 exprLocation(linitial(returningClause->exprs)))));
2787
2788 /* mark column origins */
2790
2791 /* resolve any still-unresolved output columns as being type text */
2792 if (pstate->p_resolve_unknowns)
2794
2795 /* restore state */
2796 pstate->p_namespace = list_truncate(pstate->p_namespace, save_nslen);
2797 pstate->p_next_resno = save_next_resno;
2798}
#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:1747
@ RETURNING_OPTION_OLD
Definition: parsenodes.h:1746
static void addNSItemForReturning(ParseState *pstate, const char *aliasname, VarReturningType returning_type)
Definition: analyze.c:2651
#define foreach_node(type, var, lst)
Definition: pg_list.h:496
@ VAR_RETURNING_OLD
Definition: primnodes.h:256
@ VAR_RETURNING_NEW
Definition: primnodes.h:257
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 396 of file analyze.c.

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

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

333{
334 Query *result;
335
336 /* Store RawStmt's length and location in pstate */
337 pstate->p_stmt_len = parseTree->stmt_len;
338 pstate->p_stmt_location = parseTree->stmt_location;
339
340 /* We're at top level, so allow SELECT INTO */
341 result = transformOptionalSelectInto(pstate, parseTree->stmt);
342
343 return result;
344}
static Query * transformOptionalSelectInto(ParseState *pstate, Node *parseTree)
Definition: analyze.c:357
ParseLoc p_stmt_location
Definition: parse_node.h:210
ParseLoc p_stmt_len
Definition: parse_node.h:211
ParseLoc stmt_location
Definition: parsenodes.h:2067
ParseLoc stmt_len
Definition: parsenodes.h:2068

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

2577{
2578 List *tlist = NIL;
2579 RTEPermissionInfo *target_perminfo;
2580 ListCell *orig_tl;
2581 ListCell *tl;
2582
2583 tlist = transformTargetList(pstate, origTlist,
2585
2586 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2589
2590 /* Prepare non-junk columns for assignment to target table */
2591 target_perminfo = pstate->p_target_nsitem->p_perminfo;
2592 orig_tl = list_head(origTlist);
2593
2594 foreach(tl, tlist)
2595 {
2596 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2597 ResTarget *origTarget;
2598 int attrno;
2599
2600 if (tle->resjunk)
2601 {
2602 /*
2603 * Resjunk nodes need no additional processing, but be sure they
2604 * have resnos that do not match any target columns; else rewriter
2605 * or planner might get confused. They don't need a resname
2606 * either.
2607 */
2608 tle->resno = (AttrNumber) pstate->p_next_resno++;
2609 tle->resname = NULL;
2610 continue;
2611 }
2612 if (orig_tl == NULL)
2613 elog(ERROR, "UPDATE target count mismatch --- internal error");
2614 origTarget = lfirst_node(ResTarget, orig_tl);
2615
2616 attrno = attnameAttNum(pstate->p_target_relation,
2617 origTarget->name, true);
2618 if (attrno == InvalidAttrNumber)
2619 ereport(ERROR,
2620 (errcode(ERRCODE_UNDEFINED_COLUMN),
2621 errmsg("column \"%s\" of relation \"%s\" does not exist",
2622 origTarget->name,
2624 (origTarget->indirection != NIL &&
2625 strcmp(origTarget->name, pstate->p_target_nsitem->p_names->aliasname) == 0) ?
2626 errhint("SET target columns cannot be qualified with the relation name.") : 0,
2627 parser_errposition(pstate, origTarget->location)));
2628
2629 updateTargetListEntry(pstate, tle, origTarget->name,
2630 attrno,
2631 origTarget->indirection,
2632 origTarget->location);
2633
2634 /* Mark the target column as requiring update permissions */
2635 target_perminfo->updatedCols = bms_add_member(target_perminfo->updatedCols,
2637
2638 orig_tl = lnext(origTlist, orig_tl);
2639 }
2640 if (orig_tl != NULL)
2641 elog(ERROR, "UPDATE target count mismatch --- internal error");
2642
2643 return tlist;
2644}
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:539
char * aliasname
Definition: primnodes.h:50
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:1304
AttrNumber resno
Definition: primnodes.h:2247
#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