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