1 /*-------------------------------------------------------------------------
4 * various routines that make nodes for query plans
6 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/parser/parse_node.c,v 1.49 2000/11/16 22:30:28 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/parse_coerce.h"
27 #include "parser/parse_expr.h"
28 #include "parser/parse_node.h"
29 #include "parser/parse_oper.h"
30 #include "parser/parse_relation.h"
31 #include "parser/parse_target.h"
32 #include "parser/parse_type.h"
33 #include "utils/builtins.h"
34 #include "utils/varbit.h"
35 #include "utils/lsyscache.h"
36 #include "utils/syscache.h"
38 static bool fitsInFloat(Value *value);
42 * Allocate and initialize a new ParseState.
43 * The CALLER is responsible for freeing the ParseState* returned.
46 make_parsestate(ParseState *parentParseState)
50 pstate = palloc(sizeof(ParseState));
51 MemSet(pstate, 0, sizeof(ParseState));
53 pstate->parentParseState = parentParseState;
54 pstate->p_last_resno = 1;
61 * Ensure argument type match by forcing conversion of constants.
64 make_operand(char *opname,
74 if (target_typeId != orig_typeId)
75 result = coerce_type(NULL, tree, orig_typeId, target_typeId, -1);
81 /* otherwise, this is a NULL value */
82 result = (Node *) makeNullConst(target_typeId);
86 } /* make_operand() */
90 * Operator construction.
92 * Transform operator expression ensuring type compatibility.
93 * This is where some type conversion happens.
96 make_op(char *opname, Node *ltree, Node *rtree)
101 Form_pg_operator opform;
107 ltypeId = (ltree == NULL) ? UNKNOWNOID : exprType(ltree);
108 rtypeId = (rtree == NULL) ? UNKNOWNOID : exprType(rtree);
110 /* right operator? */
113 tup = right_oper(opname, ltypeId);
114 opform = (Form_pg_operator) GETSTRUCT(tup);
115 left = make_operand(opname, ltree, ltypeId, opform->oprleft);
120 else if (ltree == NULL)
122 tup = left_oper(opname, rtypeId);
123 opform = (Form_pg_operator) GETSTRUCT(tup);
124 right = make_operand(opname, rtree, rtypeId, opform->oprright);
128 /* otherwise, binary operator */
131 tup = oper(opname, ltypeId, rtypeId, false);
132 opform = (Form_pg_operator) GETSTRUCT(tup);
133 left = make_operand(opname, ltree, ltypeId, opform->oprleft);
134 right = make_operand(opname, rtree, rtypeId, opform->oprright);
137 newop = makeOper(oprid(tup),/* opno */
138 InvalidOid,/* opid */
139 opform->oprresult); /* operator result type */
141 result = makeNode(Expr);
142 result->typeOid = opform->oprresult;
143 result->opType = OP_EXPR;
144 result->oper = (Node *) newop;
147 result->args = makeList1(right);
149 result->args = makeList1(left);
151 result->args = makeList2(left, right);
153 ReleaseSysCache(tup);
161 * Build a Var node for an attribute identified by RTE and attrno
164 make_var(ParseState *pstate, RangeTblEntry *rte, int attrno)
171 vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
173 if (rte->relid != InvalidOid)
175 /* Plain relation RTE --- get the attribute's type info */
177 Form_pg_attribute att_tup;
179 tp = SearchSysCache(ATTNUM,
180 ObjectIdGetDatum(rte->relid),
181 Int16GetDatum(attrno),
183 /* this shouldn't happen... */
184 if (!HeapTupleIsValid(tp))
185 elog(ERROR, "Relation %s does not have attribute %d",
186 rte->relname, attrno);
187 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
188 vartypeid = att_tup->atttypid;
189 type_mod = att_tup->atttypmod;
194 /* Subselect RTE --- get type info from subselect's tlist */
197 foreach(tlistitem, rte->subquery->targetList)
199 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
201 if (te->resdom->resjunk || te->resdom->resno != attrno)
203 vartypeid = te->resdom->restype;
204 type_mod = te->resdom->restypmod;
207 /* falling off end of list shouldn't happen... */
208 if (tlistitem == NIL)
209 elog(ERROR, "Subquery %s does not have attribute %d",
210 rte->eref->relname, attrno);
213 return makeVar(vnum, attrno, vartypeid, type_mod, sublevels_up);
217 * transformArraySubscripts()
218 * Transform array subscripting. This is used for both
219 * array fetch and array assignment.
221 * In an array fetch, we are given a source array value and we produce an
222 * expression that represents the result of extracting a single array element
225 * In an array assignment, we are given a destination array value plus a
226 * source value that is to be assigned to a single element or a slice of
227 * that array. We produce an expression that represents the new array value
228 * with the source data inserted into the right part of the array.
231 * arrayBase Already-transformed expression for the array as a whole
232 * indirection Untransformed list of subscripts (must not be NIL)
233 * forceSlice If true, treat subscript as array slice in all cases
234 * assignFrom NULL for array fetch, else transformed expression for source.
237 transformArraySubscripts(ParseState *pstate,
246 HeapTuple type_tuple_array,
248 Form_pg_type type_struct_array,
250 bool isSlice = forceSlice;
251 List *upperIndexpr = NIL;
252 List *lowerIndexpr = NIL;
256 /* Get the type tuple for the array */
257 typearray = exprType(arrayBase);
259 type_tuple_array = SearchSysCache(TYPEOID,
260 ObjectIdGetDatum(typearray),
262 if (!HeapTupleIsValid(type_tuple_array))
263 elog(ERROR, "transformArraySubscripts: Cache lookup failed for array type %u",
265 type_struct_array = (Form_pg_type) GETSTRUCT(type_tuple_array);
267 typeelement = type_struct_array->typelem;
268 if (typeelement == InvalidOid)
269 elog(ERROR, "transformArraySubscripts: type %s is not an array",
270 NameStr(type_struct_array->typname));
272 /* Get the type tuple for the array element type */
273 type_tuple_element = SearchSysCache(TYPEOID,
274 ObjectIdGetDatum(typeelement),
276 if (!HeapTupleIsValid(type_tuple_element))
277 elog(ERROR, "transformArraySubscripts: Cache lookup failed for array element type %u",
279 type_struct_element = (Form_pg_type) GETSTRUCT(type_tuple_element);
282 * A list containing only single subscripts refers to a single array
283 * element. If any of the items are double subscripts (lower:upper),
284 * then the subscript expression means an array slice operation. In
285 * this case, we supply a default lower bound of 1 for any items that
286 * contain only a single subscript. The forceSlice parameter forces us
287 * to treat the operation as a slice, even if no lower bounds are
288 * mentioned. Otherwise, we have to prescan the indirection list to
289 * see if there are any double subscripts.
293 foreach(idx, indirection)
295 A_Indices *ai = (A_Indices *) lfirst(idx);
297 if (ai->lidx != NULL)
306 * The type represented by the subscript expression is the element
307 * type if we are fetching a single element, but it is the same as the
308 * array type if we are fetching a slice or storing.
310 if (isSlice || assignFrom != NULL)
311 typeresult = typearray;
313 typeresult = typeelement;
316 * Transform the subscript expressions.
318 foreach(idx, indirection)
320 A_Indices *ai = (A_Indices *) lfirst(idx);
327 subexpr = transformExpr(pstate, ai->lidx, EXPR_COLUMN_FIRST);
328 /* If it's not int4 already, try to coerce */
329 subexpr = CoerceTargetExpr(pstate, subexpr, exprType(subexpr),
332 elog(ERROR, "array index expressions must be integers");
336 /* Make a constant 1 */
337 subexpr = (Node *) makeConst(INT4OID,
341 true, /* pass by value */
345 lowerIndexpr = lappend(lowerIndexpr, subexpr);
347 subexpr = transformExpr(pstate, ai->uidx, EXPR_COLUMN_FIRST);
348 /* If it's not int4 already, try to coerce */
349 subexpr = CoerceTargetExpr(pstate, subexpr, exprType(subexpr),
352 elog(ERROR, "array index expressions must be integers");
353 upperIndexpr = lappend(upperIndexpr, subexpr);
357 * If doing an array store, coerce the source value to the right type.
359 if (assignFrom != NULL)
361 Oid typesource = exprType(assignFrom);
362 Oid typeneeded = isSlice ? typearray : typeelement;
364 if (typesource != InvalidOid)
366 if (typesource != typeneeded)
368 /* XXX fixme: need to get the array's atttypmod? */
369 assignFrom = CoerceTargetExpr(pstate, assignFrom,
370 typesource, typeneeded,
372 if (assignFrom == NULL)
373 elog(ERROR, "Array assignment requires type '%s'"
374 " but expression is of type '%s'"
375 "\n\tYou will need to rewrite or cast the expression",
376 typeidTypeName(typeneeded),
377 typeidTypeName(typesource));
383 * Ready to build the ArrayRef node.
385 aref = makeNode(ArrayRef);
386 aref->refattrlength = type_struct_array->typlen;
387 aref->refelemlength = type_struct_element->typlen;
388 aref->refelemtype = typeresult; /* XXX should save element type
390 aref->refelembyval = type_struct_element->typbyval;
391 aref->refupperindexpr = upperIndexpr;
392 aref->reflowerindexpr = lowerIndexpr;
393 aref->refexpr = arrayBase;
394 aref->refassgnexpr = assignFrom;
396 ReleaseSysCache(type_tuple_array);
397 ReleaseSysCache(type_tuple_element);
405 * Convert a Value node (as returned by the grammar) to a Const node
406 * of the "natural" type for the constant. Note that this routine is
407 * only used when there is no explicit cast for the constant, so we
408 * have to guess what type is wanted.
410 * For string literals we produce a constant of type UNKNOWN ---- whose
411 * representation is the same as text, but it indicates to later type
412 * resolution that we're not sure that it should be considered text.
413 * Explicit "NULL" constants are also typed as UNKNOWN.
415 * For integers and floats we produce int4, float8, or numeric depending
416 * on the value of the number. XXX In some cases it would be nice to take
417 * context into account when determining the type to convert to, but in
418 * other cases we can't delay the type choice. One possibility is to invent
419 * a dummy type "UNKNOWNNUMERIC" that's treated similarly to UNKNOWN;
420 * that would allow us to do the right thing in examples like a simple
421 * INSERT INTO table (numericcolumn) VALUES (1.234), since we wouldn't
422 * have to resolve the unknown type until we knew the destination column
423 * type. On the other hand UNKNOWN has considerable problems of its own.
424 * We would not like "SELECT 1.2 + 3.4" to claim it can't choose a type.
427 make_const(Value *value)
435 switch (nodeTag(value))
438 val = Int32GetDatum(intVal(value));
441 typelen = sizeof(int32);
446 if (fitsInFloat(value))
448 val = Float8GetDatum(floatVal(value));
451 typelen = sizeof(float8);
452 typebyval = false; /* XXX might change someday */
456 val = DirectFunctionCall3(numeric_in,
457 CStringGetDatum(strVal(value)),
458 ObjectIdGetDatum(InvalidOid),
462 typelen = -1; /* variable len */
468 val = DirectFunctionCall1(textin, CStringGetDatum(strVal(value)));
470 typeid = UNKNOWNOID;/* will be coerced later */
471 typelen = -1; /* variable len */
476 val = DirectFunctionCall3(zpbit_in,
477 CStringGetDatum(strVal(value)),
478 ObjectIdGetDatum(InvalidOid),
486 elog(NOTICE, "make_const: unknown type %d", nodeTag(value));
490 /* return a null const */
491 con = makeConst(UNKNOWNOID,
501 con = makeConst(typeid,
506 false, /* not a set */
507 false); /* not coerced */
513 * Decide whether a T_Float value fits in float8, or must be treated as
514 * type "numeric". We check the number of digits and check for overflow/
515 * underflow. (With standard compilation options, Postgres' NUMERIC type
516 * can handle decimal exponents up to 1000, considerably more than most
517 * implementations of float8, so this is a sensible test.)
520 fitsInFloat(Value *value)
527 * Count digits, ignoring leading zeroes (but not trailing zeroes).
528 * DBL_DIG is the maximum safe number of digits for "double".
531 while (*ptr == '+' || *ptr == '-' || *ptr == '0' || *ptr == '.')
536 if (isdigit((int) *ptr))
538 else if (*ptr == 'e' || *ptr == 'E')
539 break; /* don't count digits in exponent */
541 if (ndigits > DBL_DIG)
545 * Use strtod() to check for overflow/underflow.
548 (void) strtod(strVal(value), &endptr);
549 if (*endptr != '\0' || errno != 0)