OSDN Git Service

Give left_oper() and right_oper() noError parameters like oper() (the
[pg-rex/syncrep.git] / src / backend / parser / parse_node.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_node.c
4  *        various routines that make nodes for query plans
5  *
6  * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/parser/parse_node.c,v 1.64 2002/05/01 19:26:07 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <ctype.h>
18 #include <errno.h>
19 #include <float.h>
20
21 #include "access/heapam.h"
22 #include "catalog/pg_operator.h"
23 #include "catalog/pg_type.h"
24 #include "fmgr.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"
38
39 static bool fitsInFloat(Value *value);
40
41
42 /* make_parsestate()
43  * Allocate and initialize a new ParseState.
44  * The CALLER is responsible for freeing the ParseState* returned.
45  */
46 ParseState *
47 make_parsestate(ParseState *parentParseState)
48 {
49         ParseState *pstate;
50
51         pstate = palloc(sizeof(ParseState));
52         MemSet(pstate, 0, sizeof(ParseState));
53
54         pstate->parentParseState = parentParseState;
55         pstate->p_last_resno = 1;
56
57         return pstate;
58 }
59
60
61 /* make_operand()
62  * Ensure argument type match by forcing conversion of constants.
63  */
64 Node *
65 make_operand(Node *tree, Oid orig_typeId, Oid target_typeId)
66 {
67         Node       *result;
68
69         if (tree != NULL)
70         {
71                 /* must coerce? */
72                 if (target_typeId != orig_typeId)
73                         result = coerce_type(NULL, tree, orig_typeId, target_typeId, -1,
74                                                                  false);
75                 else
76                         result = tree;
77         }
78         else
79         {
80                 /* otherwise, this is a NULL value */
81                 result = (Node *) makeNullConst(target_typeId);
82         }
83
84         return result;
85 }       /* make_operand() */
86
87
88 /* make_op()
89  * Operator construction.
90  *
91  * Transform operator expression ensuring type compatibility.
92  * This is where some type conversion happens.
93  */
94 Expr *
95 make_op(List *opname, Node *ltree, Node *rtree)
96 {
97         Oid                     ltypeId,
98                                 rtypeId;
99         Operator        tup;
100         Form_pg_operator opform;
101         Oper       *newop;
102         Node       *left,
103                            *right;
104         Expr       *result;
105
106         ltypeId = (ltree == NULL) ? UNKNOWNOID : exprType(ltree);
107         rtypeId = (rtree == NULL) ? UNKNOWNOID : exprType(rtree);
108
109         /* right operator? */
110         if (rtree == NULL)
111         {
112                 tup = right_oper(opname, ltypeId, false);
113                 opform = (Form_pg_operator) GETSTRUCT(tup);
114                 left = make_operand(ltree, ltypeId, opform->oprleft);
115                 right = NULL;
116         }
117
118         /* left operator? */
119         else if (ltree == NULL)
120         {
121                 tup = left_oper(opname, rtypeId, false);
122                 opform = (Form_pg_operator) GETSTRUCT(tup);
123                 right = make_operand(rtree, rtypeId, opform->oprright);
124                 left = NULL;
125         }
126
127         /* otherwise, binary operator */
128         else
129         {
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);
134         }
135
136         newop = makeOper(oprid(tup),    /* opno */
137                                          InvalidOid,    /* opid */
138                                          opform->oprresult);            /* operator result type */
139
140         result = makeNode(Expr);
141         result->typeOid = opform->oprresult;
142         result->opType = OP_EXPR;
143         result->oper = (Node *) newop;
144
145         if (!left)
146                 result->args = makeList1(right);
147         else if (!right)
148                 result->args = makeList1(left);
149         else
150                 result->args = makeList2(left, right);
151
152         ReleaseSysCache(tup);
153
154         return result;
155 }       /* make_op() */
156
157
158 /*
159  * make_var
160  *              Build a Var node for an attribute identified by RTE and attrno
161  */
162 Var *
163 make_var(ParseState *pstate, RangeTblEntry *rte, int attrno)
164 {
165         int                     vnum,
166                                 sublevels_up;
167         Oid                     vartypeid;
168         int32           type_mod;
169
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);
173 }
174
175 /*
176  * transformArraySubscripts()
177  *              Transform array subscripting.  This is used for both
178  *              array fetch and array assignment.
179  *
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
182  * or an array slice.
183  *
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.
188  *
189  * pstate               Parse state
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.
196  */
197 ArrayRef *
198 transformArraySubscripts(ParseState *pstate,
199                                                  Node *arrayBase,
200                                                  Oid arrayType,
201                                                  List *indirection,
202                                                  bool forceSlice,
203                                                  Node *assignFrom)
204 {
205         Oid                     elementType,
206                                 resultType;
207         HeapTuple       type_tuple_array,
208                                 type_tuple_element;
209         Form_pg_type type_struct_array,
210                                 type_struct_element;
211         bool            isSlice = forceSlice;
212         List       *upperIndexpr = NIL;
213         List       *lowerIndexpr = NIL;
214         List       *idx;
215         ArrayRef   *aref;
216
217         /* Get the type tuple for the array */
218         type_tuple_array = SearchSysCache(TYPEOID,
219                                                                           ObjectIdGetDatum(arrayType),
220                                                                           0, 0, 0);
221         if (!HeapTupleIsValid(type_tuple_array))
222                 elog(ERROR, "transformArraySubscripts: Cache lookup failed for array type %u",
223                          arrayType);
224         type_struct_array = (Form_pg_type) GETSTRUCT(type_tuple_array);
225
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));
230
231         /* Get the type tuple for the array element type */
232         type_tuple_element = SearchSysCache(TYPEOID,
233                                                                                 ObjectIdGetDatum(elementType),
234                                                                                 0, 0, 0);
235         if (!HeapTupleIsValid(type_tuple_element))
236                 elog(ERROR, "transformArraySubscripts: Cache lookup failed for array element type %u",
237                          elementType);
238         type_struct_element = (Form_pg_type) GETSTRUCT(type_tuple_element);
239
240         /*
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.
249          */
250         if (!isSlice)
251         {
252                 foreach(idx, indirection)
253                 {
254                         A_Indices  *ai = (A_Indices *) lfirst(idx);
255
256                         if (ai->lidx != NULL)
257                         {
258                                 isSlice = true;
259                                 break;
260                         }
261                 }
262         }
263
264         /*
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.
268          */
269         if (isSlice || assignFrom != NULL)
270                 resultType = arrayType;
271         else
272                 resultType = elementType;
273
274         /*
275          * Transform the subscript expressions.
276          */
277         foreach(idx, indirection)
278         {
279                 A_Indices  *ai = (A_Indices *) lfirst(idx);
280                 Node       *subexpr;
281
282                 if (isSlice)
283                 {
284                         if (ai->lidx)
285                         {
286                                 subexpr = transformExpr(pstate, ai->lidx);
287                                 /* If it's not int4 already, try to coerce */
288                                 subexpr = CoerceTargetExpr(pstate, subexpr, exprType(subexpr),
289                                                                                    INT4OID, -1, false);
290                                 if (subexpr == NULL)
291                                         elog(ERROR, "array index expressions must be integers");
292                         }
293                         else
294                         {
295                                 /* Make a constant 1 */
296                                 subexpr = (Node *) makeConst(INT4OID,
297                                                                                          sizeof(int32),
298                                                                                          Int32GetDatum(1),
299                                                                                          false,
300                                                                                          true,          /* pass by value */
301                                                                                          false,
302                                                                                          false);
303                         }
304                         lowerIndexpr = lappend(lowerIndexpr, subexpr);
305                 }
306                 subexpr = transformExpr(pstate, ai->uidx);
307                 /* If it's not int4 already, try to coerce */
308                 subexpr = CoerceTargetExpr(pstate, subexpr, exprType(subexpr),
309                                                                    INT4OID, -1, false);
310                 if (subexpr == NULL)
311                         elog(ERROR, "array index expressions must be integers");
312                 upperIndexpr = lappend(upperIndexpr, subexpr);
313         }
314
315         /*
316          * If doing an array store, coerce the source value to the right type.
317          */
318         if (assignFrom != NULL)
319         {
320                 Oid                     typesource = exprType(assignFrom);
321                 Oid                     typeneeded = isSlice ? arrayType : elementType;
322
323                 if (typesource != InvalidOid)
324                 {
325                         if (typesource != typeneeded)
326                         {
327                                 /* XXX fixme: need to get the array's atttypmod? */
328                                 assignFrom = CoerceTargetExpr(pstate, assignFrom,
329                                                                                           typesource, typeneeded,
330                                                                                           -1, false);
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));
337                         }
338                 }
339         }
340
341         /*
342          * Ready to build the ArrayRef node.
343          */
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
348                                                                                  * too */
349         aref->refelembyval = type_struct_element->typbyval;
350         aref->refupperindexpr = upperIndexpr;
351         aref->reflowerindexpr = lowerIndexpr;
352         aref->refexpr = arrayBase;
353         aref->refassgnexpr = assignFrom;
354
355         ReleaseSysCache(type_tuple_array);
356         ReleaseSysCache(type_tuple_element);
357
358         return aref;
359 }
360
361 /*
362  * make_const
363  *
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.
368  *
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.
373  *
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.
384  */
385 Const *
386 make_const(Value *value)
387 {
388         Datum           val;
389         Oid                     typeid;
390         int                     typelen;
391         bool            typebyval;
392         Const      *con;
393
394         switch (nodeTag(value))
395         {
396                 case T_Integer:
397                         val = Int32GetDatum(intVal(value));
398
399                         typeid = INT4OID;
400                         typelen = sizeof(int32);
401                         typebyval = true;
402                         break;
403
404                 case T_Float:
405                         if (fitsInFloat(value))
406                         {
407                                 val = Float8GetDatum(floatVal(value));
408
409                                 typeid = FLOAT8OID;
410                                 typelen = sizeof(float8);
411                                 typebyval = false;              /* XXX might change someday */
412                         }
413                         else
414                         {
415                                 val = DirectFunctionCall3(numeric_in,
416                                                                                   CStringGetDatum(strVal(value)),
417                                                                                   ObjectIdGetDatum(InvalidOid),
418                                                                                   Int32GetDatum(-1));
419
420                                 typeid = NUMERICOID;
421                                 typelen = -1;   /* variable len */
422                                 typebyval = false;
423                         }
424                         break;
425
426                 case T_String:
427                         val = DirectFunctionCall1(unknownin,
428                                                                           CStringGetDatum(strVal(value)));
429
430                         typeid = UNKNOWNOID;    /* will be coerced later */
431                         typelen = -1;           /* variable len */
432                         typebyval = false;
433                         break;
434
435                 case T_BitString:
436                         val = DirectFunctionCall3(bit_in,
437                                                                           CStringGetDatum(strVal(value)),
438                                                                           ObjectIdGetDatum(InvalidOid),
439                                                                           Int32GetDatum(-1));
440                         typeid = BITOID;
441                         typelen = -1;
442                         typebyval = false;
443                         break;
444
445                 default:
446                         elog(WARNING, "make_const: unknown type %d", nodeTag(value));
447                         /* FALLTHROUGH */
448
449                 case T_Null:
450                         /* return a null const */
451                         con = makeConst(UNKNOWNOID,
452                                                         -1,
453                                                         (Datum) NULL,
454                                                         true,
455                                                         false,
456                                                         false,
457                                                         false);
458                         return con;
459         }
460
461         con = makeConst(typeid,
462                                         typelen,
463                                         val,
464                                         false,
465                                         typebyval,
466                                         false,          /* not a set */
467                                         false);         /* not coerced */
468
469         return con;
470 }
471
472 /*
473  * Decide whether a T_Float value fits in float8, or must be treated as
474  * type "numeric".      We check the number of digits and check for overflow/
475  * underflow.  (With standard compilation options, Postgres' NUMERIC type
476  * can handle decimal exponents up to 1000, considerably more than most
477  * implementations of float8, so this is a sensible test.)
478  */
479 static bool
480 fitsInFloat(Value *value)
481 {
482         const char *ptr;
483         int                     ndigits;
484         char       *endptr;
485
486         /*
487          * Count digits, ignoring leading zeroes (but not trailing zeroes).
488          * DBL_DIG is the maximum safe number of digits for "double".
489          */
490         ptr = strVal(value);
491         while (*ptr == '+' || *ptr == '-' || *ptr == '0' || *ptr == '.')
492                 ptr++;
493         ndigits = 0;
494         for (; *ptr; ptr++)
495         {
496                 if (isdigit((unsigned char) *ptr))
497                         ndigits++;
498                 else if (*ptr == 'e' || *ptr == 'E')
499                         break;                          /* don't count digits in exponent */
500         }
501         if (ndigits > DBL_DIG)
502                 return false;
503
504         /*
505          * Use strtod() to check for overflow/underflow.
506          */
507         errno = 0;
508         (void) strtod(strVal(value), &endptr);
509         if (*endptr != '\0' || errno != 0)
510                 return false;
511
512         return true;
513 }