1 /*-------------------------------------------------------------------------
4 * various routines that make nodes for querytrees
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/parser/parse_node.c,v 1.106 2009/10/31 01:41:31 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "access/heapam.h"
18 #include "catalog/pg_type.h"
19 #include "mb/pg_wchar.h"
20 #include "nodes/makefuncs.h"
21 #include "nodes/nodeFuncs.h"
22 #include "parser/parsetree.h"
23 #include "parser/parse_coerce.h"
24 #include "parser/parse_expr.h"
25 #include "parser/parse_relation.h"
26 #include "utils/builtins.h"
27 #include "utils/int8.h"
28 #include "utils/syscache.h"
29 #include "utils/varbit.h"
32 static void pcb_error_callback(void *arg);
37 * Allocate and initialize a new ParseState.
39 * Caller should eventually release the ParseState via free_parsestate().
42 make_parsestate(ParseState *parentParseState)
46 pstate = palloc0(sizeof(ParseState));
48 pstate->parentParseState = parentParseState;
50 /* Fill in fields that don't start at null/false/zero */
51 pstate->p_next_resno = 1;
55 pstate->p_sourcetext = parentParseState->p_sourcetext;
56 /* all hooks are copied from parent */
57 pstate->p_pre_columnref_hook = parentParseState->p_pre_columnref_hook;
58 pstate->p_post_columnref_hook = parentParseState->p_post_columnref_hook;
59 pstate->p_paramref_hook = parentParseState->p_paramref_hook;
60 pstate->p_coerce_param_hook = parentParseState->p_coerce_param_hook;
61 pstate->p_ref_hook_state = parentParseState->p_ref_hook_state;
69 * Release a ParseState and any subsidiary resources.
72 free_parsestate(ParseState *pstate)
75 * Check that we did not produce too many resnos; at the very least we
76 * cannot allow more than 2^16, since that would exceed the range of a
77 * AttrNumber. It seems safest to use MaxTupleAttributeNumber.
79 if (pstate->p_next_resno - 1 > MaxTupleAttributeNumber)
81 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
82 errmsg("target lists can have at most %d entries",
83 MaxTupleAttributeNumber)));
85 if (pstate->p_target_relation != NULL)
86 heap_close(pstate->p_target_relation, NoLock);
94 * Report a parse-analysis-time cursor position, if possible.
96 * This is expected to be used within an ereport() call. The return value
97 * is a dummy (always 0, in fact).
99 * The locations stored in raw parsetrees are byte offsets into the source
100 * string. We have to convert them to 1-based character indexes for reporting
101 * to clients. (We do things this way to avoid unnecessary overhead in the
102 * normal non-error case: computing character indexes would be much more
103 * expensive than storing token offsets.)
106 parser_errposition(ParseState *pstate, int location)
110 /* No-op if location was not provided */
113 /* Can't do anything if source text is not available */
114 if (pstate == NULL || pstate->p_sourcetext == NULL)
116 /* Convert offset to character number */
117 pos = pg_mbstrlen_with_len(pstate->p_sourcetext, location) + 1;
118 /* And pass it to the ereport mechanism */
119 return errposition(pos);
124 * setup_parser_errposition_callback
125 * Arrange for non-parser errors to report an error position
127 * Sometimes the parser calls functions that aren't part of the parser
128 * subsystem and can't reasonably be passed a ParseState; yet we would
129 * like any errors thrown in those functions to be tagged with a parse
130 * error location. Use this function to set up an error context stack
131 * entry that will accomplish that. Usage pattern:
133 * declare a local variable "ParseCallbackState pcbstate"
135 * setup_parser_errposition_callback(&pcbstate, pstate, location);
136 * call function that might throw error;
137 * cancel_parser_errposition_callback(&pcbstate);
140 setup_parser_errposition_callback(ParseCallbackState *pcbstate,
141 ParseState *pstate, int location)
143 /* Setup error traceback support for ereport() */
144 pcbstate->pstate = pstate;
145 pcbstate->location = location;
146 pcbstate->errcontext.callback = pcb_error_callback;
147 pcbstate->errcontext.arg = (void *) pcbstate;
148 pcbstate->errcontext.previous = error_context_stack;
149 error_context_stack = &pcbstate->errcontext;
153 * Cancel a previously-set-up errposition callback.
156 cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
158 /* Pop the error context stack */
159 error_context_stack = pcbstate->errcontext.previous;
163 * Error context callback for inserting parser error location.
165 * Note that this will be called for *any* error occurring while the
166 * callback is installed. We avoid inserting an irrelevant error location
167 * if the error is a query cancel --- are there any other important cases?
170 pcb_error_callback(void *arg)
172 ParseCallbackState *pcbstate = (ParseCallbackState *) arg;
174 if (geterrcode() != ERRCODE_QUERY_CANCELED)
175 (void) parser_errposition(pcbstate->pstate, pcbstate->location);
181 * Build a Var node for an attribute identified by RTE and attrno
184 make_var(ParseState *pstate, RangeTblEntry *rte, int attrno, int location)
192 vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
193 get_rte_attribute_type(rte, attrno, &vartypeid, &type_mod);
194 result = makeVar(vnum, attrno, vartypeid, type_mod, sublevels_up);
195 result->location = location;
200 * transformArrayType()
201 * Get the element type of an array type in preparation for subscripting
204 transformArrayType(Oid arrayType)
207 HeapTuple type_tuple_array;
208 Form_pg_type type_struct_array;
210 /* Get the type tuple for the array */
211 type_tuple_array = SearchSysCache(TYPEOID,
212 ObjectIdGetDatum(arrayType),
214 if (!HeapTupleIsValid(type_tuple_array))
215 elog(ERROR, "cache lookup failed for type %u", arrayType);
216 type_struct_array = (Form_pg_type) GETSTRUCT(type_tuple_array);
218 /* needn't check typisdefined since this will fail anyway */
220 elementType = type_struct_array->typelem;
221 if (elementType == InvalidOid)
223 (errcode(ERRCODE_DATATYPE_MISMATCH),
224 errmsg("cannot subscript type %s because it is not an array",
225 format_type_be(arrayType))));
227 ReleaseSysCache(type_tuple_array);
233 * transformArraySubscripts()
234 * Transform array subscripting. This is used for both
235 * array fetch and array assignment.
237 * In an array fetch, we are given a source array value and we produce an
238 * expression that represents the result of extracting a single array element
241 * In an array assignment, we are given a destination array value plus a
242 * source value that is to be assigned to a single element or a slice of
243 * that array. We produce an expression that represents the new array value
244 * with the source data inserted into the right part of the array.
247 * arrayBase Already-transformed expression for the array as a whole
248 * arrayType OID of array's datatype (should match type of arrayBase)
249 * elementType OID of array's element type (fetch with transformArrayType,
250 * or pass InvalidOid to do it here)
251 * elementTypMod typmod to be applied to array elements (if storing) or of
252 * the source array (if fetching)
253 * indirection Untransformed list of subscripts (must not be NIL)
254 * assignFrom NULL for array fetch, else transformed expression for source.
257 transformArraySubscripts(ParseState *pstate,
265 bool isSlice = false;
266 List *upperIndexpr = NIL;
267 List *lowerIndexpr = NIL;
271 /* Caller may or may not have bothered to determine elementType */
272 if (!OidIsValid(elementType))
273 elementType = transformArrayType(arrayType);
276 * A list containing only single subscripts refers to a single array
277 * element. If any of the items are double subscripts (lower:upper), then
278 * the subscript expression means an array slice operation. In this case,
279 * we supply a default lower bound of 1 for any items that contain only a
280 * single subscript. We have to prescan the indirection list to see if
281 * there are any double subscripts.
283 foreach(idx, indirection)
285 A_Indices *ai = (A_Indices *) lfirst(idx);
287 if (ai->lidx != NULL)
295 * Transform the subscript expressions.
297 foreach(idx, indirection)
299 A_Indices *ai = (A_Indices *) lfirst(idx);
302 Assert(IsA(ai, A_Indices));
307 subexpr = transformExpr(pstate, ai->lidx);
308 /* If it's not int4 already, try to coerce */
309 subexpr = coerce_to_target_type(pstate,
310 subexpr, exprType(subexpr),
313 COERCE_IMPLICIT_CAST,
317 (errcode(ERRCODE_DATATYPE_MISMATCH),
318 errmsg("array subscript must have type integer"),
319 parser_errposition(pstate, exprLocation(ai->lidx))));
323 /* Make a constant 1 */
324 subexpr = (Node *) makeConst(INT4OID,
329 true); /* pass by value */
331 lowerIndexpr = lappend(lowerIndexpr, subexpr);
333 subexpr = transformExpr(pstate, ai->uidx);
334 /* If it's not int4 already, try to coerce */
335 subexpr = coerce_to_target_type(pstate,
336 subexpr, exprType(subexpr),
339 COERCE_IMPLICIT_CAST,
343 (errcode(ERRCODE_DATATYPE_MISMATCH),
344 errmsg("array subscript must have type integer"),
345 parser_errposition(pstate, exprLocation(ai->uidx))));
346 upperIndexpr = lappend(upperIndexpr, subexpr);
350 * If doing an array store, coerce the source value to the right type.
351 * (This should agree with the coercion done by transformAssignedExpr.)
353 if (assignFrom != NULL)
355 Oid typesource = exprType(assignFrom);
356 Oid typeneeded = isSlice ? arrayType : elementType;
359 newFrom = coerce_to_target_type(pstate,
360 assignFrom, typesource,
361 typeneeded, elementTypMod,
363 COERCE_IMPLICIT_CAST,
367 (errcode(ERRCODE_DATATYPE_MISMATCH),
368 errmsg("array assignment requires type %s"
369 " but expression is of type %s",
370 format_type_be(typeneeded),
371 format_type_be(typesource)),
372 errhint("You will need to rewrite or cast the expression."),
373 parser_errposition(pstate, exprLocation(assignFrom))));
374 assignFrom = newFrom;
378 * Ready to build the ArrayRef node.
380 aref = makeNode(ArrayRef);
381 aref->refarraytype = arrayType;
382 aref->refelemtype = elementType;
383 aref->reftypmod = elementTypMod;
384 aref->refupperindexpr = upperIndexpr;
385 aref->reflowerindexpr = lowerIndexpr;
386 aref->refexpr = (Expr *) arrayBase;
387 aref->refassgnexpr = (Expr *) assignFrom;
395 * Convert a Value node (as returned by the grammar) to a Const node
396 * of the "natural" type for the constant. Note that this routine is
397 * only used when there is no explicit cast for the constant, so we
398 * have to guess what type is wanted.
400 * For string literals we produce a constant of type UNKNOWN ---- whose
401 * representation is the same as cstring, but it indicates to later type
402 * resolution that we're not sure yet what type it should be considered.
403 * Explicit "NULL" constants are also typed as UNKNOWN.
405 * For integers and floats we produce int4, int8, or numeric depending
406 * on the value of the number. XXX We should produce int2 as well,
407 * but additional cleanup is needed before we can do that; there are
408 * too many examples that fail if we try.
411 make_const(ParseState *pstate, Value *value, int location)
419 ParseCallbackState pcbstate;
421 switch (nodeTag(value))
424 val = Int32GetDatum(intVal(value));
427 typelen = sizeof(int32);
432 /* could be an oversize integer as well as a float ... */
433 if (scanint8(strVal(value), true, &val64))
436 * It might actually fit in int32. Probably only INT_MIN can
437 * occur, but we'll code the test generally just to be sure.
439 int32 val32 = (int32) val64;
441 if (val64 == (int64) val32)
443 val = Int32GetDatum(val32);
446 typelen = sizeof(int32);
451 val = Int64GetDatum(val64);
454 typelen = sizeof(int64);
455 typebyval = FLOAT8PASSBYVAL; /* int8 and float8 alike */
460 /* arrange to report location if numeric_in() fails */
461 setup_parser_errposition_callback(&pcbstate, pstate, location);
462 val = DirectFunctionCall3(numeric_in,
463 CStringGetDatum(strVal(value)),
464 ObjectIdGetDatum(InvalidOid),
466 cancel_parser_errposition_callback(&pcbstate);
469 typelen = -1; /* variable len */
477 * We assume here that UNKNOWN's internal representation is the
480 val = CStringGetDatum(strVal(value));
482 typeid = UNKNOWNOID; /* will be coerced later */
483 typelen = -2; /* cstring-style varwidth type */
488 /* arrange to report location if bit_in() fails */
489 setup_parser_errposition_callback(&pcbstate, pstate, location);
490 val = DirectFunctionCall3(bit_in,
491 CStringGetDatum(strVal(value)),
492 ObjectIdGetDatum(InvalidOid),
494 cancel_parser_errposition_callback(&pcbstate);
501 /* return a null const */
502 con = makeConst(UNKNOWNOID,
508 con->location = location;
512 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(value));
513 return NULL; /* keep compiler quiet */
516 con = makeConst(typeid,
517 -1, /* typmod -1 is OK for all cases */
522 con->location = location;