1 /*-------------------------------------------------------------------------
4 * various routines that make nodes for query plans
6 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/parser/parse_node.c,v 1.62 2002/04/16 23:08:11 tgl Exp $
13 *-------------------------------------------------------------------------
21 #include "access/heapam.h"
22 #include "catalog/pg_operator.h"
23 #include "catalog/pg_type.h"
25 #include "nodes/makefuncs.h"
26 #include "parser/parsetree.h"
27 #include "parser/parse_coerce.h"
28 #include "parser/parse_expr.h"
29 #include "parser/parse_node.h"
30 #include "parser/parse_oper.h"
31 #include "parser/parse_relation.h"
32 #include "parser/parse_target.h"
33 #include "parser/parse_type.h"
34 #include "utils/builtins.h"
35 #include "utils/varbit.h"
36 #include "utils/lsyscache.h"
37 #include "utils/syscache.h"
39 static bool fitsInFloat(Value *value);
43 * Allocate and initialize a new ParseState.
44 * The CALLER is responsible for freeing the ParseState* returned.
47 make_parsestate(ParseState *parentParseState)
51 pstate = palloc(sizeof(ParseState));
52 MemSet(pstate, 0, sizeof(ParseState));
54 pstate->parentParseState = parentParseState;
55 pstate->p_last_resno = 1;
62 * Ensure argument type match by forcing conversion of constants.
65 make_operand(Node *tree, Oid orig_typeId, Oid target_typeId)
72 if (target_typeId != orig_typeId)
73 result = coerce_type(NULL, tree, orig_typeId, target_typeId, -1,
80 /* otherwise, this is a NULL value */
81 result = (Node *) makeNullConst(target_typeId);
85 } /* make_operand() */
89 * Operator construction.
91 * Transform operator expression ensuring type compatibility.
92 * This is where some type conversion happens.
95 make_op(List *opname, Node *ltree, Node *rtree)
100 Form_pg_operator opform;
106 ltypeId = (ltree == NULL) ? UNKNOWNOID : exprType(ltree);
107 rtypeId = (rtree == NULL) ? UNKNOWNOID : exprType(rtree);
109 /* right operator? */
112 tup = right_oper(opname, ltypeId);
113 opform = (Form_pg_operator) GETSTRUCT(tup);
114 left = make_operand(ltree, ltypeId, opform->oprleft);
119 else if (ltree == NULL)
121 tup = left_oper(opname, rtypeId);
122 opform = (Form_pg_operator) GETSTRUCT(tup);
123 right = make_operand(rtree, rtypeId, opform->oprright);
127 /* otherwise, binary operator */
130 tup = oper(opname, ltypeId, rtypeId, false);
131 opform = (Form_pg_operator) GETSTRUCT(tup);
132 left = make_operand(ltree, ltypeId, opform->oprleft);
133 right = make_operand(rtree, rtypeId, opform->oprright);
136 newop = makeOper(oprid(tup), /* opno */
137 InvalidOid, /* opid */
138 opform->oprresult); /* operator result type */
140 result = makeNode(Expr);
141 result->typeOid = opform->oprresult;
142 result->opType = OP_EXPR;
143 result->oper = (Node *) newop;
146 result->args = makeList1(right);
148 result->args = makeList1(left);
150 result->args = makeList2(left, right);
152 ReleaseSysCache(tup);
160 * Build a Var node for an attribute identified by RTE and attrno
163 make_var(ParseState *pstate, RangeTblEntry *rte, int attrno)
170 vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
171 get_rte_attribute_type(rte, attrno, &vartypeid, &type_mod);
172 return makeVar(vnum, attrno, vartypeid, type_mod, sublevels_up);
176 * transformArraySubscripts()
177 * Transform array subscripting. This is used for both
178 * array fetch and array assignment.
180 * In an array fetch, we are given a source array value and we produce an
181 * expression that represents the result of extracting a single array element
184 * In an array assignment, we are given a destination array value plus a
185 * source value that is to be assigned to a single element or a slice of
186 * that array. We produce an expression that represents the new array value
187 * with the source data inserted into the right part of the array.
190 * arrayBase Already-transformed expression for the array as a whole
191 * (may be NULL if we are handling an INSERT)
192 * arrayType OID of array's datatype
193 * indirection Untransformed list of subscripts (must not be NIL)
194 * forceSlice If true, treat subscript as array slice in all cases
195 * assignFrom NULL for array fetch, else transformed expression for source.
198 transformArraySubscripts(ParseState *pstate,
207 HeapTuple type_tuple_array,
209 Form_pg_type type_struct_array,
211 bool isSlice = forceSlice;
212 List *upperIndexpr = NIL;
213 List *lowerIndexpr = NIL;
217 /* Get the type tuple for the array */
218 type_tuple_array = SearchSysCache(TYPEOID,
219 ObjectIdGetDatum(arrayType),
221 if (!HeapTupleIsValid(type_tuple_array))
222 elog(ERROR, "transformArraySubscripts: Cache lookup failed for array type %u",
224 type_struct_array = (Form_pg_type) GETSTRUCT(type_tuple_array);
226 elementType = type_struct_array->typelem;
227 if (elementType == InvalidOid)
228 elog(ERROR, "transformArraySubscripts: type %s is not an array",
229 NameStr(type_struct_array->typname));
231 /* Get the type tuple for the array element type */
232 type_tuple_element = SearchSysCache(TYPEOID,
233 ObjectIdGetDatum(elementType),
235 if (!HeapTupleIsValid(type_tuple_element))
236 elog(ERROR, "transformArraySubscripts: Cache lookup failed for array element type %u",
238 type_struct_element = (Form_pg_type) GETSTRUCT(type_tuple_element);
241 * A list containing only single subscripts refers to a single array
242 * element. If any of the items are double subscripts (lower:upper),
243 * then the subscript expression means an array slice operation. In
244 * this case, we supply a default lower bound of 1 for any items that
245 * contain only a single subscript. The forceSlice parameter forces us
246 * to treat the operation as a slice, even if no lower bounds are
247 * mentioned. Otherwise, we have to prescan the indirection list to
248 * see if there are any double subscripts.
252 foreach(idx, indirection)
254 A_Indices *ai = (A_Indices *) lfirst(idx);
256 if (ai->lidx != NULL)
265 * The type represented by the subscript expression is the element
266 * type if we are fetching a single element, but it is the same as the
267 * array type if we are fetching a slice or storing.
269 if (isSlice || assignFrom != NULL)
270 resultType = arrayType;
272 resultType = elementType;
275 * Transform the subscript expressions.
277 foreach(idx, indirection)
279 A_Indices *ai = (A_Indices *) lfirst(idx);
286 subexpr = transformExpr(pstate, ai->lidx);
287 /* If it's not int4 already, try to coerce */
288 subexpr = CoerceTargetExpr(pstate, subexpr, exprType(subexpr),
291 elog(ERROR, "array index expressions must be integers");
295 /* Make a constant 1 */
296 subexpr = (Node *) makeConst(INT4OID,
300 true, /* pass by value */
304 lowerIndexpr = lappend(lowerIndexpr, subexpr);
306 subexpr = transformExpr(pstate, ai->uidx);
307 /* If it's not int4 already, try to coerce */
308 subexpr = CoerceTargetExpr(pstate, subexpr, exprType(subexpr),
311 elog(ERROR, "array index expressions must be integers");
312 upperIndexpr = lappend(upperIndexpr, subexpr);
316 * If doing an array store, coerce the source value to the right type.
318 if (assignFrom != NULL)
320 Oid typesource = exprType(assignFrom);
321 Oid typeneeded = isSlice ? arrayType : elementType;
323 if (typesource != InvalidOid)
325 if (typesource != typeneeded)
327 /* XXX fixme: need to get the array's atttypmod? */
328 assignFrom = CoerceTargetExpr(pstate, assignFrom,
329 typesource, typeneeded,
331 if (assignFrom == NULL)
332 elog(ERROR, "Array assignment requires type '%s'"
333 " but expression is of type '%s'"
334 "\n\tYou will need to rewrite or cast the expression",
335 format_type_be(typeneeded),
336 format_type_be(typesource));
342 * Ready to build the ArrayRef node.
344 aref = makeNode(ArrayRef);
345 aref->refattrlength = type_struct_array->typlen;
346 aref->refelemlength = type_struct_element->typlen;
347 aref->refelemtype = resultType; /* XXX should save element type
349 aref->refelembyval = type_struct_element->typbyval;
350 aref->refupperindexpr = upperIndexpr;
351 aref->reflowerindexpr = lowerIndexpr;
352 aref->refexpr = arrayBase;
353 aref->refassgnexpr = assignFrom;
355 ReleaseSysCache(type_tuple_array);
356 ReleaseSysCache(type_tuple_element);
364 * Convert a Value node (as returned by the grammar) to a Const node
365 * of the "natural" type for the constant. Note that this routine is
366 * only used when there is no explicit cast for the constant, so we
367 * have to guess what type is wanted.
369 * For string literals we produce a constant of type UNKNOWN ---- whose
370 * representation is the same as text, but it indicates to later type
371 * resolution that we're not sure that it should be considered text.
372 * Explicit "NULL" constants are also typed as UNKNOWN.
374 * For integers and floats we produce int4, float8, or numeric depending
375 * on the value of the number. XXX In some cases it would be nice to take
376 * context into account when determining the type to convert to, but in
377 * other cases we can't delay the type choice. One possibility is to invent
378 * a dummy type "UNKNOWNNUMERIC" that's treated similarly to UNKNOWN;
379 * that would allow us to do the right thing in examples like a simple
380 * INSERT INTO table (numericcolumn) VALUES (1.234), since we wouldn't
381 * have to resolve the unknown type until we knew the destination column
382 * type. On the other hand UNKNOWN has considerable problems of its own.
383 * We would not like "SELECT 1.2 + 3.4" to claim it can't choose a type.
386 make_const(Value *value)
394 switch (nodeTag(value))
397 val = Int32GetDatum(intVal(value));
400 typelen = sizeof(int32);
405 if (fitsInFloat(value))
407 val = Float8GetDatum(floatVal(value));
410 typelen = sizeof(float8);
411 typebyval = false; /* XXX might change someday */
415 val = DirectFunctionCall3(numeric_in,
416 CStringGetDatum(strVal(value)),
417 ObjectIdGetDatum(InvalidOid),
421 typelen = -1; /* variable len */
427 val = DirectFunctionCall1(textin, CStringGetDatum(strVal(value)));
429 typeid = UNKNOWNOID; /* will be coerced later */
430 typelen = -1; /* variable len */
435 val = DirectFunctionCall3(bit_in,
436 CStringGetDatum(strVal(value)),
437 ObjectIdGetDatum(InvalidOid),
445 elog(WARNING, "make_const: unknown type %d", nodeTag(value));
449 /* return a null const */
450 con = makeConst(UNKNOWNOID,
460 con = makeConst(typeid,
465 false, /* not a set */
466 false); /* not coerced */
472 * Decide whether a T_Float value fits in float8, or must be treated as
473 * type "numeric". We check the number of digits and check for overflow/
474 * underflow. (With standard compilation options, Postgres' NUMERIC type
475 * can handle decimal exponents up to 1000, considerably more than most
476 * implementations of float8, so this is a sensible test.)
479 fitsInFloat(Value *value)
486 * Count digits, ignoring leading zeroes (but not trailing zeroes).
487 * DBL_DIG is the maximum safe number of digits for "double".
490 while (*ptr == '+' || *ptr == '-' || *ptr == '0' || *ptr == '.')
495 if (isdigit((unsigned char) *ptr))
497 else if (*ptr == 'e' || *ptr == 'E')
498 break; /* don't count digits in exponent */
500 if (ndigits > DBL_DIG)
504 * Use strtod() to check for overflow/underflow.
507 (void) strtod(strVal(value), &endptr);
508 if (*endptr != '\0' || errno != 0)