1 /*-------------------------------------------------------------------------
4 * various routines that make nodes for querytrees
6 * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/parser/parse_node.c
13 *-------------------------------------------------------------------------
17 #include "access/heapam.h"
18 #include "access/htup_details.h"
19 #include "catalog/pg_type.h"
20 #include "mb/pg_wchar.h"
21 #include "nodes/makefuncs.h"
22 #include "nodes/nodeFuncs.h"
23 #include "parser/parsetree.h"
24 #include "parser/parse_coerce.h"
25 #include "parser/parse_expr.h"
26 #include "parser/parse_relation.h"
27 #include "utils/builtins.h"
28 #include "utils/int8.h"
29 #include "utils/lsyscache.h"
30 #include "utils/syscache.h"
31 #include "utils/varbit.h"
34 static void pcb_error_callback(void *arg);
39 * Allocate and initialize a new ParseState.
41 * Caller should eventually release the ParseState via free_parsestate().
44 make_parsestate(ParseState *parentParseState)
48 pstate = palloc0(sizeof(ParseState));
50 pstate->parentParseState = parentParseState;
52 /* Fill in fields that don't start at null/false/zero */
53 pstate->p_next_resno = 1;
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;
71 * Release a ParseState and any subsidiary resources.
74 free_parsestate(ParseState *pstate)
77 * Check that we did not produce too many resnos; at the very least we
78 * cannot allow more than 2^16, since that would exceed the range of a
79 * AttrNumber. It seems safest to use MaxTupleAttributeNumber.
81 if (pstate->p_next_resno - 1 > MaxTupleAttributeNumber)
83 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
84 errmsg("target lists can have at most %d entries",
85 MaxTupleAttributeNumber)));
87 if (pstate->p_target_relation != NULL)
88 heap_close(pstate->p_target_relation, NoLock);
96 * Report a parse-analysis-time cursor position, if possible.
98 * This is expected to be used within an ereport() call. The return value
99 * is a dummy (always 0, in fact).
101 * The locations stored in raw parsetrees are byte offsets into the source
102 * string. We have to convert them to 1-based character indexes for reporting
103 * to clients. (We do things this way to avoid unnecessary overhead in the
104 * normal non-error case: computing character indexes would be much more
105 * expensive than storing token offsets.)
108 parser_errposition(ParseState *pstate, int location)
112 /* No-op if location was not provided */
115 /* Can't do anything if source text is not available */
116 if (pstate == NULL || pstate->p_sourcetext == NULL)
118 /* Convert offset to character number */
119 pos = pg_mbstrlen_with_len(pstate->p_sourcetext, location) + 1;
120 /* And pass it to the ereport mechanism */
121 return errposition(pos);
126 * setup_parser_errposition_callback
127 * Arrange for non-parser errors to report an error position
129 * Sometimes the parser calls functions that aren't part of the parser
130 * subsystem and can't reasonably be passed a ParseState; yet we would
131 * like any errors thrown in those functions to be tagged with a parse
132 * error location. Use this function to set up an error context stack
133 * entry that will accomplish that. Usage pattern:
135 * declare a local variable "ParseCallbackState pcbstate"
137 * setup_parser_errposition_callback(&pcbstate, pstate, location);
138 * call function that might throw error;
139 * cancel_parser_errposition_callback(&pcbstate);
142 setup_parser_errposition_callback(ParseCallbackState *pcbstate,
143 ParseState *pstate, int location)
145 /* Setup error traceback support for ereport() */
146 pcbstate->pstate = pstate;
147 pcbstate->location = location;
148 pcbstate->errcallback.callback = pcb_error_callback;
149 pcbstate->errcallback.arg = (void *) pcbstate;
150 pcbstate->errcallback.previous = error_context_stack;
151 error_context_stack = &pcbstate->errcallback;
155 * Cancel a previously-set-up errposition callback.
158 cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
160 /* Pop the error context stack */
161 error_context_stack = pcbstate->errcallback.previous;
165 * Error context callback for inserting parser error location.
167 * Note that this will be called for *any* error occurring while the
168 * callback is installed. We avoid inserting an irrelevant error location
169 * if the error is a query cancel --- are there any other important cases?
172 pcb_error_callback(void *arg)
174 ParseCallbackState *pcbstate = (ParseCallbackState *) arg;
176 if (geterrcode() != ERRCODE_QUERY_CANCELED)
177 (void) parser_errposition(pcbstate->pstate, pcbstate->location);
183 * Build a Var node for an attribute identified by RTE and attrno
186 make_var(ParseState *pstate, RangeTblEntry *rte, int attrno, int location)
195 vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
196 get_rte_attribute_type(rte, attrno, &vartypeid, &type_mod, &varcollid);
197 result = makeVar(vnum, attrno, vartypeid, type_mod, varcollid, sublevels_up);
198 result->location = location;
203 * transformArrayType()
204 * Identify the types involved in a subscripting operation
206 * On entry, arrayType/arrayTypmod identify the type of the input value
207 * to be subscripted (which could be a domain type). These are modified
208 * if necessary to identify the actual array type and typmod, and the
209 * array's element type is returned. An error is thrown if the input isn't
213 transformArrayType(Oid *arrayType, int32 *arrayTypmod)
215 Oid origArrayType = *arrayType;
217 HeapTuple type_tuple_array;
218 Form_pg_type type_struct_array;
221 * If the input is a domain, smash to base type, and extract the actual
222 * typmod to be applied to the base type. Subscripting a domain is an
223 * operation that necessarily works on the base array type, not the domain
224 * itself. (Note that we provide no method whereby the creator of a
225 * domain over an array type could hide its ability to be subscripted.)
227 *arrayType = getBaseTypeAndTypmod(*arrayType, arrayTypmod);
230 * We treat int2vector and oidvector as though they were domains over
231 * int2[] and oid[]. This is needed because array slicing could create an
232 * array that doesn't satisfy the dimensionality constraints of the
233 * xxxvector type; so we want the result of a slice operation to be
234 * considered to be of the more general type.
236 if (*arrayType == INT2VECTOROID)
237 *arrayType = INT2ARRAYOID;
238 else if (*arrayType == OIDVECTOROID)
239 *arrayType = OIDARRAYOID;
241 /* Get the type tuple for the array */
242 type_tuple_array = SearchSysCache1(TYPEOID, ObjectIdGetDatum(*arrayType));
243 if (!HeapTupleIsValid(type_tuple_array))
244 elog(ERROR, "cache lookup failed for type %u", *arrayType);
245 type_struct_array = (Form_pg_type) GETSTRUCT(type_tuple_array);
247 /* needn't check typisdefined since this will fail anyway */
249 elementType = type_struct_array->typelem;
250 if (elementType == InvalidOid)
252 (errcode(ERRCODE_DATATYPE_MISMATCH),
253 errmsg("cannot subscript type %s because it is not an array",
254 format_type_be(origArrayType))));
256 ReleaseSysCache(type_tuple_array);
262 * transformArraySubscripts()
263 * Transform array subscripting. This is used for both
264 * array fetch and array assignment.
266 * In an array fetch, we are given a source array value and we produce an
267 * expression that represents the result of extracting a single array element
270 * In an array assignment, we are given a destination array value plus a
271 * source value that is to be assigned to a single element or a slice of
272 * that array. We produce an expression that represents the new array value
273 * with the source data inserted into the right part of the array.
275 * For both cases, if the source array is of a domain-over-array type,
276 * the result is of the base array type or its element type; essentially,
277 * we must fold a domain to its base type before applying subscripting.
278 * (Note that int2vector and oidvector are treated as domains here.)
281 * arrayBase Already-transformed expression for the array as a whole
282 * arrayType OID of array's datatype (should match type of arrayBase,
283 * or be the base type of arrayBase's domain type)
284 * elementType OID of array's element type (fetch with transformArrayType,
285 * or pass InvalidOid to do it here)
286 * arrayTypMod typmod for the array (which is also typmod for the elements)
287 * indirection Untransformed list of subscripts (must not be NIL)
288 * assignFrom NULL for array fetch, else transformed expression for source.
291 transformArraySubscripts(ParseState *pstate,
299 bool isSlice = false;
300 List *upperIndexpr = NIL;
301 List *lowerIndexpr = NIL;
306 * Caller may or may not have bothered to determine elementType. Note
307 * that if the caller did do so, arrayType/arrayTypMod must be as modified
308 * by transformArrayType, ie, smash domain to base type.
310 if (!OidIsValid(elementType))
311 elementType = transformArrayType(&arrayType, &arrayTypMod);
314 * A list containing only simple subscripts refers to a single array
315 * element. If any of the items are slice specifiers (lower:upper), then
316 * the subscript expression means an array slice operation. In this case,
317 * we convert any non-slice items to slices by treating the single
318 * subscript as the upper bound and supplying an assumed lower bound of 1.
319 * We have to prescan the list to see if there are any slice items.
321 foreach(idx, indirection)
323 A_Indices *ai = (A_Indices *) lfirst(idx);
333 * Transform the subscript expressions.
335 foreach(idx, indirection)
337 A_Indices *ai = (A_Indices *) lfirst(idx);
340 Assert(IsA(ai, A_Indices));
345 subexpr = transformExpr(pstate, ai->lidx, pstate->p_expr_kind);
346 /* If it's not int4 already, try to coerce */
347 subexpr = coerce_to_target_type(pstate,
348 subexpr, exprType(subexpr),
351 COERCE_IMPLICIT_CAST,
355 (errcode(ERRCODE_DATATYPE_MISMATCH),
356 errmsg("array subscript must have type integer"),
357 parser_errposition(pstate, exprLocation(ai->lidx))));
359 else if (!ai->is_slice)
361 /* Make a constant 1 */
362 subexpr = (Node *) makeConst(INT4OID,
368 true); /* pass by value */
372 /* Slice with omitted lower bound, put NULL into the list */
375 lowerIndexpr = lappend(lowerIndexpr, subexpr);
378 Assert(ai->lidx == NULL && !ai->is_slice);
382 subexpr = transformExpr(pstate, ai->uidx, pstate->p_expr_kind);
383 /* If it's not int4 already, try to coerce */
384 subexpr = coerce_to_target_type(pstate,
385 subexpr, exprType(subexpr),
388 COERCE_IMPLICIT_CAST,
392 (errcode(ERRCODE_DATATYPE_MISMATCH),
393 errmsg("array subscript must have type integer"),
394 parser_errposition(pstate, exprLocation(ai->uidx))));
398 /* Slice with omitted upper bound, put NULL into the list */
399 Assert(isSlice && ai->is_slice);
402 upperIndexpr = lappend(upperIndexpr, subexpr);
406 * If doing an array store, coerce the source value to the right type.
407 * (This should agree with the coercion done by transformAssignedExpr.)
409 if (assignFrom != NULL)
411 Oid typesource = exprType(assignFrom);
412 Oid typeneeded = isSlice ? arrayType : elementType;
415 newFrom = coerce_to_target_type(pstate,
416 assignFrom, typesource,
417 typeneeded, arrayTypMod,
419 COERCE_IMPLICIT_CAST,
423 (errcode(ERRCODE_DATATYPE_MISMATCH),
424 errmsg("array assignment requires type %s"
425 " but expression is of type %s",
426 format_type_be(typeneeded),
427 format_type_be(typesource)),
428 errhint("You will need to rewrite or cast the expression."),
429 parser_errposition(pstate, exprLocation(assignFrom))));
430 assignFrom = newFrom;
434 * Ready to build the ArrayRef node.
436 aref = makeNode(ArrayRef);
437 aref->refarraytype = arrayType;
438 aref->refelemtype = elementType;
439 aref->reftypmod = arrayTypMod;
440 /* refcollid will be set by parse_collate.c */
441 aref->refupperindexpr = upperIndexpr;
442 aref->reflowerindexpr = lowerIndexpr;
443 aref->refexpr = (Expr *) arrayBase;
444 aref->refassgnexpr = (Expr *) assignFrom;
452 * Convert a Value node (as returned by the grammar) to a Const node
453 * of the "natural" type for the constant. Note that this routine is
454 * only used when there is no explicit cast for the constant, so we
455 * have to guess what type is wanted.
457 * For string literals we produce a constant of type UNKNOWN ---- whose
458 * representation is the same as cstring, but it indicates to later type
459 * resolution that we're not sure yet what type it should be considered.
460 * Explicit "NULL" constants are also typed as UNKNOWN.
462 * For integers and floats we produce int4, int8, or numeric depending
463 * on the value of the number. XXX We should produce int2 as well,
464 * but additional cleanup is needed before we can do that; there are
465 * too many examples that fail if we try.
468 make_const(ParseState *pstate, Value *value, int location)
476 ParseCallbackState pcbstate;
478 switch (nodeTag(value))
481 val = Int32GetDatum(intVal(value));
484 typelen = sizeof(int32);
489 /* could be an oversize integer as well as a float ... */
490 if (scanint8(strVal(value), true, &val64))
493 * It might actually fit in int32. Probably only INT_MIN can
494 * occur, but we'll code the test generally just to be sure.
496 int32 val32 = (int32) val64;
498 if (val64 == (int64) val32)
500 val = Int32GetDatum(val32);
503 typelen = sizeof(int32);
508 val = Int64GetDatum(val64);
511 typelen = sizeof(int64);
512 typebyval = FLOAT8PASSBYVAL; /* int8 and float8 alike */
517 /* arrange to report location if numeric_in() fails */
518 setup_parser_errposition_callback(&pcbstate, pstate, location);
519 val = DirectFunctionCall3(numeric_in,
520 CStringGetDatum(strVal(value)),
521 ObjectIdGetDatum(InvalidOid),
523 cancel_parser_errposition_callback(&pcbstate);
526 typelen = -1; /* variable len */
534 * We assume here that UNKNOWN's internal representation is the
537 val = CStringGetDatum(strVal(value));
539 typeid = UNKNOWNOID; /* will be coerced later */
540 typelen = -2; /* cstring-style varwidth type */
545 /* arrange to report location if bit_in() fails */
546 setup_parser_errposition_callback(&pcbstate, pstate, location);
547 val = DirectFunctionCall3(bit_in,
548 CStringGetDatum(strVal(value)),
549 ObjectIdGetDatum(InvalidOid),
551 cancel_parser_errposition_callback(&pcbstate);
558 /* return a null const */
559 con = makeConst(UNKNOWNOID,
566 con->location = location;
570 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(value));
571 return NULL; /* keep compiler quiet */
574 con = makeConst(typeid,
575 -1, /* typmod -1 is OK for all cases */
576 InvalidOid, /* all cases are uncollatable types */
581 con->location = location;