1 /*-------------------------------------------------------------------------
4 * various routines that make nodes for querytrees
6 * Portions Copyright (c) 1996-2006, 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.95 2006/10/04 00:29:56 momjian Exp $
13 *-------------------------------------------------------------------------
17 #include "catalog/pg_type.h"
18 #include "mb/pg_wchar.h"
19 #include "nodes/makefuncs.h"
20 #include "parser/parsetree.h"
21 #include "parser/parse_coerce.h"
22 #include "parser/parse_expr.h"
23 #include "parser/parse_relation.h"
24 #include "utils/builtins.h"
25 #include "utils/int8.h"
26 #include "utils/syscache.h"
27 #include "utils/varbit.h"
31 * Allocate and initialize a new ParseState.
32 * The CALLER is responsible for freeing the ParseState* returned.
35 make_parsestate(ParseState *parentParseState)
39 pstate = palloc0(sizeof(ParseState));
41 pstate->parentParseState = parentParseState;
43 /* Fill in fields that don't start at null/false/zero */
44 pstate->p_next_resno = 1;
48 pstate->p_sourcetext = parentParseState->p_sourcetext;
49 pstate->p_variableparams = parentParseState->p_variableparams;
58 * Report a parse-analysis-time cursor position, if possible.
60 * This is expected to be used within an ereport() call. The return value
61 * is a dummy (always 0, in fact).
63 * The locations stored in raw parsetrees are byte offsets into the source
64 * string. We have to convert them to 1-based character indexes for reporting
65 * to clients. (We do things this way to avoid unnecessary overhead in the
66 * normal non-error case: computing character indexes would be much more
67 * expensive than storing token offsets.)
70 parser_errposition(ParseState *pstate, int location)
74 /* No-op if location was not provided */
77 /* Can't do anything if source text is not available */
78 if (pstate == NULL || pstate->p_sourcetext == NULL)
80 /* Convert offset to character number */
81 pos = pg_mbstrlen_with_len(pstate->p_sourcetext, location) + 1;
82 /* And pass it to the ereport mechanism */
83 return errposition(pos);
89 * Build a Var node for an attribute identified by RTE and attrno
92 make_var(ParseState *pstate, RangeTblEntry *rte, int attrno)
99 vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
100 get_rte_attribute_type(rte, attrno, &vartypeid, &type_mod);
101 return makeVar(vnum, attrno, vartypeid, type_mod, sublevels_up);
105 * transformArrayType()
106 * Get the element type of an array type in preparation for subscripting
109 transformArrayType(Oid arrayType)
112 HeapTuple type_tuple_array;
113 Form_pg_type type_struct_array;
115 /* Get the type tuple for the array */
116 type_tuple_array = SearchSysCache(TYPEOID,
117 ObjectIdGetDatum(arrayType),
119 if (!HeapTupleIsValid(type_tuple_array))
120 elog(ERROR, "cache lookup failed for type %u", arrayType);
121 type_struct_array = (Form_pg_type) GETSTRUCT(type_tuple_array);
123 /* needn't check typisdefined since this will fail anyway */
125 elementType = type_struct_array->typelem;
126 if (elementType == InvalidOid)
128 (errcode(ERRCODE_DATATYPE_MISMATCH),
129 errmsg("cannot subscript type %s because it is not an array",
130 format_type_be(arrayType))));
132 ReleaseSysCache(type_tuple_array);
138 * transformArraySubscripts()
139 * Transform array subscripting. This is used for both
140 * array fetch and array assignment.
142 * In an array fetch, we are given a source array value and we produce an
143 * expression that represents the result of extracting a single array element
146 * In an array assignment, we are given a destination array value plus a
147 * source value that is to be assigned to a single element or a slice of
148 * that array. We produce an expression that represents the new array value
149 * with the source data inserted into the right part of the array.
152 * arrayBase Already-transformed expression for the array as a whole
153 * arrayType OID of array's datatype (should match type of arrayBase)
154 * elementType OID of array's element type (fetch with transformArrayType,
155 * or pass InvalidOid to do it here)
156 * elementTypMod typmod to be applied to array elements (if storing)
157 * indirection Untransformed list of subscripts (must not be NIL)
158 * assignFrom NULL for array fetch, else transformed expression for source.
161 transformArraySubscripts(ParseState *pstate,
170 bool isSlice = false;
171 List *upperIndexpr = NIL;
172 List *lowerIndexpr = NIL;
176 /* Caller may or may not have bothered to determine elementType */
177 if (!OidIsValid(elementType))
178 elementType = transformArrayType(arrayType);
181 * A list containing only single subscripts refers to a single array
182 * element. If any of the items are double subscripts (lower:upper), then
183 * the subscript expression means an array slice operation. In this case,
184 * we supply a default lower bound of 1 for any items that contain only a
185 * single subscript. We have to prescan the indirection list to see if
186 * there are any double subscripts.
188 foreach(idx, indirection)
190 A_Indices *ai = (A_Indices *) lfirst(idx);
192 if (ai->lidx != NULL)
200 * The type represented by the subscript expression is the element type if
201 * we are fetching a single element, but it is the same as the array type
202 * if we are fetching a slice or storing.
204 if (isSlice || assignFrom != NULL)
205 resultType = arrayType;
207 resultType = elementType;
210 * Transform the subscript expressions.
212 foreach(idx, indirection)
214 A_Indices *ai = (A_Indices *) lfirst(idx);
217 Assert(IsA(ai, A_Indices));
222 subexpr = transformExpr(pstate, ai->lidx);
223 /* If it's not int4 already, try to coerce */
224 subexpr = coerce_to_target_type(pstate,
225 subexpr, exprType(subexpr),
228 COERCE_IMPLICIT_CAST);
231 (errcode(ERRCODE_DATATYPE_MISMATCH),
232 errmsg("array subscript must have type integer")));
236 /* Make a constant 1 */
237 subexpr = (Node *) makeConst(INT4OID,
241 true); /* pass by value */
243 lowerIndexpr = lappend(lowerIndexpr, subexpr);
245 subexpr = transformExpr(pstate, ai->uidx);
246 /* If it's not int4 already, try to coerce */
247 subexpr = coerce_to_target_type(pstate,
248 subexpr, exprType(subexpr),
251 COERCE_IMPLICIT_CAST);
254 (errcode(ERRCODE_DATATYPE_MISMATCH),
255 errmsg("array subscript must have type integer")));
256 upperIndexpr = lappend(upperIndexpr, subexpr);
260 * If doing an array store, coerce the source value to the right type.
261 * (This should agree with the coercion done by transformAssignedExpr.)
263 if (assignFrom != NULL)
265 Oid typesource = exprType(assignFrom);
266 Oid typeneeded = isSlice ? arrayType : elementType;
268 assignFrom = coerce_to_target_type(pstate,
269 assignFrom, typesource,
270 typeneeded, elementTypMod,
272 COERCE_IMPLICIT_CAST);
273 if (assignFrom == NULL)
275 (errcode(ERRCODE_DATATYPE_MISMATCH),
276 errmsg("array assignment requires type %s"
277 " but expression is of type %s",
278 format_type_be(typeneeded),
279 format_type_be(typesource)),
280 errhint("You will need to rewrite or cast the expression.")));
284 * Ready to build the ArrayRef node.
286 aref = makeNode(ArrayRef);
287 aref->refrestype = resultType;
288 aref->refarraytype = arrayType;
289 aref->refelemtype = elementType;
290 aref->refupperindexpr = upperIndexpr;
291 aref->reflowerindexpr = lowerIndexpr;
292 aref->refexpr = (Expr *) arrayBase;
293 aref->refassgnexpr = (Expr *) assignFrom;
301 * Convert a Value node (as returned by the grammar) to a Const node
302 * of the "natural" type for the constant. Note that this routine is
303 * only used when there is no explicit cast for the constant, so we
304 * have to guess what type is wanted.
306 * For string literals we produce a constant of type UNKNOWN ---- whose
307 * representation is the same as cstring, but it indicates to later type
308 * resolution that we're not sure yet what type it should be considered.
309 * Explicit "NULL" constants are also typed as UNKNOWN.
311 * For integers and floats we produce int4, int8, or numeric depending
312 * on the value of the number. XXX We should produce int2 as well,
313 * but additional cleanup is needed before we can do that; there are
314 * too many examples that fail if we try.
317 make_const(Value *value)
326 switch (nodeTag(value))
329 val = Int32GetDatum(intVal(value));
332 typelen = sizeof(int32);
337 /* could be an oversize integer as well as a float ... */
338 if (scanint8(strVal(value), true, &val64))
341 * It might actually fit in int32. Probably only INT_MIN can
342 * occur, but we'll code the test generally just to be sure.
344 int32 val32 = (int32) val64;
346 if (val64 == (int64) val32)
348 val = Int32GetDatum(val32);
351 typelen = sizeof(int32);
356 val = Int64GetDatum(val64);
359 typelen = sizeof(int64);
360 typebyval = false; /* XXX might change someday */
365 val = DirectFunctionCall3(numeric_in,
366 CStringGetDatum(strVal(value)),
367 ObjectIdGetDatum(InvalidOid),
371 typelen = -1; /* variable len */
379 * We assume here that UNKNOWN's internal representation is the
382 val = CStringGetDatum(strVal(value));
384 typeid = UNKNOWNOID; /* will be coerced later */
385 typelen = -2; /* cstring-style varwidth type */
390 val = DirectFunctionCall3(bit_in,
391 CStringGetDatum(strVal(value)),
392 ObjectIdGetDatum(InvalidOid),
400 /* return a null const */
401 con = makeConst(UNKNOWNOID,
409 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(value));
410 return NULL; /* keep compiler quiet */
413 con = makeConst(typeid,