PostgreSQL Source Code  git master
parse_node.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/table.h"
#include "catalog/pg_type.h"
#include "mb/pg_wchar.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/subscripting.h"
#include "parser/parse_coerce.h"
#include "parser/parse_expr.h"
#include "parser/parse_relation.h"
#include "parser/parsetree.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/varbit.h"
Include dependency graph for parse_node.c:

Go to the source code of this file.

Functions

static void pcb_error_callback (void *arg)
 
ParseStatemake_parsestate (ParseState *parentParseState)
 
void free_parsestate (ParseState *pstate)
 
int parser_errposition (ParseState *pstate, int location)
 
void setup_parser_errposition_callback (ParseCallbackState *pcbstate, ParseState *pstate, int location)
 
void cancel_parser_errposition_callback (ParseCallbackState *pcbstate)
 
void transformContainerType (Oid *containerType, int32 *containerTypmod)
 
SubscriptingReftransformContainerSubscripts (ParseState *pstate, Node *containerBase, Oid containerType, int32 containerTypMod, List *indirection, bool isAssignment)
 
Constmake_const (ParseState *pstate, A_Const *aconst)
 

Function Documentation

◆ cancel_parser_errposition_callback()

void cancel_parser_errposition_callback ( ParseCallbackState pcbstate)

◆ free_parsestate()

void free_parsestate ( ParseState pstate)

Definition at line 76 of file parse_node.c.

77 {
78  /*
79  * Check that we did not produce too many resnos; at the very least we
80  * cannot allow more than 2^16, since that would exceed the range of a
81  * AttrNumber. It seems safest to use MaxTupleAttributeNumber.
82  */
83  if (pstate->p_next_resno - 1 > MaxTupleAttributeNumber)
84  ereport(ERROR,
85  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
86  errmsg("target lists can have at most %d entries",
88 
89  if (pstate->p_target_relation != NULL)
91 
92  pfree(pstate);
93 }
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define ereport(elevel,...)
Definition: elog.h:143
#define MaxTupleAttributeNumber
Definition: htup_details.h:33
#define NoLock
Definition: lockdefs.h:34
void pfree(void *pointer)
Definition: mcxt.c:1175
int p_next_resno
Definition: parse_node.h:198
Relation p_target_relation
Definition: parse_node.h:193
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167

References ereport, errcode(), errmsg(), ERROR, MaxTupleAttributeNumber, NoLock, ParseState::p_next_resno, ParseState::p_target_relation, pfree(), and table_close().

Referenced by AlterPolicy(), CreatePolicy(), CreateTriggerFiringOn(), inline_function(), interpret_AS_clause(), parse_analyze_fixedparams(), parse_analyze_varparams(), parse_analyze_withcb(), parse_sub_analyze(), standard_ProcessUtility(), transformIndexStmt(), transformInsertStmt(), transformJsonArrayQueryConstructor(), TransformPubWhereClauses(), transformRuleStmt(), and transformStatsStmt().

◆ make_const()

Const* make_const ( ParseState pstate,
A_Const aconst 
)

Definition at line 351 of file parse_node.c.

352 {
353  Const *con;
354  Datum val;
355  Oid typeid;
356  int typelen;
357  bool typebyval;
358  ParseCallbackState pcbstate;
359 
360  if (aconst->isnull)
361  {
362  /* return a null const */
363  con = makeConst(UNKNOWNOID,
364  -1,
365  InvalidOid,
366  -2,
367  (Datum) 0,
368  true,
369  false);
370  con->location = aconst->location;
371  return con;
372  }
373 
374  switch (nodeTag(&aconst->val))
375  {
376  case T_Integer:
377  val = Int32GetDatum(intVal(&aconst->val));
378 
379  typeid = INT4OID;
380  typelen = sizeof(int32);
381  typebyval = true;
382  break;
383 
384  case T_Float:
385  {
386  /* could be an oversize integer as well as a float ... */
387 
388  int64 val64;
389  char *endptr;
390 
391  errno = 0;
392  val64 = strtoi64(aconst->val.fval.fval, &endptr, 10);
393  if (errno == 0 && *endptr == '\0')
394  {
395  /*
396  * It might actually fit in int32. Probably only INT_MIN
397  * can occur, but we'll code the test generally just to be
398  * sure.
399  */
400  int32 val32 = (int32) val64;
401 
402  if (val64 == (int64) val32)
403  {
404  val = Int32GetDatum(val32);
405 
406  typeid = INT4OID;
407  typelen = sizeof(int32);
408  typebyval = true;
409  }
410  else
411  {
412  val = Int64GetDatum(val64);
413 
414  typeid = INT8OID;
415  typelen = sizeof(int64);
416  typebyval = FLOAT8PASSBYVAL; /* int8 and float8 alike */
417  }
418  }
419  else
420  {
421  /* arrange to report location if numeric_in() fails */
422  setup_parser_errposition_callback(&pcbstate, pstate, aconst->location);
424  CStringGetDatum(aconst->val.fval.fval),
426  Int32GetDatum(-1));
428 
429  typeid = NUMERICOID;
430  typelen = -1; /* variable len */
431  typebyval = false;
432  }
433  break;
434  }
435 
436  case T_Boolean:
437  val = BoolGetDatum(boolVal(&aconst->val));
438 
439  typeid = BOOLOID;
440  typelen = 1;
441  typebyval = true;
442  break;
443 
444  case T_String:
445 
446  /*
447  * We assume here that UNKNOWN's internal representation is the
448  * same as CSTRING
449  */
450  val = CStringGetDatum(strVal(&aconst->val));
451 
452  typeid = UNKNOWNOID; /* will be coerced later */
453  typelen = -2; /* cstring-style varwidth type */
454  typebyval = false;
455  break;
456 
457  case T_BitString:
458  /* arrange to report location if bit_in() fails */
459  setup_parser_errposition_callback(&pcbstate, pstate, aconst->location);
461  CStringGetDatum(aconst->val.bsval.bsval),
463  Int32GetDatum(-1));
465  typeid = BITOID;
466  typelen = -1;
467  typebyval = false;
468  break;
469 
470  default:
471  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(&aconst->val));
472  return NULL; /* keep compiler quiet */
473  }
474 
475  con = makeConst(typeid,
476  -1, /* typmod -1 is OK for all cases */
477  InvalidOid, /* all cases are uncollatable types */
478  typelen,
479  val,
480  false,
481  typebyval);
482  con->location = aconst->location;
483 
484  return con;
485 }
Datum numeric_in(PG_FUNCTION_ARGS)
Definition: numeric.c:617
signed int int32
Definition: c.h:429
#define strtoi64(str, endptr, base)
Definition: c.h:1321
#define FLOAT8PASSBYVAL
Definition: c.h:570
#define elog(elevel,...)
Definition: elog.h:218
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1683
#define DirectFunctionCall3(func, arg1, arg2, arg3)
Definition: fmgr.h:635
long val
Definition: informix.c:664
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:300
#define nodeTag(nodeptr)
Definition: nodes.h:578
@ T_BitString
Definition: nodes.h:312
@ T_Float
Definition: nodes.h:309
@ T_String
Definition: nodes.h:311
@ T_Integer
Definition: nodes.h:308
@ T_Boolean
Definition: nodes.h:310
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
#define CStringGetDatum(X)
Definition: postgres.h:622
uintptr_t Datum
Definition: postgres.h:411
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define BoolGetDatum(X)
Definition: postgres.h:446
#define Int32GetDatum(X)
Definition: postgres.h:523
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
bool isnull
Definition: parsenodes.h:317
int location
Definition: parsenodes.h:318
union A_Const::ValUnion val
char * bsval
Definition: value.h:66
int location
Definition: primnodes.h:235
char * fval
Definition: value.h:48
BitString bsval
Definition: parsenodes.h:315
#define boolVal(v)
Definition: value.h:71
#define intVal(v)
Definition: value.h:69
#define strVal(v)
Definition: value.h:72
Datum bit_in(PG_FUNCTION_ARGS)
Definition: varbit.c:147

References bit_in(), BoolGetDatum, boolVal, A_Const::ValUnion::bsval, BitString::bsval, cancel_parser_errposition_callback(), CStringGetDatum, DirectFunctionCall3, elog, ERROR, FLOAT8PASSBYVAL, A_Const::ValUnion::fval, Float::fval, Int32GetDatum, Int64GetDatum(), intVal, InvalidOid, A_Const::isnull, A_Const::location, Const::location, makeConst(), nodeTag, numeric_in(), ObjectIdGetDatum, setup_parser_errposition_callback(), strtoi64, strVal, T_BitString, T_Boolean, T_Float, T_Integer, T_String, A_Const::val, and val.

Referenced by transformExprRecurse().

◆ make_parsestate()

ParseState* make_parsestate ( ParseState parentParseState)

Definition at line 43 of file parse_node.c.

44 {
45  ParseState *pstate;
46 
47  pstate = palloc0(sizeof(ParseState));
48 
49  pstate->parentParseState = parentParseState;
50 
51  /* Fill in fields that don't start at null/false/zero */
52  pstate->p_next_resno = 1;
53  pstate->p_resolve_unknowns = true;
54 
55  if (parentParseState)
56  {
57  pstate->p_sourcetext = parentParseState->p_sourcetext;
58  /* all hooks are copied from parent */
59  pstate->p_pre_columnref_hook = parentParseState->p_pre_columnref_hook;
60  pstate->p_post_columnref_hook = parentParseState->p_post_columnref_hook;
61  pstate->p_paramref_hook = parentParseState->p_paramref_hook;
62  pstate->p_coerce_param_hook = parentParseState->p_coerce_param_hook;
63  pstate->p_ref_hook_state = parentParseState->p_ref_hook_state;
64  /* query environment stays in context for the whole parse analysis */
65  pstate->p_queryEnv = parentParseState->p_queryEnv;
66  }
67 
68  return pstate;
69 }
void * palloc0(Size size)
Definition: mcxt.c:1099
ParseState * parentParseState
Definition: parse_node.h:181
void * p_ref_hook_state
Definition: parse_node.h:225
ParseParamRefHook p_paramref_hook
Definition: parse_node.h:223
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:221
QueryEnvironment * p_queryEnv
Definition: parse_node.h:206
const char * p_sourcetext
Definition: parse_node.h:182
bool p_resolve_unknowns
Definition: parse_node.h:203
CoerceParamHook p_coerce_param_hook
Definition: parse_node.h:224
PostParseColumnRefHook p_post_columnref_hook
Definition: parse_node.h:222

References ParseState::p_coerce_param_hook, ParseState::p_next_resno, ParseState::p_paramref_hook, ParseState::p_post_columnref_hook, ParseState::p_pre_columnref_hook, ParseState::p_queryEnv, ParseState::p_ref_hook_state, ParseState::p_resolve_unknowns, ParseState::p_sourcetext, palloc0(), and ParseState::parentParseState.

Referenced by AddRelationNewConstraints(), AlterDomainDefault(), AlterPolicy(), ATExecAttachPartition(), ATPrepAlterColumnType(), convert_ANY_sublink_to_join(), copy_table(), CreatePolicy(), CreateTriggerFiringOn(), DefineDomain(), DefineRelation(), domainAddConstraint(), ExplainExecuteQuery(), inline_function(), interpret_AS_clause(), parse_analyze_fixedparams(), parse_analyze_varparams(), parse_analyze_withcb(), parse_sub_analyze(), rewriteTargetView(), standard_ProcessUtility(), test_rls_hooks_permissive(), test_rls_hooks_restrictive(), transformAlterTableStmt(), transformCreateStmt(), transformIndexStmt(), transformInsertStmt(), transformJsonArrayQueryConstructor(), transformPartitionSpec(), TransformPubWhereClauses(), transformRuleStmt(), transformStatsStmt(), and UpdateRangeTableOfViewParse().

◆ parser_errposition()

int parser_errposition ( ParseState pstate,
int  location 
)

Definition at line 110 of file parse_node.c.

111 {
112  int pos;
113 
114  /* No-op if location was not provided */
115  if (location < 0)
116  return 0;
117  /* Can't do anything if source text is not available */
118  if (pstate == NULL || pstate->p_sourcetext == NULL)
119  return 0;
120  /* Convert offset to character number */
121  pos = pg_mbstrlen_with_len(pstate->p_sourcetext, location) + 1;
122  /* And pass it to the ereport mechanism */
123  return errposition(pos);
124 }
int errposition(int cursorpos)
Definition: elog.c:1280
int pg_mbstrlen_with_len(const char *mbstr, int limit)
Definition: mbutils.c:1000

References errposition(), ParseState::p_sourcetext, and pg_mbstrlen_with_len().

Referenced by addRangeTableEntryForCTE(), addRangeTableEntryForFunction(), AlterDatabase(), analyzeCTE(), analyzeCTETargetList(), appendJsonTableColumns(), array_subscript_transform(), assign_collations_walker(), assign_hypothetical_collations(), check_agg_arguments(), check_agg_arguments_walker(), check_agglevels_and_constraints(), check_lateral_ref_ok(), check_nested_generated_walker(), check_new_partition_bound(), check_parameter_resolution_walker(), check_simple_rowfilter_expr_walker(), check_srf_call_placement(), check_ungrouped_columns_walker(), checkExprIsVarFree(), checkInsertTargets(), checkJsonOutputFormat(), checkTargetlistEntrySQL92(), checkWellFormedRecursion(), checkWellFormedRecursionWalker(), cluster(), coerce_to_boolean(), coerce_to_common_type(), coerce_to_specific_type_typmod(), coerceDefaultJsonExpr(), colNameToVar(), compatible_oper(), compute_common_attribute(), compute_function_attributes(), ComputePartitionAttrs(), createdb(), CreateTriggerFiringOn(), DefineCollation(), DefineType(), DropDatabase(), errorConflictingDefElem(), errorMissingColumn(), errorMissingRTE(), EvaluateParams(), ExecReindex(), ExecVacuum(), ExpandAllTables(), ExpandColumnRefStar(), ExplainQuery(), finalize_grouping_exprs_walker(), findTargetlistEntrySQL92(), fixed_paramref_hook(), GetColumnDefCollation(), hstore_subscript_transform(), init_params(), jsonb_subscript_transform(), LookupOperName(), LookupTypeNameExtended(), LookupTypeNameOid(), make_distinct_op(), make_op(), make_row_comparison_op(), make_row_distinct_op(), make_scalar_array_op(), merge_collation_state(), op_error(), parseCheckAggregates(), ParseFuncOrColumn(), parser_coercion_errposition(), parseTypeString(), pcb_error_callback(), plpgsql_post_column_ref(), ProcessCopyOptions(), resolve_column_ref(), resolve_unique_index_expr(), scanNameSpaceForRefname(), scanNameSpaceForRelid(), scanNSItemForColumn(), scanRTEForColumn(), select_common_collation(), select_common_type(), TopologicalSort(), transformAExprNullIf(), transformAggregateCall(), transformArrayExpr(), transformAssignedExpr(), transformAssignmentIndirection(), transformAssignmentSubscripts(), transformCaseExpr(), transformCoalesceExpr(), transformCollateClause(), transformColumnDefinition(), transformColumnRef(), transformColumnType(), transformConstraintAttrs(), transformContainerSubscripts(), transformDistinctClause(), transformDistinctOnClause(), transformExprRecurse(), transformFrameOffset(), transformFromClauseItem(), transformGroupingFunc(), transformGroupingSet(), transformIndexConstraint(), transformIndirection(), transformInsertRow(), transformJsonAggConstructor(), transformJsonArrayQueryConstructor(), transformJsonConstructorRet(), transformJsonExprCommon(), transformJsonFuncExpr(), transformJsonParseArg(), transformJsonParseExpr(), transformJsonTable(), transformJsonTableChildPlan(), transformJsonTableColumns(), transformJsonValueExprExt(), transformLockingClause(), transformMultiAssignRef(), transformOnConflictArbiter(), transformParamRef(), transformPartitionBound(), transformPartitionBoundValue(), transformPLAssignStmt(), transformRangeFunction(), transformRangeTableFunc(), transformRangeTableSample(), transformReturningList(), transformSelectStmt(), transformSetOperationStmt(), transformSetOperationTree(), transformSubLink(), transformTableConstraint(), transformUpdateTargetList(), transformValuesClause(), transformWindowDefinitions(), transformWindowFuncCall(), transformWithClause(), transformXmlExpr(), transformXmlSerialize(), typenameType(), typenameTypeMod(), unknown_attribute(), validateInfiniteBounds(), validateJsonTableChildPlan(), variable_coerce_param_hook(), and variable_paramref_hook().

◆ pcb_error_callback()

static void pcb_error_callback ( void *  arg)
static

Definition at line 174 of file parse_node.c.

175 {
176  ParseCallbackState *pcbstate = (ParseCallbackState *) arg;
177 
178  if (geterrcode() != ERRCODE_QUERY_CANCELED)
179  (void) parser_errposition(pcbstate->pstate, pcbstate->location);
180 }
int geterrcode(void)
Definition: elog.c:1395
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
void * arg
ParseState * pstate
Definition: parse_node.h:315

References arg, geterrcode(), ParseCallbackState::location, parser_errposition(), and ParseCallbackState::pstate.

Referenced by setup_parser_errposition_callback().

◆ setup_parser_errposition_callback()

void setup_parser_errposition_callback ( ParseCallbackState pcbstate,
ParseState pstate,
int  location 
)

◆ transformContainerSubscripts()

SubscriptingRef* transformContainerSubscripts ( ParseState pstate,
Node containerBase,
Oid  containerType,
int32  containerTypMod,
List indirection,
bool  isAssignment 
)

Definition at line 247 of file parse_node.c.

253 {
254  SubscriptingRef *sbsref;
255  const SubscriptRoutines *sbsroutines;
256  Oid elementType;
257  bool isSlice = false;
258  ListCell *idx;
259 
260  /*
261  * Determine the actual container type, smashing any domain. In the
262  * assignment case the caller already did this, since it also needs to
263  * know the actual container type.
264  */
265  if (!isAssignment)
266  transformContainerType(&containerType, &containerTypMod);
267 
268  /*
269  * Verify that the container type is subscriptable, and get its support
270  * functions and typelem.
271  */
272  sbsroutines = getSubscriptingRoutines(containerType, &elementType);
273  if (!sbsroutines)
274  ereport(ERROR,
275  (errcode(ERRCODE_DATATYPE_MISMATCH),
276  errmsg("cannot subscript type %s because it does not support subscripting",
277  format_type_be(containerType)),
278  parser_errposition(pstate, exprLocation(containerBase))));
279 
280  /*
281  * Detect whether any of the indirection items are slice specifiers.
282  *
283  * A list containing only simple subscripts refers to a single container
284  * element. If any of the items are slice specifiers (lower:upper), then
285  * the subscript expression means a container slice operation.
286  */
287  foreach(idx, indirection)
288  {
290 
291  if (ai->is_slice)
292  {
293  isSlice = true;
294  break;
295  }
296  }
297 
298  /*
299  * Ready to build the SubscriptingRef node.
300  */
301  sbsref = makeNode(SubscriptingRef);
302 
303  sbsref->refcontainertype = containerType;
304  sbsref->refelemtype = elementType;
305  /* refrestype is to be set by container-specific logic */
306  sbsref->reftypmod = containerTypMod;
307  /* refcollid will be set by parse_collate.c */
308  /* refupperindexpr, reflowerindexpr are to be set by container logic */
309  sbsref->refexpr = (Expr *) containerBase;
310  sbsref->refassgnexpr = NULL; /* caller will fill if it's an assignment */
311 
312  /*
313  * Call the container-type-specific logic to transform the subscripts and
314  * determine the subscripting result type.
315  */
316  sbsroutines->transform(sbsref, indirection, pstate,
317  isSlice, isAssignment);
318 
319  /*
320  * Verify we got a valid type (this defends, for example, against someone
321  * using array_subscript_handler as typsubscript without setting typelem).
322  */
323  if (!OidIsValid(sbsref->refrestype))
324  ereport(ERROR,
325  (errcode(ERRCODE_DATATYPE_MISMATCH),
326  errmsg("cannot subscript type %s because it does not support subscripting",
327  format_type_be(containerType))));
328 
329  return sbsref;
330 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
#define OidIsValid(objectId)
Definition: c.h:710
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
const struct SubscriptRoutines * getSubscriptingRoutines(Oid typid, Oid *typelemp)
Definition: lsyscache.c:3087
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1343
#define makeNode(_type_)
Definition: nodes.h:621
void transformContainerType(Oid *containerType, int32 *containerTypmod)
Definition: parse_node.c:193
#define lfirst_node(type, lc)
Definition: pg_list.h:172
bool is_slice
Definition: parsenodes.h:413
SubscriptTransform transform
Definition: subscripting.h:160
Expr * refassgnexpr
Definition: primnodes.h:460
Expr * refexpr
Definition: primnodes.h:458
Oid refcontainertype
Definition: primnodes.h:448

References ereport, errcode(), errmsg(), ERROR, exprLocation(), format_type_be(), getSubscriptingRoutines(), idx(), A_Indices::is_slice, lfirst_node, makeNode, OidIsValid, parser_errposition(), SubscriptingRef::refassgnexpr, SubscriptingRef::refcontainertype, SubscriptingRef::refelemtype, SubscriptingRef::refexpr, SubscriptingRef::refrestype, SubscriptingRef::reftypmod, SubscriptRoutines::transform, and transformContainerType().

Referenced by transformAssignmentSubscripts(), and transformIndirection().

◆ transformContainerType()

void transformContainerType ( Oid containerType,
int32 containerTypmod 
)

Definition at line 193 of file parse_node.c.

194 {
195  /*
196  * If the input is a domain, smash to base type, and extract the actual
197  * typmod to be applied to the base type. Subscripting a domain is an
198  * operation that necessarily works on the base container type, not the
199  * domain itself. (Note that we provide no method whereby the creator of a
200  * domain over a container type could hide its ability to be subscripted.)
201  */
202  *containerType = getBaseTypeAndTypmod(*containerType, containerTypmod);
203 
204  /*
205  * We treat int2vector and oidvector as though they were domains over
206  * int2[] and oid[]. This is needed because array slicing could create an
207  * array that doesn't satisfy the dimensionality constraints of the
208  * xxxvector type; so we want the result of a slice operation to be
209  * considered to be of the more general type.
210  */
211  if (*containerType == INT2VECTOROID)
212  *containerType = INT2ARRAYOID;
213  else if (*containerType == OIDVECTOROID)
214  *containerType = OIDARRAYOID;
215 }
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2495

References getBaseTypeAndTypmod().

Referenced by transformAssignmentSubscripts(), and transformContainerSubscripts().