]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_node.c
8cad187550c834ba96b79f3251971d5e55d197ea
[postgresql] / src / backend / parser / parse_node.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_node.c
4  *        various routines that make nodes for querytrees
5  *
6  * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/parser/parse_node.c,v 1.95 2006/10/04 00:29:56 momjian Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
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"
28
29
30 /* make_parsestate()
31  * Allocate and initialize a new ParseState.
32  * The CALLER is responsible for freeing the ParseState* returned.
33  */
34 ParseState *
35 make_parsestate(ParseState *parentParseState)
36 {
37         ParseState *pstate;
38
39         pstate = palloc0(sizeof(ParseState));
40
41         pstate->parentParseState = parentParseState;
42
43         /* Fill in fields that don't start at null/false/zero */
44         pstate->p_next_resno = 1;
45
46         if (parentParseState)
47         {
48                 pstate->p_sourcetext = parentParseState->p_sourcetext;
49                 pstate->p_variableparams = parentParseState->p_variableparams;
50         }
51
52         return pstate;
53 }
54
55
56 /*
57  * parser_errposition
58  *              Report a parse-analysis-time cursor position, if possible.
59  *
60  * This is expected to be used within an ereport() call.  The return value
61  * is a dummy (always 0, in fact).
62  *
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.)
68  */
69 int
70 parser_errposition(ParseState *pstate, int location)
71 {
72         int                     pos;
73
74         /* No-op if location was not provided */
75         if (location < 0)
76                 return 0;
77         /* Can't do anything if source text is not available */
78         if (pstate == NULL || pstate->p_sourcetext == NULL)
79                 return 0;
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);
84 }
85
86
87 /*
88  * make_var
89  *              Build a Var node for an attribute identified by RTE and attrno
90  */
91 Var *
92 make_var(ParseState *pstate, RangeTblEntry *rte, int attrno)
93 {
94         int                     vnum,
95                                 sublevels_up;
96         Oid                     vartypeid;
97         int32           type_mod;
98
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);
102 }
103
104 /*
105  * transformArrayType()
106  *              Get the element type of an array type in preparation for subscripting
107  */
108 Oid
109 transformArrayType(Oid arrayType)
110 {
111         Oid                     elementType;
112         HeapTuple       type_tuple_array;
113         Form_pg_type type_struct_array;
114
115         /* Get the type tuple for the array */
116         type_tuple_array = SearchSysCache(TYPEOID,
117                                                                           ObjectIdGetDatum(arrayType),
118                                                                           0, 0, 0);
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);
122
123         /* needn't check typisdefined since this will fail anyway */
124
125         elementType = type_struct_array->typelem;
126         if (elementType == InvalidOid)
127                 ereport(ERROR,
128                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
129                                  errmsg("cannot subscript type %s because it is not an array",
130                                                 format_type_be(arrayType))));
131
132         ReleaseSysCache(type_tuple_array);
133
134         return elementType;
135 }
136
137 /*
138  * transformArraySubscripts()
139  *              Transform array subscripting.  This is used for both
140  *              array fetch and array assignment.
141  *
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
144  * or an array slice.
145  *
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.
150  *
151  * pstate               Parse state
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.
159  */
160 ArrayRef *
161 transformArraySubscripts(ParseState *pstate,
162                                                  Node *arrayBase,
163                                                  Oid arrayType,
164                                                  Oid elementType,
165                                                  int32 elementTypMod,
166                                                  List *indirection,
167                                                  Node *assignFrom)
168 {
169         Oid                     resultType;
170         bool            isSlice = false;
171         List       *upperIndexpr = NIL;
172         List       *lowerIndexpr = NIL;
173         ListCell   *idx;
174         ArrayRef   *aref;
175
176         /* Caller may or may not have bothered to determine elementType */
177         if (!OidIsValid(elementType))
178                 elementType = transformArrayType(arrayType);
179
180         /*
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.
187          */
188         foreach(idx, indirection)
189         {
190                 A_Indices  *ai = (A_Indices *) lfirst(idx);
191
192                 if (ai->lidx != NULL)
193                 {
194                         isSlice = true;
195                         break;
196                 }
197         }
198
199         /*
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.
203          */
204         if (isSlice || assignFrom != NULL)
205                 resultType = arrayType;
206         else
207                 resultType = elementType;
208
209         /*
210          * Transform the subscript expressions.
211          */
212         foreach(idx, indirection)
213         {
214                 A_Indices  *ai = (A_Indices *) lfirst(idx);
215                 Node       *subexpr;
216
217                 Assert(IsA(ai, A_Indices));
218                 if (isSlice)
219                 {
220                         if (ai->lidx)
221                         {
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),
226                                                                                                 INT4OID, -1,
227                                                                                                 COERCION_ASSIGNMENT,
228                                                                                                 COERCE_IMPLICIT_CAST);
229                                 if (subexpr == NULL)
230                                         ereport(ERROR,
231                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
232                                                   errmsg("array subscript must have type integer")));
233                         }
234                         else
235                         {
236                                 /* Make a constant 1 */
237                                 subexpr = (Node *) makeConst(INT4OID,
238                                                                                          sizeof(int32),
239                                                                                          Int32GetDatum(1),
240                                                                                          false,
241                                                                                          true);         /* pass by value */
242                         }
243                         lowerIndexpr = lappend(lowerIndexpr, subexpr);
244                 }
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),
249                                                                                 INT4OID, -1,
250                                                                                 COERCION_ASSIGNMENT,
251                                                                                 COERCE_IMPLICIT_CAST);
252                 if (subexpr == NULL)
253                         ereport(ERROR,
254                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
255                                          errmsg("array subscript must have type integer")));
256                 upperIndexpr = lappend(upperIndexpr, subexpr);
257         }
258
259         /*
260          * If doing an array store, coerce the source value to the right type.
261          * (This should agree with the coercion done by transformAssignedExpr.)
262          */
263         if (assignFrom != NULL)
264         {
265                 Oid                     typesource = exprType(assignFrom);
266                 Oid                     typeneeded = isSlice ? arrayType : elementType;
267
268                 assignFrom = coerce_to_target_type(pstate,
269                                                                                    assignFrom, typesource,
270                                                                                    typeneeded, elementTypMod,
271                                                                                    COERCION_ASSIGNMENT,
272                                                                                    COERCE_IMPLICIT_CAST);
273                 if (assignFrom == NULL)
274                         ereport(ERROR,
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.")));
281         }
282
283         /*
284          * Ready to build the ArrayRef node.
285          */
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;
294
295         return aref;
296 }
297
298 /*
299  * make_const
300  *
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.
305  *
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.
310  *
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.
315  */
316 Const *
317 make_const(Value *value)
318 {
319         Datum           val;
320         int64           val64;
321         Oid                     typeid;
322         int                     typelen;
323         bool            typebyval;
324         Const      *con;
325
326         switch (nodeTag(value))
327         {
328                 case T_Integer:
329                         val = Int32GetDatum(intVal(value));
330
331                         typeid = INT4OID;
332                         typelen = sizeof(int32);
333                         typebyval = true;
334                         break;
335
336                 case T_Float:
337                         /* could be an oversize integer as well as a float ... */
338                         if (scanint8(strVal(value), true, &val64))
339                         {
340                                 /*
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.
343                                  */
344                                 int32           val32 = (int32) val64;
345
346                                 if (val64 == (int64) val32)
347                                 {
348                                         val = Int32GetDatum(val32);
349
350                                         typeid = INT4OID;
351                                         typelen = sizeof(int32);
352                                         typebyval = true;
353                                 }
354                                 else
355                                 {
356                                         val = Int64GetDatum(val64);
357
358                                         typeid = INT8OID;
359                                         typelen = sizeof(int64);
360                                         typebyval = false;      /* XXX might change someday */
361                                 }
362                         }
363                         else
364                         {
365                                 val = DirectFunctionCall3(numeric_in,
366                                                                                   CStringGetDatum(strVal(value)),
367                                                                                   ObjectIdGetDatum(InvalidOid),
368                                                                                   Int32GetDatum(-1));
369
370                                 typeid = NUMERICOID;
371                                 typelen = -1;   /* variable len */
372                                 typebyval = false;
373                         }
374                         break;
375
376                 case T_String:
377
378                         /*
379                          * We assume here that UNKNOWN's internal representation is the
380                          * same as CSTRING
381                          */
382                         val = CStringGetDatum(strVal(value));
383
384                         typeid = UNKNOWNOID;    /* will be coerced later */
385                         typelen = -2;           /* cstring-style varwidth type */
386                         typebyval = false;
387                         break;
388
389                 case T_BitString:
390                         val = DirectFunctionCall3(bit_in,
391                                                                           CStringGetDatum(strVal(value)),
392                                                                           ObjectIdGetDatum(InvalidOid),
393                                                                           Int32GetDatum(-1));
394                         typeid = BITOID;
395                         typelen = -1;
396                         typebyval = false;
397                         break;
398
399                 case T_Null:
400                         /* return a null const */
401                         con = makeConst(UNKNOWNOID,
402                                                         -2,
403                                                         (Datum) 0,
404                                                         true,
405                                                         false);
406                         return con;
407
408                 default:
409                         elog(ERROR, "unrecognized node type: %d", (int) nodeTag(value));
410                         return NULL;            /* keep compiler quiet */
411         }
412
413         con = makeConst(typeid,
414                                         typelen,
415                                         val,
416                                         false,
417                                         typebyval);
418
419         return con;
420 }