]> granicus.if.org Git - postgresql/blob - src/include/nodes/primnodes.h
Fix array coercion expressions to ensure that the correct volatility is
[postgresql] / src / include / nodes / primnodes.h
1 /*-------------------------------------------------------------------------
2  *
3  * primnodes.h
4  *        Definitions for "primitive" node types, those that are used in more
5  *        than one of the parse/plan/execute stages of the query pipeline.
6  *        Currently, these are mostly nodes for executable expressions
7  *        and join trees.
8  *
9  *
10  * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
11  * Portions Copyright (c) 1994, Regents of the University of California
12  *
13  * $PostgreSQL: pgsql/src/include/nodes/primnodes.h,v 1.129 2007/03/27 23:21:12 tgl Exp $
14  *
15  *-------------------------------------------------------------------------
16  */
17 #ifndef PRIMNODES_H
18 #define PRIMNODES_H
19
20 #include "access/attnum.h"
21 #include "nodes/pg_list.h"
22
23
24 /* ----------------------------------------------------------------
25  *                                              node definitions
26  * ----------------------------------------------------------------
27  */
28
29 /*
30  * Alias -
31  *        specifies an alias for a range variable; the alias might also
32  *        specify renaming of columns within the table.
33  *
34  * Note: colnames is a list of Value nodes (always strings).  In Alias structs
35  * associated with RTEs, there may be entries corresponding to dropped
36  * columns; these are normally empty strings ("").      See parsenodes.h for info.
37  */
38 typedef struct Alias
39 {
40         NodeTag         type;
41         char       *aliasname;          /* aliased rel name (never qualified) */
42         List       *colnames;           /* optional list of column aliases */
43 } Alias;
44
45 typedef enum InhOption
46 {
47         INH_NO,                                         /* Do NOT scan child tables */
48         INH_YES,                                        /* DO scan child tables */
49         INH_DEFAULT                                     /* Use current SQL_inheritance option */
50 } InhOption;
51
52 /* What to do at commit time for temporary relations */
53 typedef enum OnCommitAction
54 {
55         ONCOMMIT_NOOP,                          /* No ON COMMIT clause (do nothing) */
56         ONCOMMIT_PRESERVE_ROWS,         /* ON COMMIT PRESERVE ROWS (do nothing) */
57         ONCOMMIT_DELETE_ROWS,           /* ON COMMIT DELETE ROWS */
58         ONCOMMIT_DROP                           /* ON COMMIT DROP */
59 } OnCommitAction;
60
61 /*
62  * RangeVar - range variable, used in FROM clauses
63  *
64  * Also used to represent table names in utility statements; there, the alias
65  * field is not used, and inhOpt shows whether to apply the operation
66  * recursively to child tables.  In some contexts it is also useful to carry
67  * a TEMP table indication here.
68  */
69 typedef struct RangeVar
70 {
71         NodeTag         type;
72         char       *catalogname;        /* the catalog (database) name, or NULL */
73         char       *schemaname;         /* the schema name, or NULL */
74         char       *relname;            /* the relation/sequence name */
75         InhOption       inhOpt;                 /* expand rel by inheritance? recursively act
76                                                                  * on children? */
77         bool            istemp;                 /* is this a temp relation/sequence? */
78         Alias      *alias;                      /* table alias & optional column aliases */
79 } RangeVar;
80
81 /*
82  * IntoClause - target information for SELECT INTO and CREATE TABLE AS
83  */
84 typedef struct IntoClause
85 {
86         NodeTag         type;
87
88         RangeVar   *rel;                        /* target relation name */
89         List       *colNames;           /* column names to assign, or NIL */
90         List       *options;            /* options from WITH clause */
91         OnCommitAction onCommit;        /* what do we do at COMMIT? */
92         char       *tableSpaceName;     /* table space to use, or NULL */
93 } IntoClause;
94
95
96 /* ----------------------------------------------------------------
97  *                                      node types for executable expressions
98  * ----------------------------------------------------------------
99  */
100
101 /*
102  * Expr - generic superclass for executable-expression nodes
103  *
104  * All node types that are used in executable expression trees should derive
105  * from Expr (that is, have Expr as their first field).  Since Expr only
106  * contains NodeTag, this is a formality, but it is an easy form of
107  * documentation.  See also the ExprState node types in execnodes.h.
108  */
109 typedef struct Expr
110 {
111         NodeTag         type;
112 } Expr;
113
114 /*
115  * Var - expression node representing a variable (ie, a table column)
116  *
117  * Note: during parsing/planning, varnoold/varoattno are always just copies
118  * of varno/varattno.  At the tail end of planning, Var nodes appearing in
119  * upper-level plan nodes are reassigned to point to the outputs of their
120  * subplans; for example, in a join node varno becomes INNER or OUTER and
121  * varattno becomes the index of the proper element of that subplan's target
122  * list.  But varnoold/varoattno continue to hold the original values.
123  * The code doesn't really need varnoold/varoattno, but they are very useful
124  * for debugging and interpreting completed plans, so we keep them around.
125  */
126 #define    INNER                65000
127 #define    OUTER                65001
128
129 #define    PRS2_OLD_VARNO                       1
130 #define    PRS2_NEW_VARNO                       2
131
132 typedef struct Var
133 {
134         Expr            xpr;
135         Index           varno;                  /* index of this var's relation in the range
136                                                                  * table (could also be INNER or OUTER) */
137         AttrNumber      varattno;               /* attribute number of this var, or zero for
138                                                                  * all */
139         Oid                     vartype;                /* pg_type OID for the type of this var */
140         int32           vartypmod;              /* pg_attribute typmod value */
141         Index           varlevelsup;
142
143         /*
144          * for subquery variables referencing outer relations; 0 in a normal var,
145          * >0 means N levels up
146          */
147         Index           varnoold;               /* original value of varno, for debugging */
148         AttrNumber      varoattno;              /* original value of varattno */
149 } Var;
150
151 /*
152  * Const
153  */
154 typedef struct Const
155 {
156         Expr            xpr;
157         Oid                     consttype;              /* pg_type OID of the constant's datatype */
158         int32           consttypmod;    /* typmod value, if any */
159         int                     constlen;               /* typlen of the constant's datatype */
160         Datum           constvalue;             /* the constant's value */
161         bool            constisnull;    /* whether the constant is null (if true,
162                                                                  * constvalue is undefined) */
163         bool            constbyval;             /* whether this datatype is passed by value.
164                                                                  * If true, then all the information is stored
165                                                                  * in the Datum. If false, then the Datum
166                                                                  * contains a pointer to the information. */
167 } Const;
168
169 /* ----------------
170  * Param
171  *              paramkind - specifies the kind of parameter. The possible values
172  *              for this field are:
173  *
174  *              PARAM_EXTERN:  The parameter value is supplied from outside the plan.
175  *                              Such parameters are numbered from 1 to n.
176  *
177  *              PARAM_EXEC:  The parameter is an internal executor parameter, used
178  *                              for passing values into and out of sub-queries.
179  *                              For historical reasons, such parameters are numbered from 0.
180  *                              These numbers are independent of PARAM_EXTERN numbers.
181  *
182  *              PARAM_SUBLINK:  The parameter represents an output column of a SubLink
183  *                              node's sub-select.  The column number is contained in the
184  *                              `paramid' field.  (This type of Param is converted to
185  *                              PARAM_EXEC during planning.)
186  *
187  * Note: currently, paramtypmod is valid for PARAM_SUBLINK Params, and for
188  * PARAM_EXEC Params generated from them; it is always -1 for PARAM_EXTERN
189  * params, since the APIs that supply values for such parameters don't carry
190  * any typmod info.
191  * ----------------
192  */
193 typedef enum ParamKind
194 {
195         PARAM_EXTERN,
196         PARAM_EXEC,
197         PARAM_SUBLINK
198 } ParamKind;
199
200 typedef struct Param
201 {
202         Expr            xpr;
203         ParamKind       paramkind;              /* kind of parameter. See above */
204         int                     paramid;                /* numeric ID for parameter */
205         Oid                     paramtype;              /* pg_type OID of parameter's datatype */
206         int32           paramtypmod;    /* typmod value, if known */
207 } Param;
208
209 /*
210  * Aggref
211  */
212 typedef struct Aggref
213 {
214         Expr            xpr;
215         Oid                     aggfnoid;               /* pg_proc Oid of the aggregate */
216         Oid                     aggtype;                /* type Oid of result of the aggregate */
217         List       *args;                       /* arguments to the aggregate */
218         Index           agglevelsup;    /* > 0 if agg belongs to outer query */
219         bool            aggstar;                /* TRUE if argument list was really '*' */
220         bool            aggdistinct;    /* TRUE if it's agg(DISTINCT ...) */
221 } Aggref;
222
223 /* ----------------
224  *      ArrayRef: describes an array subscripting operation
225  *
226  * An ArrayRef can describe fetching a single element from an array,
227  * fetching a subarray (array slice), storing a single element into
228  * an array, or storing a slice.  The "store" cases work with an
229  * initial array value and a source value that is inserted into the
230  * appropriate part of the array; the result of the operation is an
231  * entire new modified array value.
232  *
233  * If reflowerindexpr = NIL, then we are fetching or storing a single array
234  * element at the subscripts given by refupperindexpr.  Otherwise we are
235  * fetching or storing an array slice, that is a rectangular subarray
236  * with lower and upper bounds given by the index expressions.
237  * reflowerindexpr must be the same length as refupperindexpr when it
238  * is not NIL.
239  *
240  * Note: the result datatype is the element type when fetching a single
241  * element; but it is the array type when doing subarray fetch or either
242  * type of store.
243  * ----------------
244  */
245 typedef struct ArrayRef
246 {
247         Expr            xpr;
248         Oid                     refarraytype;   /* type of the array proper */
249         Oid                     refelemtype;    /* type of the array elements */
250         int32           reftypmod;              /* typmod of the array (and elements too) */
251         List       *refupperindexpr;/* expressions that evaluate to upper array
252                                                                  * indexes */
253         List       *reflowerindexpr;/* expressions that evaluate to lower array
254                                                                  * indexes */
255         Expr       *refexpr;            /* the expression that evaluates to an array
256                                                                  * value */
257         Expr       *refassgnexpr;       /* expression for the source value, or NULL if
258                                                                  * fetch */
259 } ArrayRef;
260
261 /*
262  * CoercionContext - distinguishes the allowed set of type casts
263  *
264  * NB: ordering of the alternatives is significant; later (larger) values
265  * allow more casts than earlier ones.
266  */
267 typedef enum CoercionContext
268 {
269         COERCION_IMPLICIT,                      /* coercion in context of expression */
270         COERCION_ASSIGNMENT,            /* coercion in context of assignment */
271         COERCION_EXPLICIT                       /* explicit cast operation */
272 } CoercionContext;
273
274 /*
275  * CoercionForm - information showing how to display a function-call node
276  */
277 typedef enum CoercionForm
278 {
279         COERCE_EXPLICIT_CALL,           /* display as a function call */
280         COERCE_EXPLICIT_CAST,           /* display as an explicit cast */
281         COERCE_IMPLICIT_CAST,           /* implicit cast, so hide it */
282         COERCE_DONTCARE                         /* special case for planner */
283 } CoercionForm;
284
285 /*
286  * FuncExpr - expression node for a function call
287  */
288 typedef struct FuncExpr
289 {
290         Expr            xpr;
291         Oid                     funcid;                 /* PG_PROC OID of the function */
292         Oid                     funcresulttype; /* PG_TYPE OID of result value */
293         bool            funcretset;             /* true if function returns set */
294         CoercionForm funcformat;        /* how to display this function call */
295         List       *args;                       /* arguments to the function */
296 } FuncExpr;
297
298 /*
299  * OpExpr - expression node for an operator invocation
300  *
301  * Semantically, this is essentially the same as a function call.
302  *
303  * Note that opfuncid is not necessarily filled in immediately on creation
304  * of the node.  The planner makes sure it is valid before passing the node
305  * tree to the executor, but during parsing/planning opfuncid is typically 0.
306  */
307 typedef struct OpExpr
308 {
309         Expr            xpr;
310         Oid                     opno;                   /* PG_OPERATOR OID of the operator */
311         Oid                     opfuncid;               /* PG_PROC OID of underlying function */
312         Oid                     opresulttype;   /* PG_TYPE OID of result value */
313         bool            opretset;               /* true if operator returns set */
314         List       *args;                       /* arguments to the operator (1 or 2) */
315 } OpExpr;
316
317 /*
318  * DistinctExpr - expression node for "x IS DISTINCT FROM y"
319  *
320  * Except for the nodetag, this is represented identically to an OpExpr
321  * referencing the "=" operator for x and y.
322  * We use "=", not the more obvious "<>", because more datatypes have "="
323  * than "<>".  This means the executor must invert the operator result.
324  * Note that the operator function won't be called at all if either input
325  * is NULL, since then the result can be determined directly.
326  */
327 typedef OpExpr DistinctExpr;
328
329 /*
330  * ScalarArrayOpExpr - expression node for "scalar op ANY/ALL (array)"
331  *
332  * The operator must yield boolean.  It is applied to the left operand
333  * and each element of the righthand array, and the results are combined
334  * with OR or AND (for ANY or ALL respectively).  The node representation
335  * is almost the same as for the underlying operator, but we need a useOr
336  * flag to remember whether it's ANY or ALL, and we don't have to store
337  * the result type because it must be boolean.
338  */
339 typedef struct ScalarArrayOpExpr
340 {
341         Expr            xpr;
342         Oid                     opno;                   /* PG_OPERATOR OID of the operator */
343         Oid                     opfuncid;               /* PG_PROC OID of underlying function */
344         bool            useOr;                  /* true for ANY, false for ALL */
345         List       *args;                       /* the scalar and array operands */
346 } ScalarArrayOpExpr;
347
348 /*
349  * BoolExpr - expression node for the basic Boolean operators AND, OR, NOT
350  *
351  * Notice the arguments are given as a List.  For NOT, of course the list
352  * must always have exactly one element.  For AND and OR, the executor can
353  * handle any number of arguments.      The parser treats AND and OR as binary
354  * and so it only produces two-element lists, but the optimizer will flatten
355  * trees of AND and OR nodes to produce longer lists when possible.
356  */
357 typedef enum BoolExprType
358 {
359         AND_EXPR, OR_EXPR, NOT_EXPR
360 } BoolExprType;
361
362 typedef struct BoolExpr
363 {
364         Expr            xpr;
365         BoolExprType boolop;
366         List       *args;                       /* arguments to this expression */
367 } BoolExpr;
368
369 /*
370  * SubLink
371  *
372  * A SubLink represents a subselect appearing in an expression, and in some
373  * cases also the combining operator(s) just above it.  The subLinkType
374  * indicates the form of the expression represented:
375  *      EXISTS_SUBLINK          EXISTS(SELECT ...)
376  *      ALL_SUBLINK                     (lefthand) op ALL (SELECT ...)
377  *      ANY_SUBLINK                     (lefthand) op ANY (SELECT ...)
378  *      ROWCOMPARE_SUBLINK      (lefthand) op (SELECT ...)
379  *      EXPR_SUBLINK            (SELECT with single targetlist item ...)
380  *      ARRAY_SUBLINK           ARRAY(SELECT with single targetlist item ...)
381  * For ALL, ANY, and ROWCOMPARE, the lefthand is a list of expressions of the
382  * same length as the subselect's targetlist.  ROWCOMPARE will *always* have
383  * a list with more than one entry; if the subselect has just one target
384  * then the parser will create an EXPR_SUBLINK instead (and any operator
385  * above the subselect will be represented separately).  Note that both
386  * ROWCOMPARE and EXPR require the subselect to deliver only one row.
387  * ALL, ANY, and ROWCOMPARE require the combining operators to deliver boolean
388  * results.  ALL and ANY combine the per-row results using AND and OR
389  * semantics respectively.
390  * ARRAY requires just one target column, and creates an array of the target
391  * column's type using one or more rows resulting from the subselect.
392  *
393  * SubLink is classed as an Expr node, but it is not actually executable;
394  * it must be replaced in the expression tree by a SubPlan node during
395  * planning.
396  *
397  * NOTE: in the raw output of gram.y, testexpr contains just the raw form
398  * of the lefthand expression (if any), and operName is the String name of
399  * the combining operator.      Also, subselect is a raw parsetree.  During parse
400  * analysis, the parser transforms testexpr into a complete boolean expression
401  * that compares the lefthand value(s) to PARAM_SUBLINK nodes representing the
402  * output columns of the subselect.  And subselect is transformed to a Query.
403  * This is the representation seen in saved rules and in the rewriter.
404  *
405  * In EXISTS, EXPR, and ARRAY SubLinks, testexpr and operName are unused and
406  * are always null.
407  */
408 typedef enum SubLinkType
409 {
410         EXISTS_SUBLINK,
411         ALL_SUBLINK,
412         ANY_SUBLINK,
413         ROWCOMPARE_SUBLINK,
414         EXPR_SUBLINK,
415         ARRAY_SUBLINK
416 } SubLinkType;
417
418
419 typedef struct SubLink
420 {
421         Expr            xpr;
422         SubLinkType subLinkType;        /* see above */
423         Node       *testexpr;           /* outer-query test for ALL/ANY/ROWCOMPARE */
424         List       *operName;           /* originally specified operator name */
425         Node       *subselect;          /* subselect as Query* or parsetree */
426 } SubLink;
427
428 /*
429  * SubPlan - executable expression node for a subplan (sub-SELECT)
430  *
431  * The planner replaces SubLink nodes in expression trees with SubPlan
432  * nodes after it has finished planning the subquery.  SubPlan references
433  * a sub-plantree stored in the subplans list of the toplevel PlannedStmt.
434  * (We avoid a direct link to make it easier to copy expression trees
435  * without causing multiple processing of the subplan.)
436  *
437  * In an ordinary subplan, testexpr points to an executable expression
438  * (OpExpr, an AND/OR tree of OpExprs, or RowCompareExpr) for the combining
439  * operator(s); the left-hand arguments are the original lefthand expressions,
440  * and the right-hand arguments are PARAM_EXEC Param nodes representing the
441  * outputs of the sub-select.  (NOTE: runtime coercion functions may be
442  * inserted as well.)  This is just the same expression tree as testexpr in
443  * the original SubLink node, but the PARAM_SUBLINK nodes are replaced by
444  * suitably numbered PARAM_EXEC nodes.
445  *
446  * If the sub-select becomes an initplan rather than a subplan, the executable
447  * expression is part of the outer plan's expression tree (and the SubPlan
448  * node itself is not).  In this case testexpr is NULL to avoid duplication.
449  *
450  * The planner also derives lists of the values that need to be passed into
451  * and out of the subplan.      Input values are represented as a list "args" of
452  * expressions to be evaluated in the outer-query context (currently these
453  * args are always just Vars, but in principle they could be any expression).
454  * The values are assigned to the global PARAM_EXEC params indexed by parParam
455  * (the parParam and args lists must have the same ordering).  setParam is a
456  * list of the PARAM_EXEC params that are computed by the sub-select, if it
457  * is an initplan; they are listed in order by sub-select output column
458  * position.  (parParam and setParam are integer Lists, not Bitmapsets,
459  * because their ordering is significant.)
460  */
461 typedef struct SubPlan
462 {
463         Expr            xpr;
464         /* Fields copied from original SubLink: */
465         SubLinkType subLinkType;        /* see above */
466         /* The combining operators, transformed to an executable expression: */
467         Node       *testexpr;           /* OpExpr or RowCompareExpr expression tree */
468         List       *paramIds;           /* IDs of Params embedded in the above */
469         /* Identification of the Plan tree to use: */
470         int                     plan_id;                /* Index (from 1) in PlannedStmt.subplans */
471         /* Extra data saved for the convenience of exprType(): */
472         Oid                     firstColType;   /* Type of first column of subplan result */
473         /* Information about execution strategy: */
474         bool            useHashTable;   /* TRUE to store subselect output in a hash
475                                                                  * table (implies we are doing "IN") */
476         bool            unknownEqFalse; /* TRUE if it's okay to return FALSE when the
477                                                                  * spec result is UNKNOWN; this allows much
478                                                                  * simpler handling of null values */
479         /* Information for passing params into and out of the subselect: */
480         /* setParam and parParam are lists of integers (param IDs) */
481         List       *setParam;           /* initplan subqueries have to set these
482                                                                  * Params for parent plan */
483         List       *parParam;           /* indices of input Params from parent plan */
484         List       *args;                       /* exprs to pass as parParam values */
485 } SubPlan;
486
487 /* ----------------
488  * FieldSelect
489  *
490  * FieldSelect represents the operation of extracting one field from a tuple
491  * value.  At runtime, the input expression is expected to yield a rowtype
492  * Datum.  The specified field number is extracted and returned as a Datum.
493  * ----------------
494  */
495
496 typedef struct FieldSelect
497 {
498         Expr            xpr;
499         Expr       *arg;                        /* input expression */
500         AttrNumber      fieldnum;               /* attribute number of field to extract */
501         Oid                     resulttype;             /* type of the field (result type of this
502                                                                  * node) */
503         int32           resulttypmod;   /* output typmod (usually -1) */
504 } FieldSelect;
505
506 /* ----------------
507  * FieldStore
508  *
509  * FieldStore represents the operation of modifying one field in a tuple
510  * value, yielding a new tuple value (the input is not touched!).  Like
511  * the assign case of ArrayRef, this is used to implement UPDATE of a
512  * portion of a column.
513  *
514  * A single FieldStore can actually represent updates of several different
515  * fields.      The parser only generates FieldStores with single-element lists,
516  * but the planner will collapse multiple updates of the same base column
517  * into one FieldStore.
518  * ----------------
519  */
520
521 typedef struct FieldStore
522 {
523         Expr            xpr;
524         Expr       *arg;                        /* input tuple value */
525         List       *newvals;            /* new value(s) for field(s) */
526         List       *fieldnums;          /* integer list of field attnums */
527         Oid                     resulttype;             /* type of result (same as type of arg) */
528         /* Like RowExpr, we deliberately omit a typmod here */
529 } FieldStore;
530
531 /* ----------------
532  * RelabelType
533  *
534  * RelabelType represents a "dummy" type coercion between two binary-
535  * compatible datatypes, such as reinterpreting the result of an OID
536  * expression as an int4.  It is a no-op at runtime; we only need it
537  * to provide a place to store the correct type to be attributed to
538  * the expression result during type resolution.  (We can't get away
539  * with just overwriting the type field of the input expression node,
540  * so we need a separate node to show the coercion's result type.)
541  * ----------------
542  */
543
544 typedef struct RelabelType
545 {
546         Expr            xpr;
547         Expr       *arg;                        /* input expression */
548         Oid                     resulttype;             /* output type of coercion expression */
549         int32           resulttypmod;   /* output typmod (usually -1) */
550         CoercionForm relabelformat; /* how to display this node */
551 } RelabelType;
552
553 /* ----------------
554  * ArrayCoerceExpr
555  *
556  * ArrayCoerceExpr represents a type coercion from one array type to another,
557  * which is implemented by applying the indicated element-type coercion
558  * function to each element of the source array.  If elemfuncid is InvalidOid
559  * then the element types are binary-compatible, but the coercion still
560  * requires some effort (we have to fix the element type ID stored in the
561  * array header).
562  * ----------------
563  */
564
565 typedef struct ArrayCoerceExpr
566 {
567         Expr            xpr;
568         Expr       *arg;                        /* input expression (yields an array) */
569         Oid                     elemfuncid;             /* OID of element coercion function, or 0 */
570         Oid                     resulttype;             /* output type of coercion (an array type) */
571         int32           resulttypmod;   /* output typmod (also element typmod) */
572         bool            isExplicit;             /* conversion semantics flag to pass to func */
573         CoercionForm coerceformat;      /* how to display this node */
574 } ArrayCoerceExpr;
575
576 /* ----------------
577  * ConvertRowtypeExpr
578  *
579  * ConvertRowtypeExpr represents a type coercion from one composite type
580  * to another, where the source type is guaranteed to contain all the columns
581  * needed for the destination type plus possibly others; the columns need not
582  * be in the same positions, but are matched up by name.  This is primarily
583  * used to convert a whole-row value of an inheritance child table into a
584  * valid whole-row value of its parent table's rowtype.
585  * ----------------
586  */
587
588 typedef struct ConvertRowtypeExpr
589 {
590         Expr            xpr;
591         Expr       *arg;                        /* input expression */
592         Oid                     resulttype;             /* output type (always a composite type) */
593         /* result typmod is not stored, but must be -1; see RowExpr comments */
594         CoercionForm convertformat; /* how to display this node */
595 } ConvertRowtypeExpr;
596
597 /*----------
598  * CaseExpr - a CASE expression
599  *
600  * We support two distinct forms of CASE expression:
601  *              CASE WHEN boolexpr THEN expr [ WHEN boolexpr THEN expr ... ]
602  *              CASE testexpr WHEN compexpr THEN expr [ WHEN compexpr THEN expr ... ]
603  * These are distinguishable by the "arg" field being NULL in the first case
604  * and the testexpr in the second case.
605  *
606  * In the raw grammar output for the second form, the condition expressions
607  * of the WHEN clauses are just the comparison values.  Parse analysis
608  * converts these to valid boolean expressions of the form
609  *              CaseTestExpr '=' compexpr
610  * where the CaseTestExpr node is a placeholder that emits the correct
611  * value at runtime.  This structure is used so that the testexpr need be
612  * evaluated only once.  Note that after parse analysis, the condition
613  * expressions always yield boolean.
614  *
615  * Note: we can test whether a CaseExpr has been through parse analysis
616  * yet by checking whether casetype is InvalidOid or not.
617  *----------
618  */
619 typedef struct CaseExpr
620 {
621         Expr            xpr;
622         Oid                     casetype;               /* type of expression result */
623         Expr       *arg;                        /* implicit equality comparison argument */
624         List       *args;                       /* the arguments (list of WHEN clauses) */
625         Expr       *defresult;          /* the default result (ELSE clause) */
626 } CaseExpr;
627
628 /*
629  * CaseWhen - one arm of a CASE expression
630  */
631 typedef struct CaseWhen
632 {
633         Expr            xpr;
634         Expr       *expr;                       /* condition expression */
635         Expr       *result;                     /* substitution result */
636 } CaseWhen;
637
638 /*
639  * Placeholder node for the test value to be processed by a CASE expression.
640  * This is effectively like a Param, but can be implemented more simply
641  * since we need only one replacement value at a time.
642  *
643  * We also use this in nested UPDATE expressions.
644  * See transformAssignmentIndirection().
645  */
646 typedef struct CaseTestExpr
647 {
648         Expr            xpr;
649         Oid                     typeId;                 /* type for substituted value */
650         int32           typeMod;                /* typemod for substituted value */
651 } CaseTestExpr;
652
653 /*
654  * ArrayExpr - an ARRAY[] expression
655  *
656  * Note: if multidims is false, the constituent expressions all yield the
657  * scalar type identified by element_typeid.  If multidims is true, the
658  * constituent expressions all yield arrays of element_typeid (ie, the same
659  * type as array_typeid); at runtime we must check for compatible subscripts.
660  */
661 typedef struct ArrayExpr
662 {
663         Expr            xpr;
664         Oid                     array_typeid;   /* type of expression result */
665         Oid                     element_typeid; /* common type of array elements */
666         List       *elements;           /* the array elements or sub-arrays */
667         bool            multidims;              /* true if elements are sub-arrays */
668 } ArrayExpr;
669
670 /*
671  * RowExpr - a ROW() expression
672  *
673  * Note: the list of fields must have a one-for-one correspondence with
674  * physical fields of the associated rowtype, although it is okay for it
675  * to be shorter than the rowtype.      That is, the N'th list element must
676  * match up with the N'th physical field.  When the N'th physical field
677  * is a dropped column (attisdropped) then the N'th list element can just
678  * be a NULL constant.  (This case can only occur for named composite types,
679  * not RECORD types, since those are built from the RowExpr itself rather
680  * than vice versa.)  It is important not to assume that length(args) is
681  * the same as the number of columns logically present in the rowtype.
682  */
683 typedef struct RowExpr
684 {
685         Expr            xpr;
686         List       *args;                       /* the fields */
687         Oid                     row_typeid;             /* RECORDOID or a composite type's ID */
688
689         /*
690          * Note: we deliberately do NOT store a typmod.  Although a typmod will be
691          * associated with specific RECORD types at runtime, it will differ for
692          * different backends, and so cannot safely be stored in stored
693          * parsetrees.  We must assume typmod -1 for a RowExpr node.
694          */
695         CoercionForm row_format;        /* how to display this node */
696 } RowExpr;
697
698 /*
699  * RowCompareExpr - row-wise comparison, such as (a, b) <= (1, 2)
700  *
701  * We support row comparison for any operator that can be determined to
702  * act like =, <>, <, <=, >, or >= (we determine this by looking for the
703  * operator in btree opfamilies).  Note that the same operator name might
704  * map to a different operator for each pair of row elements, since the
705  * element datatypes can vary.
706  *
707  * A RowCompareExpr node is only generated for the < <= > >= cases;
708  * the = and <> cases are translated to simple AND or OR combinations
709  * of the pairwise comparisons.  However, we include = and <> in the
710  * RowCompareType enum for the convenience of parser logic.
711  */
712 typedef enum RowCompareType
713 {
714         /* Values of this enum are chosen to match btree strategy numbers */
715         ROWCOMPARE_LT = 1,                      /* BTLessStrategyNumber */
716         ROWCOMPARE_LE = 2,                      /* BTLessEqualStrategyNumber */
717         ROWCOMPARE_EQ = 3,                      /* BTEqualStrategyNumber */
718         ROWCOMPARE_GE = 4,                      /* BTGreaterEqualStrategyNumber */
719         ROWCOMPARE_GT = 5,                      /* BTGreaterStrategyNumber */
720         ROWCOMPARE_NE = 6                       /* no such btree strategy */
721 } RowCompareType;
722
723 typedef struct RowCompareExpr
724 {
725         Expr            xpr;
726         RowCompareType rctype;          /* LT LE GE or GT, never EQ or NE */
727         List       *opnos;                      /* OID list of pairwise comparison ops */
728         List       *opfamilies;         /* OID list of containing operator families */
729         List       *largs;                      /* the left-hand input arguments */
730         List       *rargs;                      /* the right-hand input arguments */
731 } RowCompareExpr;
732
733 /*
734  * CoalesceExpr - a COALESCE expression
735  */
736 typedef struct CoalesceExpr
737 {
738         Expr            xpr;
739         Oid                     coalescetype;   /* type of expression result */
740         List       *args;                       /* the arguments */
741 } CoalesceExpr;
742
743 /*
744  * MinMaxExpr - a GREATEST or LEAST function
745  */
746 typedef enum MinMaxOp
747 {
748         IS_GREATEST,
749         IS_LEAST
750 } MinMaxOp;
751
752 typedef struct MinMaxExpr
753 {
754         Expr            xpr;
755         Oid                     minmaxtype;             /* common type of arguments and result */
756         MinMaxOp        op;                             /* function to execute */
757         List       *args;                       /* the arguments */
758 } MinMaxExpr;
759
760 /*
761  * XmlExpr - various SQL/XML functions requiring special grammar productions
762  *
763  * 'name' carries the "NAME foo" argument (already XML-escaped).
764  * 'named_args' and 'arg_names' represent an xml_attribute list.
765  * 'args' carries all other arguments.
766  */
767 typedef enum XmlExprOp
768 {
769         IS_XMLCONCAT,                           /* XMLCONCAT(args) */
770         IS_XMLELEMENT,                          /* XMLELEMENT(name, xml_attributes, args) */
771         IS_XMLFOREST,                           /* XMLFOREST(xml_attributes) */
772         IS_XMLPARSE,                            /* XMLPARSE(text, is_doc, preserve_ws) */
773         IS_XMLPI,                                       /* XMLPI(name [, args]) */
774         IS_XMLROOT,                                     /* XMLROOT(xml, version, standalone) */
775         IS_XMLSERIALIZE,                        /* XMLSERIALIZE(is_document, xmlval) */
776         IS_DOCUMENT                                     /* xmlval IS DOCUMENT */
777 } XmlExprOp;
778
779 typedef enum
780 {
781         XMLOPTION_DOCUMENT,
782         XMLOPTION_CONTENT
783 } XmlOptionType;
784
785 typedef struct XmlExpr
786 {
787         Expr            xpr;
788         XmlExprOp       op;                             /* xml function ID */
789         char       *name;                       /* name in xml(NAME foo ...) syntaxes */
790         List       *named_args;         /* non-XML expressions for xml_attributes */
791         List       *arg_names;          /* parallel list of Value strings */
792         List       *args;                       /* list of expressions */
793         XmlOptionType xmloption;        /* DOCUMENT or CONTENT */
794         Oid                     type;                   /* target type for XMLSERIALIZE */
795         int32           typmod;
796 } XmlExpr;
797
798 /*
799  * NullIfExpr - a NULLIF expression
800  *
801  * Like DistinctExpr, this is represented the same as an OpExpr referencing
802  * the "=" operator for x and y.
803  */
804 typedef OpExpr NullIfExpr;
805
806 /* ----------------
807  * NullTest
808  *
809  * NullTest represents the operation of testing a value for NULLness.
810  * The appropriate test is performed and returned as a boolean Datum.
811  *
812  * NOTE: the semantics of this for rowtype inputs are noticeably different
813  * from the scalar case.  It would probably be a good idea to include an
814  * "argisrow" flag in the struct to reflect that, but for the moment,
815  * we do not do so to avoid forcing an initdb during 8.2beta.
816  * ----------------
817  */
818
819 typedef enum NullTestType
820 {
821         IS_NULL, IS_NOT_NULL
822 } NullTestType;
823
824 typedef struct NullTest
825 {
826         Expr            xpr;
827         Expr       *arg;                        /* input expression */
828         NullTestType nulltesttype;      /* IS NULL, IS NOT NULL */
829 } NullTest;
830
831 /*
832  * BooleanTest
833  *
834  * BooleanTest represents the operation of determining whether a boolean
835  * is TRUE, FALSE, or UNKNOWN (ie, NULL).  All six meaningful combinations
836  * are supported.  Note that a NULL input does *not* cause a NULL result.
837  * The appropriate test is performed and returned as a boolean Datum.
838  */
839
840 typedef enum BoolTestType
841 {
842         IS_TRUE, IS_NOT_TRUE, IS_FALSE, IS_NOT_FALSE, IS_UNKNOWN, IS_NOT_UNKNOWN
843 } BoolTestType;
844
845 typedef struct BooleanTest
846 {
847         Expr            xpr;
848         Expr       *arg;                        /* input expression */
849         BoolTestType booltesttype;      /* test type */
850 } BooleanTest;
851
852 /*
853  * CoerceToDomain
854  *
855  * CoerceToDomain represents the operation of coercing a value to a domain
856  * type.  At runtime (and not before) the precise set of constraints to be
857  * checked will be determined.  If the value passes, it is returned as the
858  * result; if not, an error is raised.  Note that this is equivalent to
859  * RelabelType in the scenario where no constraints are applied.
860  */
861 typedef struct CoerceToDomain
862 {
863         Expr            xpr;
864         Expr       *arg;                        /* input expression */
865         Oid                     resulttype;             /* domain type ID (result type) */
866         int32           resulttypmod;   /* output typmod (currently always -1) */
867         CoercionForm coercionformat;    /* how to display this node */
868 } CoerceToDomain;
869
870 /*
871  * Placeholder node for the value to be processed by a domain's check
872  * constraint.  This is effectively like a Param, but can be implemented more
873  * simply since we need only one replacement value at a time.
874  *
875  * Note: the typeId/typeMod will be set from the domain's base type, not
876  * the domain itself.  This is because we shouldn't consider the value to
877  * be a member of the domain if we haven't yet checked its constraints.
878  */
879 typedef struct CoerceToDomainValue
880 {
881         Expr            xpr;
882         Oid                     typeId;                 /* type for substituted value */
883         int32           typeMod;                /* typemod for substituted value */
884 } CoerceToDomainValue;
885
886 /*
887  * Placeholder node for a DEFAULT marker in an INSERT or UPDATE command.
888  *
889  * This is not an executable expression: it must be replaced by the actual
890  * column default expression during rewriting.  But it is convenient to
891  * treat it as an expression node during parsing and rewriting.
892  */
893 typedef struct SetToDefault
894 {
895         Expr            xpr;
896         Oid                     typeId;                 /* type for substituted value */
897         int32           typeMod;                /* typemod for substituted value */
898 } SetToDefault;
899
900 /*--------------------
901  * TargetEntry -
902  *         a target entry (used in query target lists)
903  *
904  * Strictly speaking, a TargetEntry isn't an expression node (since it can't
905  * be evaluated by ExecEvalExpr).  But we treat it as one anyway, since in
906  * very many places it's convenient to process a whole query targetlist as a
907  * single expression tree.
908  *
909  * In a SELECT's targetlist, resno should always be equal to the item's
910  * ordinal position (counting from 1).  However, in an INSERT or UPDATE
911  * targetlist, resno represents the attribute number of the destination
912  * column for the item; so there may be missing or out-of-order resnos.
913  * It is even legal to have duplicated resnos; consider
914  *              UPDATE table SET arraycol[1] = ..., arraycol[2] = ..., ...
915  * The two meanings come together in the executor, because the planner
916  * transforms INSERT/UPDATE tlists into a normalized form with exactly
917  * one entry for each column of the destination table.  Before that's
918  * happened, however, it is risky to assume that resno == position.
919  * Generally get_tle_by_resno() should be used rather than list_nth()
920  * to fetch tlist entries by resno, and only in SELECT should you assume
921  * that resno is a unique identifier.
922  *
923  * resname is required to represent the correct column name in non-resjunk
924  * entries of top-level SELECT targetlists, since it will be used as the
925  * column title sent to the frontend.  In most other contexts it is only
926  * a debugging aid, and may be wrong or even NULL.      (In particular, it may
927  * be wrong in a tlist from a stored rule, if the referenced column has been
928  * renamed by ALTER TABLE since the rule was made.      Also, the planner tends
929  * to store NULL rather than look up a valid name for tlist entries in
930  * non-toplevel plan nodes.)  In resjunk entries, resname should be either
931  * a specific system-generated name (such as "ctid") or NULL; anything else
932  * risks confusing ExecGetJunkAttribute!
933  *
934  * ressortgroupref is used in the representation of ORDER BY and
935  * GROUP BY items.      Targetlist entries with ressortgroupref=0 are not
936  * sort/group items.  If ressortgroupref>0, then this item is an ORDER BY or
937  * GROUP BY value.      No two entries in a targetlist may have the same nonzero
938  * ressortgroupref --- but there is no particular meaning to the nonzero
939  * values, except as tags.      (For example, one must not assume that lower
940  * ressortgroupref means a more significant sort key.)  The order of the
941  * associated SortClause or GroupClause lists determine the semantics.
942  *
943  * resorigtbl/resorigcol identify the source of the column, if it is a
944  * simple reference to a column of a base table (or view).      If it is not
945  * a simple reference, these fields are zeroes.
946  *
947  * If resjunk is true then the column is a working column (such as a sort key)
948  * that should be removed from the final output of the query.  Resjunk columns
949  * must have resnos that cannot duplicate any regular column's resno.  Also
950  * note that there are places that assume resjunk columns come after non-junk
951  * columns.
952  *--------------------
953  */
954 typedef struct TargetEntry
955 {
956         Expr            xpr;
957         Expr       *expr;                       /* expression to evaluate */
958         AttrNumber      resno;                  /* attribute number (see notes above) */
959         char       *resname;            /* name of the column (could be NULL) */
960         Index           ressortgroupref;/* nonzero if referenced by a sort/group
961                                                                  * clause */
962         Oid                     resorigtbl;             /* OID of column's source table */
963         AttrNumber      resorigcol;             /* column's number in source table */
964         bool            resjunk;                /* set to true to eliminate the attribute from
965                                                                  * final target list */
966 } TargetEntry;
967
968
969 /* ----------------------------------------------------------------
970  *                                      node types for join trees
971  *
972  * The leaves of a join tree structure are RangeTblRef nodes.  Above
973  * these, JoinExpr nodes can appear to denote a specific kind of join
974  * or qualified join.  Also, FromExpr nodes can appear to denote an
975  * ordinary cross-product join ("FROM foo, bar, baz WHERE ...").
976  * FromExpr is like a JoinExpr of jointype JOIN_INNER, except that it
977  * may have any number of child nodes, not just two.
978  *
979  * NOTE: the top level of a Query's jointree is always a FromExpr.
980  * Even if the jointree contains no rels, there will be a FromExpr.
981  *
982  * NOTE: the qualification expressions present in JoinExpr nodes are
983  * *in addition to* the query's main WHERE clause, which appears as the
984  * qual of the top-level FromExpr.      The reason for associating quals with
985  * specific nodes in the jointree is that the position of a qual is critical
986  * when outer joins are present.  (If we enforce a qual too soon or too late,
987  * that may cause the outer join to produce the wrong set of NULL-extended
988  * rows.)  If all joins are inner joins then all the qual positions are
989  * semantically interchangeable.
990  *
991  * NOTE: in the raw output of gram.y, a join tree contains RangeVar,
992  * RangeSubselect, and RangeFunction nodes, which are all replaced by
993  * RangeTblRef nodes during the parse analysis phase.  Also, the top-level
994  * FromExpr is added during parse analysis; the grammar regards FROM and
995  * WHERE as separate.
996  * ----------------------------------------------------------------
997  */
998
999 /*
1000  * RangeTblRef - reference to an entry in the query's rangetable
1001  *
1002  * We could use direct pointers to the RT entries and skip having these
1003  * nodes, but multiple pointers to the same node in a querytree cause
1004  * lots of headaches, so it seems better to store an index into the RT.
1005  */
1006 typedef struct RangeTblRef
1007 {
1008         NodeTag         type;
1009         int                     rtindex;
1010 } RangeTblRef;
1011
1012 /*----------
1013  * JoinExpr - for SQL JOIN expressions
1014  *
1015  * isNatural, using, and quals are interdependent.      The user can write only
1016  * one of NATURAL, USING(), or ON() (this is enforced by the grammar).
1017  * If he writes NATURAL then parse analysis generates the equivalent USING()
1018  * list, and from that fills in "quals" with the right equality comparisons.
1019  * If he writes USING() then "quals" is filled with equality comparisons.
1020  * If he writes ON() then only "quals" is set.  Note that NATURAL/USING
1021  * are not equivalent to ON() since they also affect the output column list.
1022  *
1023  * alias is an Alias node representing the AS alias-clause attached to the
1024  * join expression, or NULL if no clause.  NB: presence or absence of the
1025  * alias has a critical impact on semantics, because a join with an alias
1026  * restricts visibility of the tables/columns inside it.
1027  *
1028  * During parse analysis, an RTE is created for the Join, and its index
1029  * is filled into rtindex.      This RTE is present mainly so that Vars can
1030  * be created that refer to the outputs of the join.
1031  *----------
1032  */
1033 typedef struct JoinExpr
1034 {
1035         NodeTag         type;
1036         JoinType        jointype;               /* type of join */
1037         bool            isNatural;              /* Natural join? Will need to shape table */
1038         Node       *larg;                       /* left subtree */
1039         Node       *rarg;                       /* right subtree */
1040         List       *using;                      /* USING clause, if any (list of String) */
1041         Node       *quals;                      /* qualifiers on join, if any */
1042         Alias      *alias;                      /* user-written alias clause, if any */
1043         int                     rtindex;                /* RT index assigned for join */
1044 } JoinExpr;
1045
1046 /*----------
1047  * FromExpr - represents a FROM ... WHERE ... construct
1048  *
1049  * This is both more flexible than a JoinExpr (it can have any number of
1050  * children, including zero) and less so --- we don't need to deal with
1051  * aliases and so on.  The output column set is implicitly just the union
1052  * of the outputs of the children.
1053  *----------
1054  */
1055 typedef struct FromExpr
1056 {
1057         NodeTag         type;
1058         List       *fromlist;           /* List of join subtrees */
1059         Node       *quals;                      /* qualifiers on join, if any */
1060 } FromExpr;
1061
1062 #endif   /* PRIMNODES_H */