]> granicus.if.org Git - postgresql/blob - src/include/nodes/primnodes.h
Code review for IS DISTINCT FROM patch. Fix incorrect constant-folding
[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-2002, PostgreSQL Global Development Group
11  * Portions Copyright (c) 1994, Regents of the University of California
12  *
13  * $Id: primnodes.h,v 1.71 2002/11/30 21:25:06 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 /* FunctionCache is declared in utils/fcache.h */
24 typedef struct FunctionCache *FunctionCachePtr;
25
26
27 /* ----------------------------------------------------------------
28  *                                              node definitions
29  * ----------------------------------------------------------------
30  */
31
32 /*--------------------
33  * Resdom (Result Domain)
34  *
35  * Notes:
36  * ressortgroupref is the parse/plan-time representation of ORDER BY and
37  * GROUP BY items.      Targetlist entries with ressortgroupref=0 are not
38  * sort/group items.  If ressortgroupref>0, then this item is an ORDER BY or
39  * GROUP BY value.      No two entries in a targetlist may have the same nonzero
40  * ressortgroupref --- but there is no particular meaning to the nonzero
41  * values, except as tags.      (For example, one must not assume that lower
42  * ressortgroupref means a more significant sort key.)  The order of the
43  * associated SortClause or GroupClause lists determine the semantics.
44  *
45  * reskey and reskeyop are the execution-time representation of sorting.
46  * reskey must be zero in any non-sort-key item.  The reskey of sort key
47  * targetlist items for a sort plan node is 1,2,...,n for the n sort keys.
48  * The reskeyop of each such targetlist item is the sort operator's OID.
49  * reskeyop will be zero in non-sort-key items.
50  *
51  * Both reskey and reskeyop are typically zero during parse/plan stages.
52  * The executor does not pay any attention to ressortgroupref.
53  *--------------------
54  */
55 typedef struct Resdom
56 {
57         NodeTag         type;
58         AttrNumber      resno;                  /* attribute number */
59         Oid                     restype;                /* type of the value */
60         int32           restypmod;              /* type-specific modifier of the value */
61         char       *resname;            /* name of the resdom (could be NULL) */
62         Index           ressortgroupref;
63         /* nonzero if referenced by a sort/group clause */
64         Index           reskey;                 /* order of key in a sort (for those > 0) */
65         Oid                     reskeyop;               /* sort operator's Oid */
66         bool            resjunk;                /* set to true to eliminate the attribute
67                                                                  * from final target list */
68 } Resdom;
69
70 /*
71  * Fjoin
72  */
73 typedef struct Fjoin
74 {
75         NodeTag         type;
76         bool            fj_initialized; /* true if the Fjoin has already been
77                                                                  * initialized for the current target list
78                                                                  * evaluation */
79         int                     fj_nNodes;              /* The number of Iter nodes returning sets
80                                                                  * that the node will flatten */
81         List       *fj_innerNode;       /* exactly one Iter node.  We eval every
82                                                                  * node in the outerList once then eval
83                                                                  * the inner node to completion pair the
84                                                                  * outerList result vector with each inner
85                                                                  * result to form the full result.      When
86                                                                  * the inner has been exhausted, we get
87                                                                  * the next outer result vector and reset
88                                                                  * the inner. */
89         DatumPtr        fj_results;             /* The complete (flattened) result vector */
90         BoolPtr         fj_alwaysDone;  /* a null vector to indicate sets with a
91                                                                  * cardinality of 0, we treat them as the
92                                                                  * set {NULL}. */
93 } Fjoin;
94
95
96 /*
97  * Alias -
98  *        specifies an alias for a range variable; the alias might also
99  *        specify renaming of columns within the table.
100  */
101 typedef struct Alias
102 {
103         NodeTag         type;
104         char       *aliasname;          /* aliased rel name (never qualified) */
105         List       *colnames;           /* optional list of column aliases */
106         /* Note: colnames is a list of Value nodes (always strings) */
107 } Alias;
108
109 typedef enum InhOption
110 {
111         INH_NO,                                         /* Do NOT scan child tables */
112         INH_YES,                                        /* DO scan child tables */
113         INH_DEFAULT                                     /* Use current SQL_inheritance option */
114 } InhOption;
115
116 /*
117  * RangeVar - range variable, used in FROM clauses
118  *
119  * Also used to represent table names in utility statements; there, the alias
120  * field is not used, and inhOpt shows whether to apply the operation
121  * recursively to child tables.  In some contexts it is also useful to carry
122  * a TEMP table indication here.
123  */
124 typedef struct RangeVar
125 {
126         NodeTag         type;
127         char       *catalogname;        /* the catalog (database) name, or NULL */
128         char       *schemaname;         /* the schema name, or NULL */
129         char       *relname;            /* the relation/sequence name */
130         InhOption       inhOpt;                 /* expand rel by inheritance? recursively
131                                                                  * act on children? */
132         bool            istemp;                 /* is this a temp relation/sequence? */
133         Alias      *alias;                      /* table alias & optional column aliases */
134 } RangeVar;
135
136
137 /* ----------------------------------------------------------------
138  *                                      node types for executable expressions
139  * ----------------------------------------------------------------
140  */
141
142 /*
143  * CoercionContext - distinguishes the allowed set of type casts
144  *
145  * NB: ordering of the alternatives is significant; later (larger) values
146  * allow more casts than earlier ones.
147  */
148 typedef enum CoercionContext
149 {
150         COERCION_IMPLICIT,                      /* coercion in context of expression */
151         COERCION_ASSIGNMENT,            /* coercion in context of assignment */
152         COERCION_EXPLICIT                       /* explicit cast operation */
153 } CoercionContext;
154
155 /*
156  * CoercionForm - information showing how to display a function-call node
157  */
158 typedef enum CoercionForm
159 {
160         COERCE_EXPLICIT_CALL,           /* display as a function call */
161         COERCE_EXPLICIT_CAST,           /* display as an explicit cast */
162         COERCE_IMPLICIT_CAST,           /* implicit cast, so hide it */
163         COERCE_DONTCARE                         /* special case for pathkeys */
164 } CoercionForm;
165
166 /*
167  * Expr
168  *
169  * Note: DISTINCT_EXPR implements the "x IS DISTINCT FROM y" construct.
170  * This is similar to an OP_EXPR, except for its handling of NULL inputs.
171  * The oper field is always an Oper node for the "=" operator for x and y.
172  * (We use "=", not the more obvious "<>", because more datatypes have "="
173  * than "<>".  This means the executor must invert the operator result.)
174  */
175 typedef enum OpType
176 {
177         OP_EXPR, DISTINCT_EXPR, FUNC_EXPR,
178         OR_EXPR, AND_EXPR, NOT_EXPR, SUBPLAN_EXPR
179 } OpType;
180
181 typedef struct Expr
182 {
183         NodeTag         type;
184         Oid                     typeOid;                /* oid of the type of this expression */
185         OpType          opType;                 /* kind of expression */
186         Node       *oper;                       /* operator node if needed (Oper, Func, or
187                                                                  * SubPlan) */
188         List       *args;                       /* arguments to this expression */
189 } Expr;
190
191 /*
192  * Oper - Expr subnode for an OP_EXPR (or DISTINCT_EXPR)
193  *
194  * NOTE: in the good old days 'opno' used to be both (or either, or
195  * neither) the pg_operator oid, and/or the pg_proc oid depending
196  * on the postgres module in question (parser->pg_operator,
197  * executor->pg_proc, planner->both), the mood of the programmer,
198  * and the phase of the moon (rumors that it was also depending on the day
199  * of the week are probably false). To make things even more postgres-like
200  * (i.e. a mess) some comments were referring to 'opno' using the name
201  * 'opid'. Anyway, now we have two separate fields, and of course that
202  * immediately removes all bugs from the code...                [ sp :-) ].
203  *
204  * Note also that opid is not necessarily filled in immediately on creation
205  * of the node.  The planner makes sure it is valid before passing the node
206  * tree to the executor, but during parsing/planning opid is typically 0.
207  */
208 typedef struct Oper
209 {
210         NodeTag         type;
211         Oid                     opno;                   /* PG_OPERATOR OID of the operator */
212         Oid                     opid;                   /* PG_PROC OID of underlying function */
213         Oid                     opresulttype;   /* PG_TYPE OID of result value */
214         bool            opretset;               /* true if operator returns set */
215         FunctionCachePtr op_fcache; /* runtime state, else NULL */
216 } Oper;
217
218 /*
219  * Func - Expr subnode for a FUNC_EXPR
220  */
221 typedef struct Func
222 {
223         NodeTag         type;
224         Oid                     funcid;                 /* PG_PROC OID of the function */
225         Oid                     funcresulttype; /* PG_TYPE OID of result value */
226         bool            funcretset;             /* true if function returns set */
227         CoercionForm funcformat;        /* how to display this function call */
228         FunctionCachePtr func_fcache;           /* runtime state, or NULL */
229 } Func;
230
231 /*
232  * Var
233  *
234  * Note: during parsing/planning, varnoold/varoattno are always just copies
235  * of varno/varattno.  At the tail end of planning, Var nodes appearing in
236  * upper-level plan nodes are reassigned to point to the outputs of their
237  * subplans; for example, in a join node varno becomes INNER or OUTER and
238  * varattno becomes the index of the proper element of that subplan's target
239  * list.  But varnoold/varoattno continue to hold the original values.
240  * The code doesn't really need varnoold/varoattno, but they are very useful
241  * for debugging and interpreting completed plans, so we keep them around.
242  */
243 #define    INNER                65000
244 #define    OUTER                65001
245
246 #define    PRS2_OLD_VARNO                       1
247 #define    PRS2_NEW_VARNO                       2
248
249 typedef struct Var
250 {
251         NodeTag         type;
252         Index           varno;                  /* index of this var's relation in the
253                                                                  * range table (could also be INNER or
254                                                                  * OUTER) */
255         AttrNumber      varattno;               /* attribute number of this var, or zero
256                                                                  * for all */
257         Oid                     vartype;                /* pg_type tuple OID for the type of this
258                                                                  * var */
259         int32           vartypmod;              /* pg_attribute typmod value */
260         Index           varlevelsup;
261
262         /*
263          * for subquery variables referencing outer relations; 0 in a normal
264          * var, >0 means N levels up
265          */
266         Index           varnoold;               /* original value of varno, for debugging */
267         AttrNumber      varoattno;              /* original value of varattno */
268 } Var;
269
270 /*
271  * Const
272  */
273 typedef struct Const
274 {
275         NodeTag         type;
276         Oid                     consttype;              /* PG_TYPE OID of the constant's datatype */
277         int                     constlen;               /* typlen of the constant's datatype */
278         Datum           constvalue;             /* the constant's value */
279         bool            constisnull;    /* whether the constant is null (if true,
280                                                                  * constvalue is undefined) */
281         bool            constbyval;             /* whether this datatype is passed by value.
282                                                                  * If true, then all the information is
283                                                                  * stored in the Datum.
284                                                                  * If false, then the Datum contains a
285                                                                  * pointer to the information. */
286 } Const;
287
288 /* ----------------
289  * Param
290  *              paramkind - specifies the kind of parameter. The possible values
291  *              for this field are specified in "params.h", and they are:
292  *
293  *              PARAM_NAMED: The parameter has a name, i.e. something
294  *                              like `$.salary' or `$.foobar'.
295  *                              In this case field `paramname' must be a valid name.
296  *
297  *              PARAM_NUM:       The parameter has only a numeric identifier,
298  *                              i.e. something like `$1', `$2' etc.
299  *                              The number is contained in the `paramid' field.
300  *
301  *              PARAM_EXEC:      The parameter is an internal executor parameter.
302  *                              It has a number contained in the `paramid' field.
303  *
304  * ----------------
305  */
306 typedef struct Param
307 {
308         NodeTag         type;
309         int                     paramkind;              /* kind of parameter. See above */
310         AttrNumber      paramid;                /* numeric ID for parameter ("$1") */
311         char       *paramname;          /* name for parameter ("$.foo") */
312         Oid                     paramtype;              /* PG_TYPE OID of parameter's datatype */
313 } Param;
314
315 /*
316  * Aggref
317  */
318 typedef struct Aggref
319 {
320         NodeTag         type;
321         Oid                     aggfnoid;               /* pg_proc Oid of the aggregate */
322         Oid                     aggtype;                /* type Oid of result of the aggregate */
323         Node       *target;                     /* expression we are aggregating on */
324         bool            aggstar;                /* TRUE if argument was really '*' */
325         bool            aggdistinct;    /* TRUE if it's agg(DISTINCT ...) */
326         int                     aggno;                  /* workspace for executor (see nodeAgg.c) */
327 } Aggref;
328
329 /* ----------------
330  * SubLink
331  *
332  * A SubLink represents a subselect appearing in an expression, and in some
333  * cases also the combining operator(s) just above it.  The subLinkType
334  * indicates the form of the expression represented:
335  *      EXISTS_SUBLINK          EXISTS(SELECT ...)
336  *      ALL_SUBLINK                     (lefthand) op ALL (SELECT ...)
337  *      ANY_SUBLINK                     (lefthand) op ANY (SELECT ...)
338  *      MULTIEXPR_SUBLINK       (lefthand) op (SELECT ...)
339  *      EXPR_SUBLINK            (SELECT with single targetlist item ...)
340  * For ALL, ANY, and MULTIEXPR, the lefthand is a list of expressions of the
341  * same length as the subselect's targetlist.  MULTIEXPR will *always* have
342  * a list with more than one entry; if the subselect has just one target
343  * then the parser will create an EXPR_SUBLINK instead (and any operator
344  * above the subselect will be represented separately).  Note that both
345  * MULTIEXPR and EXPR require the subselect to deliver only one row.
346  * ALL, ANY, and MULTIEXPR require the combining operators to deliver boolean
347  * results.  These are reduced to one result per row using OR or AND semantics
348  * depending on the "useor" flag.  ALL and ANY combine the per-row results
349  * using AND and OR semantics respectively.
350  *
351  * NOTE: lefthand and oper have varying meanings depending on where you look
352  * in the parse/plan pipeline:
353  * 1. gram.y delivers a list of the (untransformed) lefthand expressions in
354  *        lefthand, and sets oper to a single A_Expr (not a list!) containing
355  *        the string name of the operator, but no arguments.
356  * 2. The parser's expression transformation transforms lefthand normally,
357  *        and replaces oper with a list of Oper nodes, one per lefthand
358  *        expression.  These nodes represent the parser's resolution of exactly
359  *        which operator to apply to each pair of lefthand and targetlist
360  *        expressions.  However, we have not constructed actual Expr trees for
361  *        these operators yet.  This is the representation seen in saved rules
362  *        and in the rewriter.
363  * 3. Finally, the planner converts the oper list to a list of normal Expr
364  *        nodes representing the application of the operator(s) to the lefthand
365  *        expressions and values from the inner targetlist.  The inner
366  *        targetlist items are represented by placeholder Param nodes.
367  *        The lefthand field is set to NIL, since its expressions are now in
368  *        the Expr list.  This representation is passed to the executor.
369  *
370  * Planner routines that might see either representation 2 or 3 can tell
371  * the difference by checking whether lefthand is NIL or not.  Also,
372  * representation 2 appears in a "bare" SubLink, while representation 3 is
373  * found in SubLinks that are children of SubPlan nodes.
374  *
375  * In EXISTS and EXPR SubLinks, both lefthand and oper are unused and are
376  * always NIL.  useor is not significant either for these sublink types.
377  * ----------------
378  */
379 typedef enum SubLinkType
380 {
381         EXISTS_SUBLINK, ALL_SUBLINK, ANY_SUBLINK, MULTIEXPR_SUBLINK, EXPR_SUBLINK
382 } SubLinkType;
383
384
385 typedef struct SubLink
386 {
387         NodeTag         type;
388         SubLinkType subLinkType;        /* EXISTS, ALL, ANY, MULTIEXPR, EXPR */
389         bool            useor;                  /* TRUE to combine column results with
390                                                                  * "OR" not "AND" */
391         List       *lefthand;           /* list of outer-query expressions on the
392                                                                  * left */
393         List       *oper;                       /* list of Oper nodes for combining
394                                                                  * operators */
395         Node       *subselect;          /* subselect as Query* or parsetree */
396 } SubLink;
397
398 /* ----------------
399  *      ArrayRef: describes an array subscripting operation
400  *
401  * An ArrayRef can describe fetching a single element from an array,
402  * fetching a subarray (array slice), storing a single element into
403  * an array, or storing a slice.  The "store" cases work with an
404  * initial array value and a source value that is inserted into the
405  * appropriate part of the array; the result of the operation is an
406  * entire new modified array value.
407  *
408  * If reflowerindexpr = NIL, then we are fetching or storing a single array
409  * element at the subscripts given by refupperindexpr.  Otherwise we are
410  * fetching or storing an array slice, that is a rectangular subarray
411  * with lower and upper bounds given by the index expressions.
412  * reflowerindexpr must be the same length as refupperindexpr when it
413  * is not NIL.
414  *
415  * Note: array types can be fixed-length (refattrlength > 0), but only
416  * when the element type is itself fixed-length.  Otherwise they are
417  * varlena structures and have refattrlength = -1.      In any case,
418  * an array type is never pass-by-value.
419  *
420  * Note: refrestype is NOT the element type, but the array type,
421  * when doing subarray fetch or either type of store.  It might be a good
422  * idea to include a refelemtype field as well.
423  * ----------------
424  */
425 typedef struct ArrayRef
426 {
427         NodeTag         type;
428         Oid                     refrestype;             /* type of the result of the ArrayRef
429                                                                  * operation */
430         int                     refattrlength;  /* typlen of array type */
431         int                     refelemlength;  /* typlen of the array element type */
432         bool            refelembyval;   /* is the element type pass-by-value? */
433         char            refelemalign;   /* typalign of the element type */
434         List       *refupperindexpr;/* expressions that evaluate to upper
435                                                                  * array indexes */
436         List       *reflowerindexpr;/* expressions that evaluate to lower
437                                                                  * array indexes */
438         Node       *refexpr;            /* the expression that evaluates to an
439                                                                  * array value */
440         Node       *refassgnexpr;       /* expression for the source value, or
441                                                                  * NULL if fetch */
442 } ArrayRef;
443
444 /* ----------------
445  * FieldSelect
446  *
447  * FieldSelect represents the operation of extracting one field from a tuple
448  * value.  At runtime, the input expression is expected to yield a Datum
449  * that contains a pointer-to-TupleTableSlot.  The specified field number
450  * is extracted and returned as a Datum.
451  * ----------------
452  */
453
454 typedef struct FieldSelect
455 {
456         NodeTag         type;
457         Node       *arg;                        /* input expression */
458         AttrNumber      fieldnum;               /* attribute number of field to extract */
459         Oid                     resulttype;             /* type of the field (result type of this
460                                                                  * node) */
461         int32           resulttypmod;   /* output typmod (usually -1) */
462 } FieldSelect;
463
464 /* ----------------
465  * RelabelType
466  *
467  * RelabelType represents a "dummy" type coercion between two binary-
468  * compatible datatypes, such as reinterpreting the result of an OID
469  * expression as an int4.  It is a no-op at runtime; we only need it
470  * to provide a place to store the correct type to be attributed to
471  * the expression result during type resolution.  (We can't get away
472  * with just overwriting the type field of the input expression node,
473  * so we need a separate node to show the coercion's result type.)
474  * ----------------
475  */
476
477 typedef struct RelabelType
478 {
479         NodeTag         type;
480         Node       *arg;                        /* input expression */
481         Oid                     resulttype;             /* output type of coercion expression */
482         int32           resulttypmod;   /* output typmod (usually -1) */
483         CoercionForm relabelformat;     /* how to display this node */
484 } RelabelType;
485
486
487 /* ----------------------------------------------------------------
488  *                                      node types for join trees
489  *
490  * The leaves of a join tree structure are RangeTblRef nodes.  Above
491  * these, JoinExpr nodes can appear to denote a specific kind of join
492  * or qualified join.  Also, FromExpr nodes can appear to denote an
493  * ordinary cross-product join ("FROM foo, bar, baz WHERE ...").
494  * FromExpr is like a JoinExpr of jointype JOIN_INNER, except that it
495  * may have any number of child nodes, not just two.  Also, there is an
496  * implementation-defined difference: the planner is allowed to join the
497  * children of a FromExpr using whatever join order seems good to it.
498  * At present, JoinExpr nodes are always joined in exactly the order
499  * implied by the jointree structure (except the planner may choose to
500  * swap inner and outer members of a join pair).
501  *
502  * NOTE: the top level of a Query's jointree is always a FromExpr.
503  * Even if the jointree contains no rels, there will be a FromExpr.
504  *
505  * NOTE: the qualification expressions present in JoinExpr nodes are
506  * *in addition to* the query's main WHERE clause, which appears as the
507  * qual of the top-level FromExpr.      The reason for associating quals with
508  * specific nodes in the jointree is that the position of a qual is critical
509  * when outer joins are present.  (If we enforce a qual too soon or too late,
510  * that may cause the outer join to produce the wrong set of NULL-extended
511  * rows.)  If all joins are inner joins then all the qual positions are
512  * semantically interchangeable.
513  *
514  * NOTE: in the raw output of gram.y, a join tree contains RangeVar,
515  * RangeSubselect, and RangeFunction nodes, which are all replaced by
516  * RangeTblRef nodes during the parse analysis phase.  Also, the top-level
517  * FromExpr is added during parse analysis; the grammar regards FROM and
518  * WHERE as separate.
519  * ----------------------------------------------------------------
520  */
521
522 /*
523  * RangeTblRef - reference to an entry in the query's rangetable
524  *
525  * We could use direct pointers to the RT entries and skip having these
526  * nodes, but multiple pointers to the same node in a querytree cause
527  * lots of headaches, so it seems better to store an index into the RT.
528  */
529 typedef struct RangeTblRef
530 {
531         NodeTag         type;
532         int                     rtindex;
533 } RangeTblRef;
534
535 /*----------
536  * JoinExpr - for SQL JOIN expressions
537  *
538  * isNatural, using, and quals are interdependent.      The user can write only
539  * one of NATURAL, USING(), or ON() (this is enforced by the grammar).
540  * If he writes NATURAL then parse analysis generates the equivalent USING()
541  * list, and from that fills in "quals" with the right equality comparisons.
542  * If he writes USING() then "quals" is filled with equality comparisons.
543  * If he writes ON() then only "quals" is set.  Note that NATURAL/USING
544  * are not equivalent to ON() since they also affect the output column list.
545  *
546  * alias is an Alias node representing the AS alias-clause attached to the
547  * join expression, or NULL if no clause.  NB: presence or absence of the
548  * alias has a critical impact on semantics, because a join with an alias
549  * restricts visibility of the tables/columns inside it.
550  *
551  * During parse analysis, an RTE is created for the Join, and its index
552  * is filled into rtindex.      This RTE is present mainly so that Vars can
553  * be created that refer to the outputs of the join.
554  *----------
555  */
556 typedef struct JoinExpr
557 {
558         NodeTag         type;
559         JoinType        jointype;               /* type of join */
560         bool            isNatural;              /* Natural join? Will need to shape table */
561         Node       *larg;                       /* left subtree */
562         Node       *rarg;                       /* right subtree */
563         List       *using;                      /* USING clause, if any (list of String) */
564         Node       *quals;                      /* qualifiers on join, if any */
565         Alias      *alias;                      /* user-written alias clause, if any */
566         int                     rtindex;                /* RT index assigned for join */
567 } JoinExpr;
568
569 /*----------
570  * FromExpr - represents a FROM ... WHERE ... construct
571  *
572  * This is both more flexible than a JoinExpr (it can have any number of
573  * children, including zero) and less so --- we don't need to deal with
574  * aliases and so on.  The output column set is implicitly just the union
575  * of the outputs of the children.
576  *----------
577  */
578 typedef struct FromExpr
579 {
580         NodeTag         type;
581         List       *fromlist;           /* List of join subtrees */
582         Node       *quals;                      /* qualifiers on join, if any */
583 } FromExpr;
584
585 #endif   /* PRIMNODES_H */