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