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