]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_node.c
Change SearchSysCache coding conventions so that a reference count is
[postgresql] / 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-2000, PostgreSQL, Inc
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.49 2000/11/16 22:30:28 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include <ctype.h>
16 #include <errno.h>
17 #include <float.h>
18
19 #include "postgres.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/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"
37
38 static bool fitsInFloat(Value *value);
39
40
41 /* make_parsestate()
42  * Allocate and initialize a new ParseState.
43  * The CALLER is responsible for freeing the ParseState* returned.
44  */
45 ParseState *
46 make_parsestate(ParseState *parentParseState)
47 {
48         ParseState *pstate;
49
50         pstate = palloc(sizeof(ParseState));
51         MemSet(pstate, 0, sizeof(ParseState));
52
53         pstate->parentParseState = parentParseState;
54         pstate->p_last_resno = 1;
55
56         return pstate;
57 }
58
59
60 /* make_operand()
61  * Ensure argument type match by forcing conversion of constants.
62  */
63 Node *
64 make_operand(char *opname,
65                          Node *tree,
66                          Oid orig_typeId,
67                          Oid target_typeId)
68 {
69         Node       *result;
70
71         if (tree != NULL)
72         {
73                 /* must coerce? */
74                 if (target_typeId != orig_typeId)
75                         result = coerce_type(NULL, tree, orig_typeId, target_typeId, -1);
76                 else
77                         result = tree;
78         }
79         else
80         {
81                 /* otherwise, this is a NULL value */
82                 result = (Node *) makeNullConst(target_typeId);
83         }
84
85         return result;
86 }       /* make_operand() */
87
88
89 /* make_op()
90  * Operator construction.
91  *
92  * Transform operator expression ensuring type compatibility.
93  * This is where some type conversion happens.
94  */
95 Expr *
96 make_op(char *opname, Node *ltree, Node *rtree)
97 {
98         Oid                     ltypeId,
99                                 rtypeId;
100         Operator        tup;
101         Form_pg_operator opform;
102         Oper       *newop;
103         Node       *left,
104                            *right;
105         Expr       *result;
106
107         ltypeId = (ltree == NULL) ? UNKNOWNOID : exprType(ltree);
108         rtypeId = (rtree == NULL) ? UNKNOWNOID : exprType(rtree);
109
110         /* right operator? */
111         if (rtree == NULL)
112         {
113                 tup = right_oper(opname, ltypeId);
114                 opform = (Form_pg_operator) GETSTRUCT(tup);
115                 left = make_operand(opname, ltree, ltypeId, opform->oprleft);
116                 right = NULL;
117         }
118
119         /* left operator? */
120         else if (ltree == NULL)
121         {
122                 tup = left_oper(opname, rtypeId);
123                 opform = (Form_pg_operator) GETSTRUCT(tup);
124                 right = make_operand(opname, rtree, rtypeId, opform->oprright);
125                 left = NULL;
126         }
127
128         /* otherwise, binary operator */
129         else
130         {
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);
135         }
136
137         newop = makeOper(oprid(tup),/* opno */
138                                          InvalidOid,/* opid */
139                                          opform->oprresult); /* operator result type */
140
141         result = makeNode(Expr);
142         result->typeOid = opform->oprresult;
143         result->opType = OP_EXPR;
144         result->oper = (Node *) newop;
145
146         if (!left)
147                 result->args = makeList1(right);
148         else if (!right)
149                 result->args = makeList1(left);
150         else
151                 result->args = makeList2(left, right);
152
153         ReleaseSysCache(tup);
154
155         return result;
156 }       /* make_op() */
157
158
159 /*
160  * make_var
161  *              Build a Var node for an attribute identified by RTE and attrno
162  */
163 Var *
164 make_var(ParseState *pstate, RangeTblEntry *rte, int attrno)
165 {
166         int                     vnum,
167                                 sublevels_up;
168         Oid                     vartypeid = 0;
169         int32           type_mod = 0;
170
171         vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
172
173         if (rte->relid != InvalidOid)
174         {
175                 /* Plain relation RTE --- get the attribute's type info */
176                 HeapTuple       tp;
177                 Form_pg_attribute att_tup;
178
179                 tp = SearchSysCache(ATTNUM,
180                                                         ObjectIdGetDatum(rte->relid),
181                                                         Int16GetDatum(attrno),
182                                                         0, 0);
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;
190                 ReleaseSysCache(tp);
191         }
192         else
193         {
194                 /* Subselect RTE --- get type info from subselect's tlist */
195                 List       *tlistitem;
196
197                 foreach(tlistitem, rte->subquery->targetList)
198                 {
199                         TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
200
201                         if (te->resdom->resjunk || te->resdom->resno != attrno)
202                                 continue;
203                         vartypeid = te->resdom->restype;
204                         type_mod = te->resdom->restypmod;
205                         break;
206                 }
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);
211         }
212
213         return makeVar(vnum, attrno, vartypeid, type_mod, sublevels_up);
214 }
215
216 /*
217  * transformArraySubscripts()
218  *              Transform array subscripting.  This is used for both
219  *              array fetch and array assignment.
220  *
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
223  * or an array slice.
224  *
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.
229  *
230  * pstate               Parse state
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.
235  */
236 ArrayRef   *
237 transformArraySubscripts(ParseState *pstate,
238                                                  Node *arrayBase,
239                                                  List *indirection,
240                                                  bool forceSlice,
241                                                  Node *assignFrom)
242 {
243         Oid                     typearray,
244                                 typeelement,
245                                 typeresult;
246         HeapTuple       type_tuple_array,
247                                 type_tuple_element;
248         Form_pg_type type_struct_array,
249                                 type_struct_element;
250         bool            isSlice = forceSlice;
251         List       *upperIndexpr = NIL;
252         List       *lowerIndexpr = NIL;
253         List       *idx;
254         ArrayRef   *aref;
255
256         /* Get the type tuple for the array */
257         typearray = exprType(arrayBase);
258
259         type_tuple_array = SearchSysCache(TYPEOID,
260                                                                           ObjectIdGetDatum(typearray),
261                                                                           0, 0, 0);
262         if (!HeapTupleIsValid(type_tuple_array))
263                 elog(ERROR, "transformArraySubscripts: Cache lookup failed for array type %u",
264                          typearray);
265         type_struct_array = (Form_pg_type) GETSTRUCT(type_tuple_array);
266
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));
271
272         /* Get the type tuple for the array element type */
273         type_tuple_element = SearchSysCache(TYPEOID,
274                                                                                 ObjectIdGetDatum(typeelement),
275                                                                                 0, 0, 0);
276         if (!HeapTupleIsValid(type_tuple_element))
277                 elog(ERROR, "transformArraySubscripts: Cache lookup failed for array element type %u",
278                          typeelement);
279         type_struct_element = (Form_pg_type) GETSTRUCT(type_tuple_element);
280
281         /*
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.
290          */
291         if (!isSlice)
292         {
293                 foreach(idx, indirection)
294                 {
295                         A_Indices  *ai = (A_Indices *) lfirst(idx);
296
297                         if (ai->lidx != NULL)
298                         {
299                                 isSlice = true;
300                                 break;
301                         }
302                 }
303         }
304
305         /*
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.
309          */
310         if (isSlice || assignFrom != NULL)
311                 typeresult = typearray;
312         else
313                 typeresult = typeelement;
314
315         /*
316          * Transform the subscript expressions.
317          */
318         foreach(idx, indirection)
319         {
320                 A_Indices  *ai = (A_Indices *) lfirst(idx);
321                 Node       *subexpr;
322
323                 if (isSlice)
324                 {
325                         if (ai->lidx)
326                         {
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),
330                                                                                    INT4OID, -1);
331                                 if (subexpr == NULL)
332                                         elog(ERROR, "array index expressions must be integers");
333                         }
334                         else
335                         {
336                                 /* Make a constant 1 */
337                                 subexpr = (Node *) makeConst(INT4OID,
338                                                                                          sizeof(int32),
339                                                                                          Int32GetDatum(1),
340                                                                                          false,
341                                                                                          true,          /* pass by value */
342                                                                                          false,
343                                                                                          false);
344                         }
345                         lowerIndexpr = lappend(lowerIndexpr, subexpr);
346                 }
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),
350                                                                    INT4OID, -1);
351                 if (subexpr == NULL)
352                         elog(ERROR, "array index expressions must be integers");
353                 upperIndexpr = lappend(upperIndexpr, subexpr);
354         }
355
356         /*
357          * If doing an array store, coerce the source value to the right type.
358          */
359         if (assignFrom != NULL)
360         {
361                 Oid                     typesource = exprType(assignFrom);
362                 Oid                     typeneeded = isSlice ? typearray : typeelement;
363
364                 if (typesource != InvalidOid)
365                 {
366                         if (typesource != typeneeded)
367                         {
368                                 /* XXX fixme: need to get the array's atttypmod? */
369                                 assignFrom = CoerceTargetExpr(pstate, assignFrom,
370                                                                                           typesource, typeneeded,
371                                                                                           -1);
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));
378                         }
379                 }
380         }
381
382         /*
383          * Ready to build the ArrayRef node.
384          */
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
389                                                                                  * too */
390         aref->refelembyval = type_struct_element->typbyval;
391         aref->refupperindexpr = upperIndexpr;
392         aref->reflowerindexpr = lowerIndexpr;
393         aref->refexpr = arrayBase;
394         aref->refassgnexpr = assignFrom;
395
396         ReleaseSysCache(type_tuple_array);
397         ReleaseSysCache(type_tuple_element);
398
399         return aref;
400 }
401
402 /*
403  * make_const
404  *
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.
409  *
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.
414  *
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.
425  */
426 Const *
427 make_const(Value *value)
428 {
429         Datum           val;
430         Oid                     typeid;
431         int                     typelen;
432         bool            typebyval;
433         Const      *con;
434
435         switch (nodeTag(value))
436         {
437                 case T_Integer:
438                         val = Int32GetDatum(intVal(value));
439
440                         typeid = INT4OID;
441                         typelen = sizeof(int32);
442                         typebyval = true;
443                         break;
444
445                 case T_Float:
446                         if (fitsInFloat(value))
447                         {
448                                 val = Float8GetDatum(floatVal(value));
449
450                                 typeid = FLOAT8OID;
451                                 typelen = sizeof(float8);
452                                 typebyval = false; /* XXX might change someday */
453                         }
454                         else
455                         {
456                                 val = DirectFunctionCall3(numeric_in,
457                                                                                   CStringGetDatum(strVal(value)),
458                                                                                   ObjectIdGetDatum(InvalidOid),
459                                                                                   Int32GetDatum(-1));
460
461                                 typeid = NUMERICOID;
462                                 typelen = -1;   /* variable len */
463                                 typebyval = false;
464                         }
465                         break;
466
467                 case T_String:
468                         val = DirectFunctionCall1(textin, CStringGetDatum(strVal(value)));
469
470                         typeid = UNKNOWNOID;/* will be coerced later */
471                         typelen = -1;           /* variable len */
472                         typebyval = false;
473                         break;
474
475                 case T_BitString:
476                         val = DirectFunctionCall3(zpbit_in,
477                                                                           CStringGetDatum(strVal(value)),
478                                                                           ObjectIdGetDatum(InvalidOid),
479                                                                           Int32GetDatum(-1));
480                         typeid = ZPBITOID;
481                         typelen = -1;
482                         typebyval = false;
483                         break;
484
485                 default:
486                         elog(NOTICE, "make_const: unknown type %d", nodeTag(value));
487                         /* FALLTHROUGH */
488
489                 case T_Null:
490                         /* return a null const */
491                         con = makeConst(UNKNOWNOID,
492                                                         -1,
493                                                         (Datum) NULL,
494                                                         true,
495                                                         false,
496                                                         false,
497                                                         false);
498                         return con;
499         }
500
501         con = makeConst(typeid,
502                                         typelen,
503                                         val,
504                                         false,
505                                         typebyval,
506                                         false,          /* not a set */
507                                         false);         /* not coerced */
508
509         return con;
510 }
511
512 /*
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.)
518  */
519 static bool
520 fitsInFloat(Value *value)
521 {
522         const char *ptr;
523         int                     ndigits;
524         char       *endptr;
525
526         /*
527          * Count digits, ignoring leading zeroes (but not trailing zeroes).
528          * DBL_DIG is the maximum safe number of digits for "double".
529          */
530         ptr = strVal(value);
531         while (*ptr == '+' || *ptr == '-' || *ptr == '0' || *ptr == '.')
532                 ptr++;
533         ndigits = 0;
534         for (; *ptr; ptr++)
535         {
536                 if (isdigit((int) *ptr))
537                         ndigits++;
538                 else if (*ptr == 'e' || *ptr == 'E')
539                         break;                          /* don't count digits in exponent */
540         }
541         if (ndigits > DBL_DIG)
542                 return false;
543
544         /*
545          * Use strtod() to check for overflow/underflow.
546          */
547         errno = 0;
548         (void) strtod(strVal(value), &endptr);
549         if (*endptr != '\0' || errno != 0)
550                 return false;
551
552         return true;
553 }