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)
 
ListtransformReturningList (ParseState *pstate, List *returningList, 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 485 of file analyze.c.

486 {
487  /*
488  * Currently, this should return true in exactly the same cases that
489  * stmt_requires_parse_analysis() does, so we just invoke that function
490  * rather than duplicating it. We keep the two entry points separate for
491  * clarity of callers, since from the callers' standpoint these are
492  * different conditions.
493  *
494  * While there may someday be a statement type for which transformStmt()
495  * does something nontrivial and yet no snapshot is needed for that
496  * processing, it seems likely that making such a choice would be fragile.
497  * If you want to install an exception, document the reasoning for it in a
498  * comment.
499  */
500  return stmt_requires_parse_analysis(parseTree);
501 }
bool stmt_requires_parse_analysis(RawStmt *parseTree)
Definition: analyze.c:441

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

3532 {
3533  RowMarkClause *rc;
3534 
3535  Assert(strength != LCS_NONE); /* else caller error */
3536 
3537  /* If it's an explicit clause, make sure hasForUpdate gets set */
3538  if (!pushedDown)
3539  qry->hasForUpdate = true;
3540 
3541  /* Check for pre-existing entry for same rtindex */
3542  if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
3543  {
3544  /*
3545  * If the same RTE is specified with more than one locking strength,
3546  * use the strongest. (Reasonable, since you can't take both a shared
3547  * and exclusive lock at the same time; it'll end up being exclusive
3548  * anyway.)
3549  *
3550  * Similarly, if the same RTE is specified with more than one lock
3551  * wait policy, consider that NOWAIT wins over SKIP LOCKED, which in
3552  * turn wins over waiting for the lock (the default). This is a bit
3553  * more debatable but raising an error doesn't seem helpful. (Consider
3554  * for instance SELECT FOR UPDATE NOWAIT from a view that internally
3555  * contains a plain FOR UPDATE spec.) Having NOWAIT win over SKIP
3556  * LOCKED is reasonable since the former throws an error in case of
3557  * coming across a locked tuple, which may be undesirable in some
3558  * cases but it seems better than silently returning inconsistent
3559  * results.
3560  *
3561  * And of course pushedDown becomes false if any clause is explicit.
3562  */
3563  rc->strength = Max(rc->strength, strength);
3564  rc->waitPolicy = Max(rc->waitPolicy, waitPolicy);
3565  rc->pushedDown &= pushedDown;
3566  return;
3567  }
3568 
3569  /* Make a new RowMarkClause */
3570  rc = makeNode(RowMarkClause);
3571  rc->rti = rtindex;
3572  rc->strength = strength;
3573  rc->waitPolicy = waitPolicy;
3574  rc->pushedDown = pushedDown;
3575  qry->rowMarks = lappend(qry->rowMarks, rc);
3576 }
#define Max(x, y)
Definition: c.h:998
#define Assert(condition)
Definition: c.h:858
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:217
LockClauseStrength strength
Definition: parsenodes.h:1583
LockWaitPolicy waitPolicy
Definition: parsenodes.h:1584

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

1227 {
1228  List *result = NIL;
1229  int attno;
1230  Var *var;
1231  TargetEntry *te;
1232 
1233  /*
1234  * Note that resnos of the tlist must correspond to attnos of the
1235  * underlying relation, hence we need entries for dropped columns too.
1236  */
1237  for (attno = 0; attno < RelationGetNumberOfAttributes(targetrel); attno++)
1238  {
1239  Form_pg_attribute attr = TupleDescAttr(targetrel->rd_att, attno);
1240  char *name;
1241 
1242  if (attr->attisdropped)
1243  {
1244  /*
1245  * can't use atttypid here, but it doesn't really matter what type
1246  * the Const claims to be.
1247  */
1248  var = (Var *) makeNullConst(INT4OID, -1, InvalidOid);
1249  name = NULL;
1250  }
1251  else
1252  {
1253  var = makeVar(exclRelIndex, attno + 1,
1254  attr->atttypid, attr->atttypmod,
1255  attr->attcollation,
1256  0);
1257  name = pstrdup(NameStr(attr->attname));
1258  }
1259 
1260  te = makeTargetEntry((Expr *) var,
1261  attno + 1,
1262  name,
1263  false);
1264 
1265  result = lappend(result, te);
1266  }
1267 
1268  /*
1269  * Add a whole-row-Var entry to support references to "EXCLUDED.*". Like
1270  * the other entries in the EXCLUDED tlist, its resno must match the Var's
1271  * varattno, else the wrong things happen while resolving references in
1272  * setrefs.c. This is against normal conventions for targetlists, but
1273  * it's okay since we don't use this as a real tlist.
1274  */
1275  var = makeVar(exclRelIndex, InvalidAttrNumber,
1276  targetrel->rd_rel->reltype,
1277  -1, InvalidOid, 0);
1278  te = makeTargetEntry((Expr *) var, InvalidAttrNumber, NULL, true);
1279  result = lappend(result, te);
1280 
1281  return result;
1282 }
#define InvalidAttrNumber
Definition: attnum.h:23
#define NameStr(name)
Definition: c.h:746
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:240
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:339
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
char * pstrdup(const char *in)
Definition: mcxt.c:1695
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
#define NIL
Definition: pg_list.h:68
#define InvalidOid
Definition: postgres_ext.h:36
#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:248
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
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 3238 of file analyze.c.

3239 {
3240  Assert(strength != LCS_NONE); /* else caller error */
3241 
3242  if (qry->setOperations)
3243  ereport(ERROR,
3244  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3245  /*------
3246  translator: %s is a SQL row locking clause such as FOR UPDATE */
3247  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
3248  LCS_asString(strength))));
3249  if (qry->distinctClause != NIL)
3250  ereport(ERROR,
3251  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3252  /*------
3253  translator: %s is a SQL row locking clause such as FOR UPDATE */
3254  errmsg("%s is not allowed with DISTINCT clause",
3255  LCS_asString(strength))));
3256  if (qry->groupClause != NIL || qry->groupingSets != NIL)
3257  ereport(ERROR,
3258  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3259  /*------
3260  translator: %s is a SQL row locking clause such as FOR UPDATE */
3261  errmsg("%s is not allowed with GROUP BY clause",
3262  LCS_asString(strength))));
3263  if (qry->havingQual != NULL)
3264  ereport(ERROR,
3265  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3266  /*------
3267  translator: %s is a SQL row locking clause such as FOR UPDATE */
3268  errmsg("%s is not allowed with HAVING clause",
3269  LCS_asString(strength))));
3270  if (qry->hasAggs)
3271  ereport(ERROR,
3272  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3273  /*------
3274  translator: %s is a SQL row locking clause such as FOR UPDATE */
3275  errmsg("%s is not allowed with aggregate functions",
3276  LCS_asString(strength))));
3277  if (qry->hasWindowFuncs)
3278  ereport(ERROR,
3279  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3280  /*------
3281  translator: %s is a SQL row locking clause such as FOR UPDATE */
3282  errmsg("%s is not allowed with window functions",
3283  LCS_asString(strength))));
3284  if (qry->hasTargetSRFs)
3285  ereport(ERROR,
3286  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3287  /*------
3288  translator: %s is a SQL row locking clause such as FOR UPDATE */
3289  errmsg("%s is not allowed with set-returning functions in the target list",
3290  LCS_asString(strength))));
3291 }
int errcode(int sqlerrcode)
Definition: elog.c:857
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:3213
Node * setOperations
Definition: parsenodes.h:219
List * groupClause
Definition: parsenodes.h:200
Node * havingQual
Definition: parsenodes.h:205
List * groupingSets
Definition: parsenodes.h:203
List * distinctClause
Definition: parsenodes.h:209

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

3214 {
3215  switch (strength)
3216  {
3217  case LCS_NONE:
3218  Assert(false);
3219  break;
3220  case LCS_FORKEYSHARE:
3221  return "FOR KEY SHARE";
3222  case LCS_FORSHARE:
3223  return "FOR SHARE";
3224  case LCS_FORNOKEYUPDATE:
3225  return "FOR NO KEY UPDATE";
3226  case LCS_FORUPDATE:
3227  return "FOR UPDATE";
3228  }
3229  return "FOR some"; /* shouldn't happen */
3230 }
@ 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 1956 of file analyze.c.

1957 {
1959  Oid sortop;
1960  Oid eqop;
1961  bool hashable;
1962 
1963  /* determine the eqop and optional sortop */
1964  get_sort_group_operators(rescoltype,
1965  false, true, false,
1966  &sortop, &eqop, NULL,
1967  &hashable);
1968 
1969  /*
1970  * The type cache doesn't believe that record is hashable (see
1971  * cache_record_field_properties()), but if the caller really needs hash
1972  * support, we can assume it does. Worst case, if any components of the
1973  * record don't support hashing, we will fail at execution.
1974  */
1975  if (require_hash && (rescoltype == RECORDOID || rescoltype == RECORDARRAYOID))
1976  hashable = true;
1977 
1978  /* we don't have a tlist yet, so can't assign sortgrouprefs */
1979  grpcl->tleSortGroupRef = 0;
1980  grpcl->eqop = eqop;
1981  grpcl->sortop = sortop;
1982  grpcl->nulls_first = false; /* OK with or without sortop */
1983  grpcl->hashable = hashable;
1984 
1985  return grpcl;
1986 }
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:31
Index tleSortGroupRef
Definition: parsenodes.h:1442

References SortGroupClause::eqop, get_sort_group_operators(), makeNode, SortGroupClause::nulls_first, 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 104 of file analyze.c.

107 {
108  ParseState *pstate = make_parsestate(NULL);
109  Query *query;
110  JumbleState *jstate = NULL;
111 
112  Assert(sourceText != NULL); /* required as of 8.4 */
113 
114  pstate->p_sourcetext = sourceText;
115 
116  if (numParams > 0)
117  setup_parse_fixed_parameters(pstate, paramTypes, numParams);
118 
119  pstate->p_queryEnv = queryEnv;
120 
121  query = transformTopLevelStmt(pstate, parseTree);
122 
123  if (IsQueryIdEnabled())
124  jstate = JumbleQuery(query);
125 
127  (*post_parse_analyze_hook) (pstate, query, jstate);
128 
129  free_parsestate(pstate);
130 
131  pgstat_report_query_id(query->queryId, false);
132 
133  return query;
134 }
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:67
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:248
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:58
static bool IsQueryIdEnabled(void)
Definition: queryjumble.h:77
JumbleState * JumbleQuery(Query *query)
QueryEnvironment * p_queryEnv
Definition: parse_node.h:220
const char * p_sourcetext
Definition: parse_node.h:193

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

147 {
148  ParseState *pstate = make_parsestate(NULL);
149  Query *query;
150  JumbleState *jstate = NULL;
151 
152  Assert(sourceText != NULL); /* required as of 8.4 */
153 
154  pstate->p_sourcetext = sourceText;
155 
156  setup_parse_variable_parameters(pstate, paramTypes, numParams);
157 
158  pstate->p_queryEnv = queryEnv;
159 
160  query = transformTopLevelStmt(pstate, parseTree);
161 
162  /* make sure all is well with parameter types */
163  check_variable_parameters(pstate, query);
164 
165  if (IsQueryIdEnabled())
166  jstate = JumbleQuery(query);
167 
169  (*post_parse_analyze_hook) (pstate, query, jstate);
170 
171  free_parsestate(pstate);
172 
173  pgstat_report_query_id(query->queryId, false);
174 
175  return query;
176 }
void check_variable_parameters(ParseState *pstate, Query *query)
Definition: parse_param.c:268
void setup_parse_variable_parameters(ParseState *pstate, Oid **paramTypes, int *numParams)
Definition: parse_param.c:83

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

189 {
190  ParseState *pstate = make_parsestate(NULL);
191  Query *query;
192  JumbleState *jstate = NULL;
193 
194  Assert(sourceText != NULL); /* required as of 8.4 */
195 
196  pstate->p_sourcetext = sourceText;
197  pstate->p_queryEnv = queryEnv;
198  (*parserSetup) (pstate, parserSetupArg);
199 
200  query = transformTopLevelStmt(pstate, parseTree);
201 
202  if (IsQueryIdEnabled())
203  jstate = JumbleQuery(query);
204 
206  (*post_parse_analyze_hook) (pstate, query, jstate);
207 
208  free_parsestate(pstate);
209 
210  pgstat_report_query_id(query->queryId, false);
211 
212  return query;
213 }

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

225 {
226  ParseState *pstate = make_parsestate(parentParseState);
227  Query *query;
228 
229  pstate->p_parent_cte = parentCTE;
230  pstate->p_locked_from_parent = locked_from_parent;
231  pstate->p_resolve_unknowns = resolve_unknowns;
232 
233  query = transformStmt(pstate, parseTree);
234 
235  free_parsestate(pstate);
236 
237  return query;
238 }
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:311
bool p_locked_from_parent
Definition: parse_node.h:215
bool p_resolve_unknowns
Definition: parse_node.h:217
CommonTableExpr * p_parent_cte
Definition: parse_node.h:206

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

442 {
443  bool result;
444 
445  switch (nodeTag(parseTree->stmt))
446  {
447  /*
448  * Optimizable statements
449  */
450  case T_InsertStmt:
451  case T_DeleteStmt:
452  case T_UpdateStmt:
453  case T_MergeStmt:
454  case T_SelectStmt:
455  case T_ReturnStmt:
456  case T_PLAssignStmt:
457  result = true;
458  break;
459 
460  /*
461  * Special cases
462  */
463  case T_DeclareCursorStmt:
464  case T_ExplainStmt:
465  case T_CreateTableAsStmt:
466  case T_CallStmt:
467  result = true;
468  break;
469 
470  default:
471  /* all other statements just get wrapped in a CMD_UTILITY Query */
472  result = false;
473  break;
474  }
475 
476  return result;
477 }
#define nodeTag(nodeptr)
Definition: nodes.h:133
Node * stmt
Definition: parsenodes.h:2025

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

1011 {
1012  List *result;
1013  ListCell *lc;
1014  ListCell *icols;
1015  ListCell *attnos;
1016 
1017  /*
1018  * Check length of expr list. It must not have more expressions than
1019  * there are target columns. We allow fewer, but only if no explicit
1020  * columns list was given (the remaining columns are implicitly
1021  * defaulted). Note we must check this *after* transformation because
1022  * that could expand '*' into multiple items.
1023  */
1024  if (list_length(exprlist) > list_length(icolumns))
1025  ereport(ERROR,
1026  (errcode(ERRCODE_SYNTAX_ERROR),
1027  errmsg("INSERT has more expressions than target columns"),
1028  parser_errposition(pstate,
1029  exprLocation(list_nth(exprlist,
1030  list_length(icolumns))))));
1031  if (stmtcols != NIL &&
1032  list_length(exprlist) < list_length(icolumns))
1033  {
1034  /*
1035  * We can get here for cases like INSERT ... SELECT (a,b,c) FROM ...
1036  * where the user accidentally created a RowExpr instead of separate
1037  * columns. Add a suitable hint if that seems to be the problem,
1038  * because the main error message is quite misleading for this case.
1039  * (If there's no stmtcols, you'll get something about data type
1040  * mismatch, which is less misleading so we don't worry about giving a
1041  * hint in that case.)
1042  */
1043  ereport(ERROR,
1044  (errcode(ERRCODE_SYNTAX_ERROR),
1045  errmsg("INSERT has more target columns than expressions"),
1046  ((list_length(exprlist) == 1 &&
1047  count_rowexpr_columns(pstate, linitial(exprlist)) ==
1048  list_length(icolumns)) ?
1049  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),
1050  parser_errposition(pstate,
1051  exprLocation(list_nth(icolumns,
1052  list_length(exprlist))))));
1053  }
1054 
1055  /*
1056  * Prepare columns for assignment to target table.
1057  */
1058  result = NIL;
1059  forthree(lc, exprlist, icols, icolumns, attnos, attrnos)
1060  {
1061  Expr *expr = (Expr *) lfirst(lc);
1062  ResTarget *col = lfirst_node(ResTarget, icols);
1063  int attno = lfirst_int(attnos);
1064 
1065  expr = transformAssignedExpr(pstate, expr,
1067  col->name,
1068  attno,
1069  col->indirection,
1070  col->location);
1071 
1072  if (strip_indirection)
1073  {
1074  /*
1075  * We need to remove top-level FieldStores and SubscriptingRefs,
1076  * as well as any CoerceToDomain appearing above one of those ---
1077  * but not a CoerceToDomain that isn't above one of those.
1078  */
1079  while (expr)
1080  {
1081  Expr *subexpr = expr;
1082 
1083  while (IsA(subexpr, CoerceToDomain))
1084  {
1085  subexpr = ((CoerceToDomain *) subexpr)->arg;
1086  }
1087  if (IsA(subexpr, FieldStore))
1088  {
1089  FieldStore *fstore = (FieldStore *) subexpr;
1090 
1091  expr = (Expr *) linitial(fstore->newvals);
1092  }
1093  else if (IsA(subexpr, SubscriptingRef))
1094  {
1095  SubscriptingRef *sbsref = (SubscriptingRef *) subexpr;
1096 
1097  if (sbsref->refassgnexpr == NULL)
1098  break;
1099 
1100  expr = sbsref->refassgnexpr;
1101  }
1102  else
1103  break;
1104  }
1105  }
1106 
1107  result = lappend(result, expr);
1108  }
1109 
1110  return result;
1111 }
int errhint(const char *fmt,...)
Definition: elog.c:1317
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1386
#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:452
static int count_rowexpr_columns(ParseState *pstate, Node *expr)
Definition: analyze.c:1295
#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
#define linitial(l)
Definition: pg_list.h:178
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
List * newvals
Definition: primnodes.h:1160
ParseLoc location
Definition: parsenodes.h:520
List * indirection
Definition: parsenodes.h:518
char * name
Definition: parsenodes.h:517
Expr * refassgnexpr
Definition: primnodes.h:703

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().

◆ transformReturningList()

List* transformReturningList ( ParseState pstate,
List returningList,
ParseExprKind  exprKind 
)

Definition at line 2560 of file analyze.c.

2562 {
2563  List *rlist;
2564  int save_next_resno;
2565 
2566  if (returningList == NIL)
2567  return NIL; /* nothing to do */
2568 
2569  /*
2570  * We need to assign resnos starting at one in the RETURNING list. Save
2571  * and restore the main tlist's value of p_next_resno, just in case
2572  * someone looks at it later (probably won't happen).
2573  */
2574  save_next_resno = pstate->p_next_resno;
2575  pstate->p_next_resno = 1;
2576 
2577  /* transform RETURNING identically to a SELECT targetlist */
2578  rlist = transformTargetList(pstate, returningList, exprKind);
2579 
2580  /*
2581  * Complain if the nonempty tlist expanded to nothing (which is possible
2582  * if it contains only a star-expansion of a zero-column table). If we
2583  * allow this, the parsed Query will look like it didn't have RETURNING,
2584  * with results that would probably surprise the user.
2585  */
2586  if (rlist == NIL)
2587  ereport(ERROR,
2588  (errcode(ERRCODE_SYNTAX_ERROR),
2589  errmsg("RETURNING must have at least one column"),
2590  parser_errposition(pstate,
2591  exprLocation(linitial(returningList)))));
2592 
2593  /* mark column origins */
2594  markTargetListOrigins(pstate, rlist);
2595 
2596  /* resolve any still-unresolved output columns as being type text */
2597  if (pstate->p_resolve_unknowns)
2598  resolveTargetListUnknowns(pstate, rlist);
2599 
2600  /* restore state */
2601  pstate->p_next_resno = save_next_resno;
2602 
2603  return rlist;
2604 }
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
int p_next_resno
Definition: parse_node.h:212

References ereport, errcode(), errmsg(), ERROR, exprLocation(), linitial, markTargetListOrigins(), NIL, ParseState::p_next_resno, ParseState::p_resolve_unknowns, parser_errposition(), resolveTargetListUnknowns(), and transformTargetList().

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

◆ transformStmt()

Query* transformStmt ( ParseState pstate,
Node parseTree 
)

Definition at line 311 of file analyze.c.

312 {
313  Query *result;
314 
315  /*
316  * We apply RAW_EXPRESSION_COVERAGE_TEST testing to basic DML statements;
317  * we can't just run it on everything because raw_expression_tree_walker()
318  * doesn't claim to handle utility statements.
319  */
320 #ifdef RAW_EXPRESSION_COVERAGE_TEST
321  switch (nodeTag(parseTree))
322  {
323  case T_SelectStmt:
324  case T_InsertStmt:
325  case T_UpdateStmt:
326  case T_DeleteStmt:
327  case T_MergeStmt:
328  (void) test_raw_expression_coverage(parseTree, NULL);
329  break;
330  default:
331  break;
332  }
333 #endif /* RAW_EXPRESSION_COVERAGE_TEST */
334 
335  /*
336  * Caution: when changing the set of statement types that have non-default
337  * processing here, see also stmt_requires_parse_analysis() and
338  * analyze_requires_snapshot().
339  */
340  switch (nodeTag(parseTree))
341  {
342  /*
343  * Optimizable statements
344  */
345  case T_InsertStmt:
346  result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
347  break;
348 
349  case T_DeleteStmt:
350  result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
351  break;
352 
353  case T_UpdateStmt:
354  result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
355  break;
356 
357  case T_MergeStmt:
358  result = transformMergeStmt(pstate, (MergeStmt *) parseTree);
359  break;
360 
361  case T_SelectStmt:
362  {
363  SelectStmt *n = (SelectStmt *) parseTree;
364 
365  if (n->valuesLists)
366  result = transformValuesClause(pstate, n);
367  else if (n->op == SETOP_NONE)
368  result = transformSelectStmt(pstate, n);
369  else
370  result = transformSetOperationStmt(pstate, n);
371  }
372  break;
373 
374  case T_ReturnStmt:
375  result = transformReturnStmt(pstate, (ReturnStmt *) parseTree);
376  break;
377 
378  case T_PLAssignStmt:
379  result = transformPLAssignStmt(pstate,
380  (PLAssignStmt *) parseTree);
381  break;
382 
383  /*
384  * Special cases
385  */
386  case T_DeclareCursorStmt:
387  result = transformDeclareCursorStmt(pstate,
388  (DeclareCursorStmt *) parseTree);
389  break;
390 
391  case T_ExplainStmt:
392  result = transformExplainStmt(pstate,
393  (ExplainStmt *) parseTree);
394  break;
395 
396  case T_CreateTableAsStmt:
397  result = transformCreateTableAsStmt(pstate,
398  (CreateTableAsStmt *) parseTree);
399  break;
400 
401  case T_CallStmt:
402  result = transformCallStmt(pstate,
403  (CallStmt *) parseTree);
404  break;
405 
406  default:
407 
408  /*
409  * other statements don't require any transformation; just return
410  * the original parsetree with a Query node plastered on top.
411  */
412  result = makeNode(Query);
413  result->commandType = CMD_UTILITY;
414  result->utilityStmt = (Node *) parseTree;
415  break;
416  }
417 
418  /* Mark as original query until we learn differently */
419  result->querySource = QSRC_ORIGINAL;
420  result->canSetTag = true;
421 
422  return result;
423 }
@ CMD_UTILITY
Definition: nodes.h:270
Query * transformMergeStmt(ParseState *pstate, MergeStmt *stmt)
Definition: parse_merge.c:107
@ SETOP_NONE
Definition: parsenodes.h:2113
@ QSRC_ORIGINAL
Definition: parsenodes.h:36
static Query * transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
Definition: analyze.c:508
static Query * transformReturnStmt(ParseState *pstate, ReturnStmt *stmt)
Definition: analyze.c:2388
static Query * transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt)
Definition: analyze.c:2619
static Query * transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
Definition: analyze.c:3013
static Query * transformCallStmt(ParseState *pstate, CallStmt *stmt)
Definition: analyze.c:3088
static Query * transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1699
static Query * transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
Definition: analyze.c:2419
static Query * transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1337
static Query * transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
Definition: analyze.c:2961
static Query * transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
Definition: analyze.c:2868
static Query * transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
Definition: analyze.c:580
static Query * transformValuesClause(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1480
Definition: nodes.h:129
CmdType commandType
Definition: parsenodes.h:121
Node * utilityStmt
Definition: parsenodes.h:136
List * valuesLists
Definition: parsenodes.h:2145
SetOperation op
Definition: parsenodes.h:2161

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

249 {
250  Query *result;
251 
252  /* We're at top level, so allow SELECT INTO */
253  result = transformOptionalSelectInto(pstate, parseTree->stmt);
254 
255  result->stmt_location = parseTree->stmt_location;
256  result->stmt_len = parseTree->stmt_len;
257 
258  return result;
259 }
static Query * transformOptionalSelectInto(ParseState *pstate, Node *parseTree)
Definition: analyze.c:272
ParseLoc stmt_location
Definition: parsenodes.h:238
ParseLoc stmt_location
Definition: parsenodes.h:2026
ParseLoc stmt_len
Definition: parsenodes.h:2027

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

2486 {
2487  List *tlist = NIL;
2488  RTEPermissionInfo *target_perminfo;
2489  ListCell *orig_tl;
2490  ListCell *tl;
2491 
2492  tlist = transformTargetList(pstate, origTlist,
2494 
2495  /* Prepare to assign non-conflicting resnos to resjunk attributes */
2498 
2499  /* Prepare non-junk columns for assignment to target table */
2500  target_perminfo = pstate->p_target_nsitem->p_perminfo;
2501  orig_tl = list_head(origTlist);
2502 
2503  foreach(tl, tlist)
2504  {
2505  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2506  ResTarget *origTarget;
2507  int attrno;
2508 
2509  if (tle->resjunk)
2510  {
2511  /*
2512  * Resjunk nodes need no additional processing, but be sure they
2513  * have resnos that do not match any target columns; else rewriter
2514  * or planner might get confused. They don't need a resname
2515  * either.
2516  */
2517  tle->resno = (AttrNumber) pstate->p_next_resno++;
2518  tle->resname = NULL;
2519  continue;
2520  }
2521  if (orig_tl == NULL)
2522  elog(ERROR, "UPDATE target count mismatch --- internal error");
2523  origTarget = lfirst_node(ResTarget, orig_tl);
2524 
2525  attrno = attnameAttNum(pstate->p_target_relation,
2526  origTarget->name, true);
2527  if (attrno == InvalidAttrNumber)
2528  ereport(ERROR,
2529  (errcode(ERRCODE_UNDEFINED_COLUMN),
2530  errmsg("column \"%s\" of relation \"%s\" does not exist",
2531  origTarget->name,
2533  (origTarget->indirection != NIL &&
2534  strcmp(origTarget->name, pstate->p_target_nsitem->p_names->aliasname) == 0) ?
2535  errhint("SET target columns cannot be qualified with the relation name.") : 0,
2536  parser_errposition(pstate, origTarget->location)));
2537 
2538  updateTargetListEntry(pstate, tle, origTarget->name,
2539  attrno,
2540  origTarget->indirection,
2541  origTarget->location);
2542 
2543  /* Mark the target column as requiring update permissions */
2544  target_perminfo->updatedCols = bms_add_member(target_perminfo->updatedCols,
2546 
2547  orig_tl = lnext(origTlist, orig_tl);
2548  }
2549  if (orig_tl != NULL)
2550  elog(ERROR, "UPDATE target count mismatch --- internal error");
2551 
2552  return tlist;
2553 }
int16 AttrNumber
Definition: attnum.h:21
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
#define elog(elevel,...)
Definition: elog.h:224
@ 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:619
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:289
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:208
Relation p_target_relation
Definition: parse_node.h:207
Bitmapset * updatedCols
Definition: parsenodes.h:1299
AttrNumber resno
Definition: primnodes.h:2194
#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