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)
 
QuerytransformTopLevelStmt (ParseState *pstate, RawStmt *parseTree)
 
QuerytransformStmt (ParseState *pstate, Node *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 430 of file analyze.c.

431 {
432  bool result;
433 
434  switch (nodeTag(parseTree->stmt))
435  {
436  /*
437  * Optimizable statements
438  */
439  case T_InsertStmt:
440  case T_DeleteStmt:
441  case T_UpdateStmt:
442  case T_MergeStmt:
443  case T_SelectStmt:
444  case T_PLAssignStmt:
445  result = true;
446  break;
447 
448  /*
449  * Special cases
450  */
451  case T_DeclareCursorStmt:
452  case T_ExplainStmt:
453  case T_CreateTableAsStmt:
454  /* yes, because we must analyze the contained statement */
455  result = true;
456  break;
457 
458  default:
459  /* other utility statements don't have any real parse analysis */
460  result = false;
461  break;
462  }
463 
464  return result;
465 }
#define nodeTag(nodeptr)
Definition: nodes.h:133
Node * stmt
Definition: parsenodes.h:1734

References nodeTag, and RawStmt::stmt.

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

3449 {
3450  RowMarkClause *rc;
3451 
3452  Assert(strength != LCS_NONE); /* else caller error */
3453 
3454  /* If it's an explicit clause, make sure hasForUpdate gets set */
3455  if (!pushedDown)
3456  qry->hasForUpdate = true;
3457 
3458  /* Check for pre-existing entry for same rtindex */
3459  if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
3460  {
3461  /*
3462  * If the same RTE is specified with more than one locking strength,
3463  * use the strongest. (Reasonable, since you can't take both a shared
3464  * and exclusive lock at the same time; it'll end up being exclusive
3465  * anyway.)
3466  *
3467  * Similarly, if the same RTE is specified with more than one lock
3468  * wait policy, consider that NOWAIT wins over SKIP LOCKED, which in
3469  * turn wins over waiting for the lock (the default). This is a bit
3470  * more debatable but raising an error doesn't seem helpful. (Consider
3471  * for instance SELECT FOR UPDATE NOWAIT from a view that internally
3472  * contains a plain FOR UPDATE spec.) Having NOWAIT win over SKIP
3473  * LOCKED is reasonable since the former throws an error in case of
3474  * coming across a locked tuple, which may be undesirable in some
3475  * cases but it seems better than silently returning inconsistent
3476  * results.
3477  *
3478  * And of course pushedDown becomes false if any clause is explicit.
3479  */
3480  rc->strength = Max(rc->strength, strength);
3481  rc->waitPolicy = Max(rc->waitPolicy, waitPolicy);
3482  rc->pushedDown &= pushedDown;
3483  return;
3484  }
3485 
3486  /* Make a new RowMarkClause */
3487  rc = makeNode(RowMarkClause);
3488  rc->rti = rtindex;
3489  rc->strength = strength;
3490  rc->waitPolicy = waitPolicy;
3491  rc->pushedDown = pushedDown;
3492  qry->rowMarks = lappend(qry->rowMarks, rc);
3493 }
#define Max(x, y)
Definition: c.h:982
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:338
@ LCS_NONE
Definition: lockoptions.h:23
#define makeNode(_type_)
Definition: nodes.h:176
RowMarkClause * get_parse_rowmark(Query *qry, Index rtindex)
List * rowMarks
Definition: parsenodes.h:215
LockClauseStrength strength
Definition: parsenodes.h:1533
LockWaitPolicy waitPolicy
Definition: parsenodes.h:1534

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

1178 {
1179  List *result = NIL;
1180  int attno;
1181  Var *var;
1182  TargetEntry *te;
1183 
1184  /*
1185  * Note that resnos of the tlist must correspond to attnos of the
1186  * underlying relation, hence we need entries for dropped columns too.
1187  */
1188  for (attno = 0; attno < RelationGetNumberOfAttributes(targetrel); attno++)
1189  {
1190  Form_pg_attribute attr = TupleDescAttr(targetrel->rd_att, attno);
1191  char *name;
1192 
1193  if (attr->attisdropped)
1194  {
1195  /*
1196  * can't use atttypid here, but it doesn't really matter what type
1197  * the Const claims to be.
1198  */
1199  var = (Var *) makeNullConst(INT4OID, -1, InvalidOid);
1200  name = NULL;
1201  }
1202  else
1203  {
1204  var = makeVar(exclRelIndex, attno + 1,
1205  attr->atttypid, attr->atttypmod,
1206  attr->attcollation,
1207  0);
1208  name = pstrdup(NameStr(attr->attname));
1209  }
1210 
1211  te = makeTargetEntry((Expr *) var,
1212  attno + 1,
1213  name,
1214  false);
1215 
1216  result = lappend(result, te);
1217  }
1218 
1219  /*
1220  * Add a whole-row-Var entry to support references to "EXCLUDED.*". Like
1221  * the other entries in the EXCLUDED tlist, its resno must match the Var's
1222  * varattno, else the wrong things happen while resolving references in
1223  * setrefs.c. This is against normal conventions for targetlists, but
1224  * it's okay since we don't use this as a real tlist.
1225  */
1226  var = makeVar(exclRelIndex, InvalidAttrNumber,
1227  targetrel->rd_rel->reltype,
1228  -1, InvalidOid, 0);
1229  te = makeTargetEntry((Expr *) var, InvalidAttrNumber, NULL, true);
1230  result = lappend(result, te);
1231 
1232  return result;
1233 }
#define InvalidAttrNumber
Definition: attnum.h:23
#define NameStr(name)
Definition: c.h:730
const char * name
Definition: encode.c:571
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:1624
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define NIL
Definition: pg_list.h:68
#define InvalidOid
Definition: postgres_ext.h:36
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:507
Definition: pg_list.h:54
TupleDesc rd_att
Definition: rel.h:111
Form_pg_class rd_rel
Definition: rel.h:110
Definition: primnodes.h:223
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

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

3156 {
3157  Assert(strength != LCS_NONE); /* else caller error */
3158 
3159  if (qry->setOperations)
3160  ereport(ERROR,
3161  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3162  /*------
3163  translator: %s is a SQL row locking clause such as FOR UPDATE */
3164  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
3165  LCS_asString(strength))));
3166  if (qry->distinctClause != NIL)
3167  ereport(ERROR,
3168  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3169  /*------
3170  translator: %s is a SQL row locking clause such as FOR UPDATE */
3171  errmsg("%s is not allowed with DISTINCT clause",
3172  LCS_asString(strength))));
3173  if (qry->groupClause != NIL || qry->groupingSets != NIL)
3174  ereport(ERROR,
3175  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3176  /*------
3177  translator: %s is a SQL row locking clause such as FOR UPDATE */
3178  errmsg("%s is not allowed with GROUP BY clause",
3179  LCS_asString(strength))));
3180  if (qry->havingQual != NULL)
3181  ereport(ERROR,
3182  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3183  /*------
3184  translator: %s is a SQL row locking clause such as FOR UPDATE */
3185  errmsg("%s is not allowed with HAVING clause",
3186  LCS_asString(strength))));
3187  if (qry->hasAggs)
3188  ereport(ERROR,
3189  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3190  /*------
3191  translator: %s is a SQL row locking clause such as FOR UPDATE */
3192  errmsg("%s is not allowed with aggregate functions",
3193  LCS_asString(strength))));
3194  if (qry->hasWindowFuncs)
3195  ereport(ERROR,
3196  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3197  /*------
3198  translator: %s is a SQL row locking clause such as FOR UPDATE */
3199  errmsg("%s is not allowed with window functions",
3200  LCS_asString(strength))));
3201  if (qry->hasTargetSRFs)
3202  ereport(ERROR,
3203  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3204  /*------
3205  translator: %s is a SQL row locking clause such as FOR UPDATE */
3206  errmsg("%s is not allowed with set-returning functions in the target list",
3207  LCS_asString(strength))));
3208 }
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
const char * LCS_asString(LockClauseStrength strength)
Definition: analyze.c:3130
Node * setOperations
Definition: parsenodes.h:217
List * groupClause
Definition: parsenodes.h:198
Node * havingQual
Definition: parsenodes.h:203
List * groupingSets
Definition: parsenodes.h:201
List * distinctClause
Definition: parsenodes.h:207

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

3131 {
3132  switch (strength)
3133  {
3134  case LCS_NONE:
3135  Assert(false);
3136  break;
3137  case LCS_FORKEYSHARE:
3138  return "FOR KEY SHARE";
3139  case LCS_FORSHARE:
3140  return "FOR SHARE";
3141  case LCS_FORNOKEYUPDATE:
3142  return "FOR NO KEY UPDATE";
3143  case LCS_FORUPDATE:
3144  return "FOR UPDATE";
3145  }
3146  return "FOR some"; /* shouldn't happen */
3147 }
@ 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 1906 of file analyze.c.

1907 {
1909  Oid sortop;
1910  Oid eqop;
1911  bool hashable;
1912 
1913  /* determine the eqop and optional sortop */
1914  get_sort_group_operators(rescoltype,
1915  false, true, false,
1916  &sortop, &eqop, NULL,
1917  &hashable);
1918 
1919  /*
1920  * The type cache doesn't believe that record is hashable (see
1921  * cache_record_field_properties()), but if the caller really needs hash
1922  * support, we can assume it does. Worst case, if any components of the
1923  * record don't support hashing, we will fail at execution.
1924  */
1925  if (require_hash && (rescoltype == RECORDOID || rescoltype == RECORDARRAYOID))
1926  hashable = true;
1927 
1928  /* we don't have a tlist yet, so can't assign sortgrouprefs */
1929  grpcl->tleSortGroupRef = 0;
1930  grpcl->eqop = eqop;
1931  grpcl->sortop = sortop;
1932  grpcl->nulls_first = false; /* OK with or without sortop */
1933  grpcl->hashable = hashable;
1934 
1935  return grpcl;
1936 }
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:192
unsigned int Oid
Definition: postgres_ext.h:31
Index tleSortGroupRef
Definition: parsenodes.h:1392

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

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

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

149 {
150  ParseState *pstate = make_parsestate(NULL);
151  Query *query;
152  JumbleState *jstate = NULL;
153 
154  Assert(sourceText != NULL); /* required as of 8.4 */
155 
156  pstate->p_sourcetext = sourceText;
157 
158  setup_parse_variable_parameters(pstate, paramTypes, numParams);
159 
160  pstate->p_queryEnv = queryEnv;
161 
162  query = transformTopLevelStmt(pstate, parseTree);
163 
164  /* make sure all is well with parameter types */
165  check_variable_parameters(pstate, query);
166 
167  if (IsQueryIdEnabled())
168  jstate = JumbleQuery(query, sourceText);
169 
171  (*post_parse_analyze_hook) (pstate, query, jstate);
172 
173  free_parsestate(pstate);
174 
175  pgstat_report_query_id(query->queryId, false);
176 
177  return query;
178 }
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 187 of file analyze.c.

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

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

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

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

◆ transformInsertRow()

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

Definition at line 970 of file analyze.c.

973 {
974  List *result;
975  ListCell *lc;
976  ListCell *icols;
977  ListCell *attnos;
978 
979  /*
980  * Check length of expr list. It must not have more expressions than
981  * there are target columns. We allow fewer, but only if no explicit
982  * columns list was given (the remaining columns are implicitly
983  * defaulted). Note we must check this *after* transformation because
984  * that could expand '*' into multiple items.
985  */
986  if (list_length(exprlist) > list_length(icolumns))
987  ereport(ERROR,
988  (errcode(ERRCODE_SYNTAX_ERROR),
989  errmsg("INSERT has more expressions than target columns"),
990  parser_errposition(pstate,
991  exprLocation(list_nth(exprlist,
992  list_length(icolumns))))));
993  if (stmtcols != NIL &&
994  list_length(exprlist) < list_length(icolumns))
995  {
996  /*
997  * We can get here for cases like INSERT ... SELECT (a,b,c) FROM ...
998  * where the user accidentally created a RowExpr instead of separate
999  * columns. Add a suitable hint if that seems to be the problem,
1000  * because the main error message is quite misleading for this case.
1001  * (If there's no stmtcols, you'll get something about data type
1002  * mismatch, which is less misleading so we don't worry about giving a
1003  * hint in that case.)
1004  */
1005  ereport(ERROR,
1006  (errcode(ERRCODE_SYNTAX_ERROR),
1007  errmsg("INSERT has more target columns than expressions"),
1008  ((list_length(exprlist) == 1 &&
1009  count_rowexpr_columns(pstate, linitial(exprlist)) ==
1010  list_length(icolumns)) ?
1011  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),
1012  parser_errposition(pstate,
1013  exprLocation(list_nth(icolumns,
1014  list_length(exprlist))))));
1015  }
1016 
1017  /*
1018  * Prepare columns for assignment to target table.
1019  */
1020  result = NIL;
1021  forthree(lc, exprlist, icols, icolumns, attnos, attrnos)
1022  {
1023  Expr *expr = (Expr *) lfirst(lc);
1024  ResTarget *col = lfirst_node(ResTarget, icols);
1025  int attno = lfirst_int(attnos);
1026 
1027  expr = transformAssignedExpr(pstate, expr,
1029  col->name,
1030  attno,
1031  col->indirection,
1032  col->location);
1033 
1034  if (strip_indirection)
1035  {
1036  while (expr)
1037  {
1038  if (IsA(expr, FieldStore))
1039  {
1040  FieldStore *fstore = (FieldStore *) expr;
1041 
1042  expr = (Expr *) linitial(fstore->newvals);
1043  }
1044  else if (IsA(expr, SubscriptingRef))
1045  {
1046  SubscriptingRef *sbsref = (SubscriptingRef *) expr;
1047 
1048  if (sbsref->refassgnexpr == NULL)
1049  break;
1050 
1051  expr = sbsref->refassgnexpr;
1052  }
1053  else
1054  break;
1055  }
1056  }
1057 
1058  result = lappend(result, expr);
1059  }
1060 
1061  return result;
1062 }
int errhint(const char *fmt,...)
Definition: elog.c:1316
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1243
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
@ 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:453
static int count_rowexpr_columns(ParseState *pstate, Node *expr)
Definition: analyze.c:1246
#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:512
#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:1080
int location
Definition: parsenodes.h:518
List * indirection
Definition: parsenodes.h:516
char * name
Definition: parsenodes.h:515
Expr * refassgnexpr
Definition: primnodes.h:627

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

◆ transformStmt()

Query* transformStmt ( ParseState pstate,
Node parseTree 
)

Definition at line 313 of file analyze.c.

314 {
315  Query *result;
316 
317  /*
318  * We apply RAW_EXPRESSION_COVERAGE_TEST testing to basic DML statements;
319  * we can't just run it on everything because raw_expression_tree_walker()
320  * doesn't claim to handle utility statements.
321  */
322 #ifdef RAW_EXPRESSION_COVERAGE_TEST
323  switch (nodeTag(parseTree))
324  {
325  case T_SelectStmt:
326  case T_InsertStmt:
327  case T_UpdateStmt:
328  case T_DeleteStmt:
329  case T_MergeStmt:
330  (void) test_raw_expression_coverage(parseTree, NULL);
331  break;
332  default:
333  break;
334  }
335 #endif /* RAW_EXPRESSION_COVERAGE_TEST */
336 
337  switch (nodeTag(parseTree))
338  {
339  /*
340  * Optimizable statements
341  */
342  case T_InsertStmt:
343  result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
344  break;
345 
346  case T_DeleteStmt:
347  result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
348  break;
349 
350  case T_UpdateStmt:
351  result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
352  break;
353 
354  case T_MergeStmt:
355  result = transformMergeStmt(pstate, (MergeStmt *) parseTree);
356  break;
357 
358  case T_SelectStmt:
359  {
360  SelectStmt *n = (SelectStmt *) parseTree;
361 
362  if (n->valuesLists)
363  result = transformValuesClause(pstate, n);
364  else if (n->op == SETOP_NONE)
365  result = transformSelectStmt(pstate, n);
366  else
367  result = transformSetOperationStmt(pstate, n);
368  }
369  break;
370 
371  case T_ReturnStmt:
372  result = transformReturnStmt(pstate, (ReturnStmt *) parseTree);
373  break;
374 
375  case T_PLAssignStmt:
376  result = transformPLAssignStmt(pstate,
377  (PLAssignStmt *) parseTree);
378  break;
379 
380  /*
381  * Special cases
382  */
383  case T_DeclareCursorStmt:
384  result = transformDeclareCursorStmt(pstate,
385  (DeclareCursorStmt *) parseTree);
386  break;
387 
388  case T_ExplainStmt:
389  result = transformExplainStmt(pstate,
390  (ExplainStmt *) parseTree);
391  break;
392 
393  case T_CreateTableAsStmt:
394  result = transformCreateTableAsStmt(pstate,
395  (CreateTableAsStmt *) parseTree);
396  break;
397 
398  case T_CallStmt:
399  result = transformCallStmt(pstate,
400  (CallStmt *) parseTree);
401  break;
402 
403  default:
404 
405  /*
406  * other statements don't require any transformation; just return
407  * the original parsetree with a Query node plastered on top.
408  */
409  result = makeNode(Query);
410  result->commandType = CMD_UTILITY;
411  result->utilityStmt = (Node *) parseTree;
412  break;
413  }
414 
415  /* Mark as original query until we learn differently */
416  result->querySource = QSRC_ORIGINAL;
417  result->canSetTag = true;
418 
419  return result;
420 }
@ CMD_UTILITY
Definition: nodes.h:281
Query * transformMergeStmt(ParseState *pstate, MergeStmt *stmt)
Definition: parse_merge.c:96
@ SETOP_NONE
Definition: parsenodes.h:1821
@ QSRC_ORIGINAL
Definition: parsenodes.h:43
static Query * transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
Definition: analyze.c:472
static Query * transformReturnStmt(ParseState *pstate, ReturnStmt *stmt)
Definition: analyze.c:2338
static Query * transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt)
Definition: analyze.c:2564
static Query * transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
Definition: analyze.c:2930
static Query * transformCallStmt(ParseState *pstate, CallStmt *stmt)
Definition: analyze.c:3005
static Query * transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1650
static Query * transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
Definition: analyze.c:2369
static Query * transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1288
static Query * transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
Definition: analyze.c:2906
static Query * transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
Definition: analyze.c:2813
static Query * transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
Definition: analyze.c:543
static Query * transformValuesClause(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1431
Definition: nodes.h:129
CmdType commandType
Definition: parsenodes.h:128
Node * utilityStmt
Definition: parsenodes.h:143
List * valuesLists
Definition: parsenodes.h:1853
SetOperation op
Definition: parsenodes.h:1869

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(), transformOptionalSelectInto(), and transformRuleStmt().

◆ transformTopLevelStmt()

Query* transformTopLevelStmt ( ParseState pstate,
RawStmt parseTree 
)

Definition at line 250 of file analyze.c.

251 {
252  Query *result;
253 
254  /* We're at top level, so allow SELECT INTO */
255  result = transformOptionalSelectInto(pstate, parseTree->stmt);
256 
257  result->stmt_location = parseTree->stmt_location;
258  result->stmt_len = parseTree->stmt_len;
259 
260  return result;
261 }
static Query * transformOptionalSelectInto(ParseState *pstate, Node *parseTree)
Definition: analyze.c:274
int stmt_location
Definition: parsenodes.h:236
int stmt_len
Definition: parsenodes.h:1736
int stmt_location
Definition: parsenodes.h:1735

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

2435 {
2436  List *tlist = NIL;
2437  RTEPermissionInfo *target_perminfo;
2438  ListCell *orig_tl;
2439  ListCell *tl;
2440 
2441  tlist = transformTargetList(pstate, origTlist,
2443 
2444  /* Prepare to assign non-conflicting resnos to resjunk attributes */
2447 
2448  /* Prepare non-junk columns for assignment to target table */
2449  target_perminfo = pstate->p_target_nsitem->p_perminfo;
2450  orig_tl = list_head(origTlist);
2451 
2452  foreach(tl, tlist)
2453  {
2454  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2455  ResTarget *origTarget;
2456  int attrno;
2457 
2458  if (tle->resjunk)
2459  {
2460  /*
2461  * Resjunk nodes need no additional processing, but be sure they
2462  * have resnos that do not match any target columns; else rewriter
2463  * or planner might get confused. They don't need a resname
2464  * either.
2465  */
2466  tle->resno = (AttrNumber) pstate->p_next_resno++;
2467  tle->resname = NULL;
2468  continue;
2469  }
2470  if (orig_tl == NULL)
2471  elog(ERROR, "UPDATE target count mismatch --- internal error");
2472  origTarget = lfirst_node(ResTarget, orig_tl);
2473 
2474  attrno = attnameAttNum(pstate->p_target_relation,
2475  origTarget->name, true);
2476  if (attrno == InvalidAttrNumber)
2477  ereport(ERROR,
2478  (errcode(ERRCODE_UNDEFINED_COLUMN),
2479  errmsg("column \"%s\" of relation \"%s\" does not exist",
2480  origTarget->name,
2482  parser_errposition(pstate, origTarget->location)));
2483 
2484  updateTargetListEntry(pstate, tle, origTarget->name,
2485  attrno,
2486  origTarget->indirection,
2487  origTarget->location);
2488 
2489  /* Mark the target column as requiring update permissions */
2490  target_perminfo->updatedCols = bms_add_member(target_perminfo->updatedCols,
2492 
2493  orig_tl = lnext(origTlist, orig_tl);
2494  }
2495  if (orig_tl != NULL)
2496  elog(ERROR, "UPDATE target count mismatch --- internal error");
2497 
2498  return tlist;
2499 }
int16 AttrNumber
Definition: attnum.h:21
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:739
@ EXPR_KIND_UPDATE_SOURCE
Definition: parse_node.h:56
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
List * transformTargetList(ParseState *pstate, List *targetlist, ParseExprKind exprKind)
Definition: parse_target.c:122
void updateTargetListEntry(ParseState *pstate, TargetEntry *tle, char *colname, int attrno, List *indirection, int location)
Definition: parse_target.c:620
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:535
RTEPermissionInfo * p_perminfo
Definition: parse_node.h:288
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:207
int p_next_resno
Definition: parse_node.h:211
Relation p_target_relation
Definition: parse_node.h:206
Bitmapset * updatedCols
Definition: parsenodes.h:1249
AttrNumber resno
Definition: primnodes.h:1724
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

References attnameAttNum(), bms_add_member(), elog(), ereport, errcode(), errmsg(), ERROR, EXPR_KIND_UPDATE_SOURCE, FirstLowInvalidHeapAttributeNumber, ResTarget::indirection, InvalidAttrNumber, lfirst, lfirst_node, list_head(), lnext(), ResTarget::location, ResTarget::name, NIL, 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