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