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  * Portions Copyright (c) 2003-2019, PgPool Global Development Group *
10  * Portions Copyright (c) 1996-2019, 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 "pg_list.h"
21 
22 
23 /* ----------------------------------------------------------------
24  *						node definitions
25  * ----------------------------------------------------------------
26  */
27 
28 /*
29  * include/nodes/bitmapset.h start
30  */
31 typedef uint32 bitmapword;		/* must be an unsigned type */
32 
33 typedef struct Bitmapset
34 {
35 	int			nwords;			/* number of words in array */
36 	bitmapword	words[1];		/* really [nwords] */
37 } Bitmapset;					/* VARIABLE LENGTH STRUCT */
38 
39 extern Bitmapset *bms_copy(const Bitmapset *a);
40 
41 /* include/nodes/bitmapset.h end */
42 
43 /*
44  * Alias -
45  *	  specifies an alias for a range variable; the alias might also
46  *	  specify renaming of columns within the table.
47  *
48  * Note: colnames is a list of Value nodes (always strings).  In Alias structs
49  * associated with RTEs, there may be entries corresponding to dropped
50  * columns; these are normally empty strings ("").  See parsenodes.h for info.
51  */
52 typedef struct Alias
53 {
54 	NodeTag		type;
55 	char	   *aliasname;		/* aliased rel name (never qualified) */
56 	List	   *colnames;		/* optional list of column aliases */
57 } Alias;
58 
59 /* What to do at commit time for temporary relations */
60 typedef enum OnCommitAction
61 {
62 	ONCOMMIT_NOOP,				/* No ON COMMIT clause (do nothing) */
63 	ONCOMMIT_PRESERVE_ROWS,		/* ON COMMIT PRESERVE ROWS (do nothing) */
64 	ONCOMMIT_DELETE_ROWS,		/* ON COMMIT DELETE ROWS */
65 	ONCOMMIT_DROP				/* ON COMMIT DROP */
66 } OnCommitAction;
67 
68 /*
69  * RangeVar - range variable, used in FROM clauses
70  *
71  * Also used to represent table names in utility statements; there, the alias
72  * field is not used, and inh tells whether to apply the operation
73  * recursively to child tables.  In some contexts it is also useful to carry
74  * a TEMP table indication here.
75  */
76 typedef struct RangeVar
77 {
78 	NodeTag		type;
79 	char	   *catalogname;	/* the catalog (database) name, or NULL */
80 	char	   *schemaname;		/* the schema name, or NULL */
81 	char	   *relname;		/* the relation/sequence name */
82 	bool		inh;			/* expand rel by inheritance? recursively act
83 								 * on children? */
84 	char		relpersistence; /* see RELPERSISTENCE_* in pg_class.h */
85 	Alias	   *alias;			/* table alias & optional column aliases */
86 	int			location;		/* token location, or -1 if unknown */
87 } RangeVar;
88 
89 /*
90  * TableFunc - node for a table function, such as XMLTABLE.
91  *
92  * Entries in the ns_names list are either string Value nodes containing
93  * literal namespace names, or NULL pointers to represent DEFAULT.
94  */
95 typedef struct TableFunc
96 {
97 	NodeTag		type;
98 	List	   *ns_uris;		/* list of namespace URI expressions */
99 	List	   *ns_names;		/* list of namespace names or NULL */
100 	Node	   *docexpr;		/* input document expression */
101 	Node	   *rowexpr;		/* row filter expression */
102 	List	   *colnames;		/* column names (list of String) */
103 	List	   *coltypes;		/* OID list of column type OIDs */
104 	List	   *coltypmods;		/* integer list of column typmods */
105 	List	   *colcollations;	/* OID list of column collation OIDs */
106 	List	   *colexprs;		/* list of column filter expressions */
107 	List	   *coldefexprs;	/* list of column default expressions */
108 	Bitmapset  *notnulls;		/* nullability flag for each output column */
109 	int			ordinalitycol;	/* counts from 0; -1 if none specified */
110 	int			location;		/* token location, or -1 if unknown */
111 } TableFunc;
112 
113 /*
114  * IntoClause - target information for SELECT INTO, CREATE TABLE AS, and
115  * CREATE MATERIALIZED VIEW
116  *
117  * For CREATE MATERIALIZED VIEW, viewQuery is the parsed-but-not-rewritten
118  * SELECT Query for the view; otherwise it's NULL.  (Although it's actually
119  * Query*, we declare it as Node* to avoid a forward reference.)
120  */
121 typedef struct IntoClause
122 {
123 	NodeTag		type;
124 
125 	RangeVar   *rel;			/* target relation name */
126 	List	   *colNames;		/* column names to assign, or NIL */
127 	char	   *accessMethod;	/* table access method */
128 	List	   *options;		/* options from WITH clause */
129 	OnCommitAction onCommit;	/* what do we do at COMMIT? */
130 	char	   *tableSpaceName; /* table space to use, or NULL */
131 	Node	   *viewQuery;		/* materialized view's SELECT query */
132 	bool		skipData;		/* true for WITH NO DATA */
133 } IntoClause;
134 
135 
136 /* ----------------------------------------------------------------
137  *					node types for executable expressions
138  * ----------------------------------------------------------------
139  */
140 
141 /*
142  * Expr - generic superclass for executable-expression nodes
143  *
144  * All node types that are used in executable expression trees should derive
145  * from Expr (that is, have Expr as their first field).  Since Expr only
146  * contains NodeTag, this is a formality, but it is an easy form of
147  * documentation.  See also the ExprState node types in execnodes.h.
148  */
149 typedef struct Expr
150 {
151 	NodeTag		type;
152 } Expr;
153 
154 /*
155  * Var - expression node representing a variable (ie, a table column)
156  *
157  * Note: during parsing/planning, varnoold/varoattno are always just copies
158  * of varno/varattno.  At the tail end of planning, Var nodes appearing in
159  * upper-level plan nodes are reassigned to point to the outputs of their
160  * subplans; for example, in a join node varno becomes INNER_VAR or OUTER_VAR
161  * and varattno becomes the index of the proper element of that subplan's
162  * target list.  Similarly, INDEX_VAR is used to identify Vars that reference
163  * an index column rather than a heap column.  (In ForeignScan and CustomScan
164  * plan nodes, INDEX_VAR is abused to signify references to columns of a
165  * custom scan tuple type.)  In all these cases, varnoold/varoattno hold the
166  * original values.  The code doesn't really need varnoold/varoattno, but they
167  * are very useful for debugging and interpreting completed plans, so we keep
168  * them around.
169  */
170 #define    INNER_VAR		65000	/* reference to inner subplan */
171 #define    OUTER_VAR		65001	/* reference to outer subplan */
172 #define    INDEX_VAR		65002	/* reference to index column */
173 
174 #define IS_SPECIAL_VARNO(varno)		((varno) >= INNER_VAR)
175 
176 /* Symbols for the indexes of the special RTE entries in rules */
177 #define    PRS2_OLD_VARNO			1
178 #define    PRS2_NEW_VARNO			2
179 
180 typedef struct Var
181 {
182 	Expr		xpr;
183 	Index		varno;			/* index of this var's relation in the range
184 								 * table, or INNER_VAR/OUTER_VAR/INDEX_VAR */
185 	AttrNumber	varattno;		/* attribute number of this var, or zero for
186 								 * all attrs ("whole-row Var") */
187 	Oid			vartype;		/* pg_type OID for the type of this var */
188 	int32		vartypmod;		/* pg_attribute typmod value */
189 	Oid			varcollid;		/* OID of collation, or InvalidOid if none */
190 	Index		varlevelsup;	/* for subquery variables referencing outer
191 								 * relations; 0 in a normal var, >0 means N
192 								 * levels up */
193 	Index		varnoold;		/* original value of varno, for debugging */
194 	AttrNumber	varoattno;		/* original value of varattno */
195 	int			location;		/* token location, or -1 if unknown */
196 } Var;
197 
198 /*
199  * Const
200  *
201  * Note: for varlena data types, we make a rule that a Const node's value
202  * must be in non-extended form (4-byte header, no compression or external
203  * references).  This ensures that the Const node is self-contained and makes
204  * it more likely that equal() will see logically identical values as equal.
205  */
206 typedef struct Const
207 {
208 	Expr		xpr;
209 	Oid			consttype;		/* pg_type OID of the constant's datatype */
210 	int32		consttypmod;	/* typmod value, if any */
211 	Oid			constcollid;	/* OID of collation, or InvalidOid if none */
212 	int			constlen;		/* typlen of the constant's datatype */
213 	Datum		constvalue;		/* the constant's value */
214 	bool		constisnull;	/* whether the constant is null (if true,
215 								 * constvalue is undefined) */
216 	bool		constbyval;		/* whether this datatype is passed by value.
217 								 * If true, then all the information is stored
218 								 * in the Datum. If false, then the Datum
219 								 * contains a pointer to the information. */
220 	int			location;		/* token location, or -1 if unknown */
221 } Const;
222 
223 /*
224  * Param
225  *
226  *		paramkind specifies the kind of parameter. The possible values
227  *		for this field are:
228  *
229  *		PARAM_EXTERN:  The parameter value is supplied from outside the plan.
230  *				Such parameters are numbered from 1 to n.
231  *
232  *		PARAM_EXEC:  The parameter is an internal executor parameter, used
233  *				for passing values into and out of sub-queries or from
234  *				nestloop joins to their inner scans.
235  *				For historical reasons, such parameters are numbered from 0.
236  *				These numbers are independent of PARAM_EXTERN numbers.
237  *
238  *		PARAM_SUBLINK:	The parameter represents an output column of a SubLink
239  *				node's sub-select.  The column number is contained in the
240  *				`paramid' field.  (This type of Param is converted to
241  *				PARAM_EXEC during planning.)
242  *
243  *		PARAM_MULTIEXPR:  Like PARAM_SUBLINK, the parameter represents an
244  *				output column of a SubLink node's sub-select, but here, the
245  *				SubLink is always a MULTIEXPR SubLink.  The high-order 16 bits
246  *				of the `paramid' field contain the SubLink's subLinkId, and
247  *				the low-order 16 bits contain the column number.  (This type
248  *				of Param is also converted to PARAM_EXEC during planning.)
249  */
250 typedef enum ParamKind
251 {
252 	PARAM_EXTERN,
253 	PARAM_EXEC,
254 	PARAM_SUBLINK,
255 	PARAM_MULTIEXPR
256 } ParamKind;
257 
258 typedef struct Param
259 {
260 	Expr		xpr;
261 	ParamKind	paramkind;		/* kind of parameter. See above */
262 	int			paramid;		/* numeric ID for parameter */
263 	Oid			paramtype;		/* pg_type OID of parameter's datatype */
264 	int32		paramtypmod;	/* typmod value, if known */
265 	Oid			paramcollid;	/* OID of collation, or InvalidOid if none */
266 	int			location;		/* token location, or -1 if unknown */
267 } Param;
268 
269 /*
270  * Aggref
271  *
272  * The aggregate's args list is a targetlist, ie, a list of TargetEntry nodes.
273  *
274  * For a normal (non-ordered-set) aggregate, the non-resjunk TargetEntries
275  * represent the aggregate's regular arguments (if any) and resjunk TLEs can
276  * be added at the end to represent ORDER BY expressions that are not also
277  * arguments.  As in a top-level Query, the TLEs can be marked with
278  * ressortgroupref indexes to let them be referenced by SortGroupClause
279  * entries in the aggorder and/or aggdistinct lists.  This represents ORDER BY
280  * and DISTINCT operations to be applied to the aggregate input rows before
281  * they are passed to the transition function.  The grammar only allows a
282  * simple "DISTINCT" specifier for the arguments, but we use the full
283  * query-level representation to allow more code sharing.
284  *
285  * For an ordered-set aggregate, the args list represents the WITHIN GROUP
286  * (aggregated) arguments, all of which will be listed in the aggorder list.
287  * DISTINCT is not supported in this case, so aggdistinct will be NIL.
288  * The direct arguments appear in aggdirectargs (as a list of plain
289  * expressions, not TargetEntry nodes).
290  *
291  * aggtranstype is the data type of the state transition values for this
292  * aggregate (resolved to an actual type, if agg's transtype is polymorphic).
293  * This is determined during planning and is InvalidOid before that.
294  *
295  * aggargtypes is an OID list of the data types of the direct and regular
296  * arguments.  Normally it's redundant with the aggdirectargs and args lists,
297  * but in a combining aggregate, it's not because the args list has been
298  * replaced with a single argument representing the partial-aggregate
299  * transition values.
300  *
301  * aggsplit indicates the expected partial-aggregation mode for the Aggref's
302  * parent plan node.  It's always set to AGGSPLIT_SIMPLE in the parser, but
303  * the planner might change it to something else.  We use this mainly as
304  * a crosscheck that the Aggrefs match the plan; but note that when aggsplit
305  * indicates a non-final mode, aggtype reflects the transition data type
306  * not the SQL-level output type of the aggregate.
307  */
308 typedef struct Aggref
309 {
310 	Expr		xpr;
311 	Oid			aggfnoid;		/* pg_proc Oid of the aggregate */
312 	Oid			aggtype;		/* type Oid of result of the aggregate */
313 	Oid			aggcollid;		/* OID of collation of result */
314 	Oid			inputcollid;	/* OID of collation that function should use */
315 	Oid			aggtranstype;	/* type Oid of aggregate's transition value */
316 	List	   *aggargtypes;	/* type Oids of direct and aggregated args */
317 	List	   *aggdirectargs;	/* direct arguments, if an ordered-set agg */
318 	List	   *args;			/* aggregated arguments and sort expressions */
319 	List	   *aggorder;		/* ORDER BY (list of SortGroupClause) */
320 	List	   *aggdistinct;	/* DISTINCT (list of SortGroupClause) */
321 	Expr	   *aggfilter;		/* FILTER expression, if any */
322 	bool		aggstar;		/* true if argument list was really '*' */
323 	bool		aggvariadic;	/* true if variadic arguments have been
324 								 * combined into an array last argument */
325 	char		aggkind;		/* aggregate kind (see pg_aggregate.h) */
326 	Index		agglevelsup;	/* > 0 if agg belongs to outer query */
327 	AggSplit	aggsplit;		/* expected agg-splitting mode of parent Agg */
328 	int			location;		/* token location, or -1 if unknown */
329 } Aggref;
330 
331 /*
332  * GroupingFunc
333  *
334  * A GroupingFunc is a GROUPING(...) expression, which behaves in many ways
335  * like an aggregate function (e.g. it "belongs" to a specific query level,
336  * which might not be the one immediately containing it), but also differs in
337  * an important respect: it never evaluates its arguments, they merely
338  * designate expressions from the GROUP BY clause of the query level to which
339  * it belongs.
340  *
341  * The spec defines the evaluation of GROUPING() purely by syntactic
342  * replacement, but we make it a real expression for optimization purposes so
343  * that one Agg node can handle multiple grouping sets at once.  Evaluating the
344  * result only needs the column positions to check against the grouping set
345  * being projected.  However, for EXPLAIN to produce meaningful output, we have
346  * to keep the original expressions around, since expression deparse does not
347  * give us any feasible way to get at the GROUP BY clause.
348  *
349  * Also, we treat two GroupingFunc nodes as equal if they have equal arguments
350  * lists and agglevelsup, without comparing the refs and cols annotations.
351  *
352  * In raw parse output we have only the args list; parse analysis fills in the
353  * refs list, and the planner fills in the cols list.
354  */
355 typedef struct GroupingFunc
356 {
357 	Expr		xpr;
358 	List	   *args;			/* arguments, not evaluated but kept for
359 								 * benefit of EXPLAIN etc. */
360 	List	   *refs;			/* ressortgrouprefs of arguments */
361 	List	   *cols;			/* actual column positions set by planner */
362 	Index		agglevelsup;	/* same as Aggref.agglevelsup */
363 	int			location;		/* token location */
364 } GroupingFunc;
365 
366 /*
367  * WindowFunc
368  */
369 typedef struct WindowFunc
370 {
371 	Expr		xpr;
372 	Oid			winfnoid;		/* pg_proc Oid of the function */
373 	Oid			wintype;		/* type Oid of result of the window function */
374 	Oid			wincollid;		/* OID of collation of result */
375 	Oid			inputcollid;	/* OID of collation that function should use */
376 	List	   *args;			/* arguments to the window function */
377 	Expr	   *aggfilter;		/* FILTER expression, if any */
378 	Index		winref;			/* index of associated WindowClause */
379 	bool		winstar;		/* true if argument list was really '*' */
380 	bool		winagg;			/* is function a simple aggregate? */
381 	int			location;		/* token location, or -1 if unknown */
382 } WindowFunc;
383 
384 /* ----------------
385  *	SubscriptingRef: describes a subscripting operation over a container
386  *			(array, etc).
387  *
388  * A SubscriptingRef can describe fetching a single element from a container,
389  * fetching a part of container (e.g. array slice), storing a single element into
390  * a container, or storing a slice.  The "store" cases work with an
391  * initial container value and a source value that is inserted into the
392  * appropriate part of the container; the result of the operation is an
393  * entire new modified container value.
394  *
395  * If reflowerindexpr = NIL, then we are fetching or storing a single container
396  * element at the subscripts given by refupperindexpr. Otherwise we are
397  * fetching or storing a container slice, that is a rectangular subcontainer
398  * with lower and upper bounds given by the index expressions.
399  * reflowerindexpr must be the same length as refupperindexpr when it
400  * is not NIL.
401  *
402  * In the slice case, individual expressions in the subscript lists can be
403  * NULL, meaning "substitute the array's current lower or upper bound".
404  *
405  * Note: the result datatype is the element type when fetching a single
406  * element; but it is the array type when doing subarray fetch or either
407  * type of store.
408  *
409  * Note: for the cases where a container is returned, if refexpr yields a R/W
410  * expanded container, then the implementation is allowed to modify that object
411  * in-place and return the same object.)
412  * ----------------
413  */
414 typedef struct SubscriptingRef
415 {
416 	Expr		xpr;
417 	Oid			refcontainertype;	/* type of the container proper */
418 	Oid			refelemtype;	/* type of the container elements */
419 	int32		reftypmod;		/* typmod of the container (and elements too) */
420 	Oid			refcollid;		/* OID of collation, or InvalidOid if none */
421 	List	   *refupperindexpr;	/* expressions that evaluate to upper
422 									 * container indexes */
423 	List	   *reflowerindexpr;	/* expressions that evaluate to lower
424 									 * container indexes, or NIL for single
425 									 * container element */
426 	Expr	   *refexpr;		/* the expression that evaluates to a
427 								 * container value */
428 
429 	Expr	   *refassgnexpr;	/* expression for the source value, or NULL if
430 								 * fetch */
431 } SubscriptingRef;
432 
433 /*
434  * CoercionContext - distinguishes the allowed set of type casts
435  *
436  * NB: ordering of the alternatives is significant; later (larger) values
437  * allow more casts than earlier ones.
438  */
439 typedef enum CoercionContext
440 {
441 	COERCION_IMPLICIT,			/* coercion in context of expression */
442 	COERCION_ASSIGNMENT,		/* coercion in context of assignment */
443 	COERCION_EXPLICIT			/* explicit cast operation */
444 } CoercionContext;
445 
446 /*
447  * CoercionForm - how to display a node that could have come from a cast
448  *
449  * NB: equal() ignores CoercionForm fields, therefore this *must* not carry
450  * any semantically significant information.  We need that behavior so that
451  * the planner will consider equivalent implicit and explicit casts to be
452  * equivalent.  In cases where those actually behave differently, the coercion
453  * function's arguments will be different.
454  */
455 typedef enum CoercionForm
456 {
457 	COERCE_EXPLICIT_CALL,		/* display as a function call */
458 	COERCE_EXPLICIT_CAST,		/* display as an explicit cast */
459 	COERCE_IMPLICIT_CAST		/* implicit cast, so hide it */
460 } CoercionForm;
461 
462 /*
463  * FuncExpr - expression node for a function call
464  */
465 typedef struct FuncExpr
466 {
467 	Expr		xpr;
468 	Oid			funcid;			/* PG_PROC OID of the function */
469 	Oid			funcresulttype; /* PG_TYPE OID of result value */
470 	bool		funcretset;		/* true if function returns set */
471 	bool		funcvariadic;	/* true if variadic arguments have been
472 								 * combined into an array last argument */
473 	CoercionForm funcformat;	/* how to display this function call */
474 	Oid			funccollid;		/* OID of collation of result */
475 	Oid			inputcollid;	/* OID of collation that function should use */
476 	List	   *args;			/* arguments to the function */
477 	int			location;		/* token location, or -1 if unknown */
478 } FuncExpr;
479 
480 /*
481  * NamedArgExpr - a named argument of a function
482  *
483  * This node type can only appear in the args list of a FuncCall or FuncExpr
484  * node.  We support pure positional call notation (no named arguments),
485  * named notation (all arguments are named), and mixed notation (unnamed
486  * arguments followed by named ones).
487  *
488  * Parse analysis sets argnumber to the positional index of the argument,
489  * but doesn't rearrange the argument list.
490  *
491  * The planner will convert argument lists to pure positional notation
492  * during expression preprocessing, so execution never sees a NamedArgExpr.
493  */
494 typedef struct NamedArgExpr
495 {
496 	Expr		xpr;
497 	Expr	   *arg;			/* the argument expression */
498 	char	   *name;			/* the name */
499 	int			argnumber;		/* argument's number in positional notation */
500 	int			location;		/* argument name location, or -1 if unknown */
501 } NamedArgExpr;
502 
503 /*
504  * OpExpr - expression node for an operator invocation
505  *
506  * Semantically, this is essentially the same as a function call.
507  *
508  * Note that opfuncid is not necessarily filled in immediately on creation
509  * of the node.  The planner makes sure it is valid before passing the node
510  * tree to the executor, but during parsing/planning opfuncid can be 0.
511  */
512 typedef struct OpExpr
513 {
514 	Expr		xpr;
515 	Oid			opno;			/* PG_OPERATOR OID of the operator */
516 	Oid			opfuncid;		/* PG_PROC OID of underlying function */
517 	Oid			opresulttype;	/* PG_TYPE OID of result value */
518 	bool		opretset;		/* true if operator returns set */
519 	Oid			opcollid;		/* OID of collation of result */
520 	Oid			inputcollid;	/* OID of collation that operator should use */
521 	List	   *args;			/* arguments to the operator (1 or 2) */
522 	int			location;		/* token location, or -1 if unknown */
523 } OpExpr;
524 
525 /*
526  * DistinctExpr - expression node for "x IS DISTINCT FROM y"
527  *
528  * Except for the nodetag, this is represented identically to an OpExpr
529  * referencing the "=" operator for x and y.
530  * We use "=", not the more obvious "<>", because more datatypes have "="
531  * than "<>".  This means the executor must invert the operator result.
532  * Note that the operator function won't be called at all if either input
533  * is NULL, since then the result can be determined directly.
534  */
535 typedef OpExpr DistinctExpr;
536 
537 /*
538  * NullIfExpr - a NULLIF expression
539  *
540  * Like DistinctExpr, this is represented the same as an OpExpr referencing
541  * the "=" operator for x and y.
542  */
543 typedef OpExpr NullIfExpr;
544 
545 /*
546  * ScalarArrayOpExpr - expression node for "scalar op ANY/ALL (array)"
547  *
548  * The operator must yield boolean.  It is applied to the left operand
549  * and each element of the righthand array, and the results are combined
550  * with OR or AND (for ANY or ALL respectively).  The node representation
551  * is almost the same as for the underlying operator, but we need a useOr
552  * flag to remember whether it's ANY or ALL, and we don't have to store
553  * the result type (or the collation) because it must be boolean.
554  */
555 typedef struct ScalarArrayOpExpr
556 {
557 	Expr		xpr;
558 	Oid			opno;			/* PG_OPERATOR OID of the operator */
559 	Oid			opfuncid;		/* PG_PROC OID of underlying function */
560 	bool		useOr;			/* true for ANY, false for ALL */
561 	Oid			inputcollid;	/* OID of collation that operator should use */
562 	List	   *args;			/* the scalar and array operands */
563 	int			location;		/* token location, or -1 if unknown */
564 } ScalarArrayOpExpr;
565 
566 /*
567  * BoolExpr - expression node for the basic Boolean operators AND, OR, NOT
568  *
569  * Notice the arguments are given as a List.  For NOT, of course the list
570  * must always have exactly one element.  For AND and OR, there can be two
571  * or more arguments.
572  */
573 typedef enum BoolExprType
574 {
575 	AND_EXPR, OR_EXPR, NOT_EXPR
576 } BoolExprType;
577 
578 typedef struct BoolExpr
579 {
580 	Expr		xpr;
581 	BoolExprType boolop;
582 	List	   *args;			/* arguments to this expression */
583 	int			location;		/* token location, or -1 if unknown */
584 } BoolExpr;
585 
586 /*
587  * SubLink
588  *
589  * A SubLink represents a subselect appearing in an expression, and in some
590  * cases also the combining operator(s) just above it.  The subLinkType
591  * indicates the form of the expression represented:
592  *	EXISTS_SUBLINK		EXISTS(SELECT ...)
593  *	ALL_SUBLINK			(lefthand) op ALL (SELECT ...)
594  *	ANY_SUBLINK			(lefthand) op ANY (SELECT ...)
595  *	ROWCOMPARE_SUBLINK	(lefthand) op (SELECT ...)
596  *	EXPR_SUBLINK		(SELECT with single targetlist item ...)
597  *	MULTIEXPR_SUBLINK	(SELECT with multiple targetlist items ...)
598  *	ARRAY_SUBLINK		ARRAY(SELECT with single targetlist item ...)
599  *	CTE_SUBLINK			WITH query (never actually part of an expression)
600  * For ALL, ANY, and ROWCOMPARE, the lefthand is a list of expressions of the
601  * same length as the subselect's targetlist.  ROWCOMPARE will *always* have
602  * a list with more than one entry; if the subselect has just one target
603  * then the parser will create an EXPR_SUBLINK instead (and any operator
604  * above the subselect will be represented separately).
605  * ROWCOMPARE, EXPR, and MULTIEXPR require the subselect to deliver at most
606  * one row (if it returns no rows, the result is NULL).
607  * ALL, ANY, and ROWCOMPARE require the combining operators to deliver boolean
608  * results.  ALL and ANY combine the per-row results using AND and OR
609  * semantics respectively.
610  * ARRAY requires just one target column, and creates an array of the target
611  * column's type using any number of rows resulting from the subselect.
612  *
613  * SubLink is classed as an Expr node, but it is not actually executable;
614  * it must be replaced in the expression tree by a SubPlan node during
615  * planning.
616  *
617  * NOTE: in the raw output of gram.y, testexpr contains just the raw form
618  * of the lefthand expression (if any), and operName is the String name of
619  * the combining operator.  Also, subselect is a raw parsetree.  During parse
620  * analysis, the parser transforms testexpr into a complete boolean expression
621  * that compares the lefthand value(s) to PARAM_SUBLINK nodes representing the
622  * output columns of the subselect.  And subselect is transformed to a Query.
623  * This is the representation seen in saved rules and in the rewriter.
624  *
625  * In EXISTS, EXPR, MULTIEXPR, and ARRAY SubLinks, testexpr and operName
626  * are unused and are always null.
627  *
628  * subLinkId is currently used only for MULTIEXPR SubLinks, and is zero in
629  * other SubLinks.  This number identifies different multiple-assignment
630  * subqueries within an UPDATE statement's SET list.  It is unique only
631  * within a particular targetlist.  The output column(s) of the MULTIEXPR
632  * are referenced by PARAM_MULTIEXPR Params appearing elsewhere in the tlist.
633  *
634  * The CTE_SUBLINK case never occurs in actual SubLink nodes, but it is used
635  * in SubPlans generated for WITH subqueries.
636  */
637 typedef enum SubLinkType
638 {
639 	EXISTS_SUBLINK,
640 	ALL_SUBLINK,
641 	ANY_SUBLINK,
642 	ROWCOMPARE_SUBLINK,
643 	EXPR_SUBLINK,
644 	MULTIEXPR_SUBLINK,
645 	ARRAY_SUBLINK,
646 	CTE_SUBLINK					/* for SubPlans only */
647 } SubLinkType;
648 
649 
650 typedef struct SubLink
651 {
652 	Expr		xpr;
653 	SubLinkType subLinkType;	/* see above */
654 	int			subLinkId;		/* ID (1..n); 0 if not MULTIEXPR */
655 	Node	   *testexpr;		/* outer-query test for ALL/ANY/ROWCOMPARE */
656 	List	   *operName;		/* originally specified operator name */
657 	Node	   *subselect;		/* subselect as Query* or raw parsetree */
658 	int			location;		/* token location, or -1 if unknown */
659 } SubLink;
660 
661 /*
662  * SubPlan - executable expression node for a subplan (sub-SELECT)
663  *
664  * The planner replaces SubLink nodes in expression trees with SubPlan
665  * nodes after it has finished planning the subquery.  SubPlan references
666  * a sub-plantree stored in the subplans list of the toplevel PlannedStmt.
667  * (We avoid a direct link to make it easier to copy expression trees
668  * without causing multiple processing of the subplan.)
669  *
670  * In an ordinary subplan, testexpr points to an executable expression
671  * (OpExpr, an AND/OR tree of OpExprs, or RowCompareExpr) for the combining
672  * operator(s); the left-hand arguments are the original lefthand expressions,
673  * and the right-hand arguments are PARAM_EXEC Param nodes representing the
674  * outputs of the sub-select.  (NOTE: runtime coercion functions may be
675  * inserted as well.)  This is just the same expression tree as testexpr in
676  * the original SubLink node, but the PARAM_SUBLINK nodes are replaced by
677  * suitably numbered PARAM_EXEC nodes.
678  *
679  * If the sub-select becomes an initplan rather than a subplan, the executable
680  * expression is part of the outer plan's expression tree (and the SubPlan
681  * node itself is not, but rather is found in the outer plan's initPlan
682  * list).  In this case testexpr is NULL to avoid duplication.
683  *
684  * The planner also derives lists of the values that need to be passed into
685  * and out of the subplan.  Input values are represented as a list "args" of
686  * expressions to be evaluated in the outer-query context (currently these
687  * args are always just Vars, but in principle they could be any expression).
688  * The values are assigned to the global PARAM_EXEC params indexed by parParam
689  * (the parParam and args lists must have the same ordering).  setParam is a
690  * list of the PARAM_EXEC params that are computed by the sub-select, if it
691  * is an initplan; they are listed in order by sub-select output column
692  * position.  (parParam and setParam are integer Lists, not Bitmapsets,
693  * because their ordering is significant.)
694  *
695  * Also, the planner computes startup and per-call costs for use of the
696  * SubPlan.  Note that these include the cost of the subquery proper,
697  * evaluation of the testexpr if any, and any hashtable management overhead.
698  */
699 typedef struct SubPlan
700 {
701 	Expr		xpr;
702 	/* Fields copied from original SubLink: */
703 	SubLinkType subLinkType;	/* see above */
704 	/* The combining operators, transformed to an executable expression: */
705 	Node	   *testexpr;		/* OpExpr or RowCompareExpr expression tree */
706 	List	   *paramIds;		/* IDs of Params embedded in the above */
707 	/* Identification of the Plan tree to use: */
708 	int			plan_id;		/* Index (from 1) in PlannedStmt.subplans */
709 	/* Identification of the SubPlan for EXPLAIN and debugging purposes: */
710 	char	   *plan_name;		/* A name assigned during planning */
711 	/* Extra data useful for determining subplan's output type: */
712 	Oid			firstColType;	/* Type of first column of subplan result */
713 	int32		firstColTypmod; /* Typmod of first column of subplan result */
714 	Oid			firstColCollation;	/* Collation of first column of subplan
715 									 * result */
716 	/* Information about execution strategy: */
717 	bool		useHashTable;	/* true to store subselect output in a hash
718 								 * table (implies we are doing "IN") */
719 	bool		unknownEqFalse; /* true if it's okay to return FALSE when the
720 								 * spec result is UNKNOWN; this allows much
721 								 * simpler handling of null values */
722 	bool		parallel_safe;	/* is the subplan parallel-safe? */
723 	/* Note: parallel_safe does not consider contents of testexpr or args */
724 	/* Information for passing params into and out of the subselect: */
725 	/* setParam and parParam are lists of integers (param IDs) */
726 	List	   *setParam;		/* initplan subqueries have to set these
727 								 * Params for parent plan */
728 	List	   *parParam;		/* indices of input Params from parent plan */
729 	List	   *args;			/* exprs to pass as parParam values */
730 	/* Estimated execution costs: */
731 	Cost		startup_cost;	/* one-time setup cost */
732 	Cost		per_call_cost;	/* cost for each subplan evaluation */
733 } SubPlan;
734 
735 /*
736  * AlternativeSubPlan - expression node for a choice among SubPlans
737  *
738  * The subplans are given as a List so that the node definition need not
739  * change if there's ever more than two alternatives.  For the moment,
740  * though, there are always exactly two; and the first one is the fast-start
741  * plan.
742  */
743 typedef struct AlternativeSubPlan
744 {
745 	Expr		xpr;
746 	List	   *subplans;		/* SubPlan(s) with equivalent results */
747 } AlternativeSubPlan;
748 
749 /* ----------------
750  * FieldSelect
751  *
752  * FieldSelect represents the operation of extracting one field from a tuple
753  * value.  At runtime, the input expression is expected to yield a rowtype
754  * Datum.  The specified field number is extracted and returned as a Datum.
755  * ----------------
756  */
757 
758 typedef struct FieldSelect
759 {
760 	Expr		xpr;
761 	Expr	   *arg;			/* input expression */
762 	AttrNumber	fieldnum;		/* attribute number of field to extract */
763 	Oid			resulttype;		/* type of the field (result type of this
764 								 * node) */
765 	int32		resulttypmod;	/* output typmod (usually -1) */
766 	Oid			resultcollid;	/* OID of collation of the field */
767 } FieldSelect;
768 
769 /* ----------------
770  * FieldStore
771  *
772  * FieldStore represents the operation of modifying one field in a tuple
773  * value, yielding a new tuple value (the input is not touched!).  Like
774  * the assign case of SubscriptingRef, this is used to implement UPDATE of a
775  * portion of a column.
776  *
777  * resulttype is always a named composite type (not a domain).  To update
778  * a composite domain value, apply CoerceToDomain to the FieldStore.
779  *
780  * A single FieldStore can actually represent updates of several different
781  * fields.  The parser only generates FieldStores with single-element lists,
782  * but the planner will collapse multiple updates of the same base column
783  * into one FieldStore.
784  * ----------------
785  */
786 
787 typedef struct FieldStore
788 {
789 	Expr		xpr;
790 	Expr	   *arg;			/* input tuple value */
791 	List	   *newvals;		/* new value(s) for field(s) */
792 	List	   *fieldnums;		/* integer list of field attnums */
793 	Oid			resulttype;		/* type of result (same as type of arg) */
794 	/* Like RowExpr, we deliberately omit a typmod and collation here */
795 } FieldStore;
796 
797 /* ----------------
798  * RelabelType
799  *
800  * RelabelType represents a "dummy" type coercion between two binary-
801  * compatible datatypes, such as reinterpreting the result of an OID
802  * expression as an int4.  It is a no-op at runtime; we only need it
803  * to provide a place to store the correct type to be attributed to
804  * the expression result during type resolution.  (We can't get away
805  * with just overwriting the type field of the input expression node,
806  * so we need a separate node to show the coercion's result type.)
807  * ----------------
808  */
809 
810 typedef struct RelabelType
811 {
812 	Expr		xpr;
813 	Expr	   *arg;			/* input expression */
814 	Oid			resulttype;		/* output type of coercion expression */
815 	int32		resulttypmod;	/* output typmod (usually -1) */
816 	Oid			resultcollid;	/* OID of collation, or InvalidOid if none */
817 	CoercionForm relabelformat; /* how to display this node */
818 	int			location;		/* token location, or -1 if unknown */
819 } RelabelType;
820 
821 /* ----------------
822  * CoerceViaIO
823  *
824  * CoerceViaIO represents a type coercion between two types whose textual
825  * representations are compatible, implemented by invoking the source type's
826  * typoutput function then the destination type's typinput function.
827  * ----------------
828  */
829 
830 typedef struct CoerceViaIO
831 {
832 	Expr		xpr;
833 	Expr	   *arg;			/* input expression */
834 	Oid			resulttype;		/* output type of coercion */
835 	/* output typmod is not stored, but is presumed -1 */
836 	Oid			resultcollid;	/* OID of collation, or InvalidOid if none */
837 	CoercionForm coerceformat;	/* how to display this node */
838 	int			location;		/* token location, or -1 if unknown */
839 } CoerceViaIO;
840 
841 /* ----------------
842  * ArrayCoerceExpr
843  *
844  * ArrayCoerceExpr represents a type coercion from one array type to another,
845  * which is implemented by applying the per-element coercion expression
846  * "elemexpr" to each element of the source array.  Within elemexpr, the
847  * source element is represented by a CaseTestExpr node.  Note that even if
848  * elemexpr is a no-op (that is, just CaseTestExpr + RelabelType), the
849  * coercion still requires some effort: we have to fix the element type OID
850  * stored in the array header.
851  * ----------------
852  */
853 
854 typedef struct ArrayCoerceExpr
855 {
856 	Expr		xpr;
857 	Expr	   *arg;			/* input expression (yields an array) */
858 	Expr	   *elemexpr;		/* expression representing per-element work */
859 	Oid			resulttype;		/* output type of coercion (an array type) */
860 	int32		resulttypmod;	/* output typmod (also element typmod) */
861 	Oid			resultcollid;	/* OID of collation, or InvalidOid if none */
862 	CoercionForm coerceformat;	/* how to display this node */
863 	int			location;		/* token location, or -1 if unknown */
864 } ArrayCoerceExpr;
865 
866 /* ----------------
867  * ConvertRowtypeExpr
868  *
869  * ConvertRowtypeExpr represents a type coercion from one composite type
870  * to another, where the source type is guaranteed to contain all the columns
871  * needed for the destination type plus possibly others; the columns need not
872  * be in the same positions, but are matched up by name.  This is primarily
873  * used to convert a whole-row value of an inheritance child table into a
874  * valid whole-row value of its parent table's rowtype.  Both resulttype
875  * and the exposed type of "arg" must be named composite types (not domains).
876  * ----------------
877  */
878 
879 typedef struct ConvertRowtypeExpr
880 {
881 	Expr		xpr;
882 	Expr	   *arg;			/* input expression */
883 	Oid			resulttype;		/* output type (always a composite type) */
884 	/* Like RowExpr, we deliberately omit a typmod and collation here */
885 	CoercionForm convertformat; /* how to display this node */
886 	int			location;		/* token location, or -1 if unknown */
887 } ConvertRowtypeExpr;
888 
889 /*----------
890  * CollateExpr - COLLATE
891  *
892  * The planner replaces CollateExpr with RelabelType during expression
893  * preprocessing, so execution never sees a CollateExpr.
894  *----------
895  */
896 typedef struct CollateExpr
897 {
898 	Expr		xpr;
899 	Expr	   *arg;			/* input expression */
900 	Oid			collOid;		/* collation's OID */
901 	int			location;		/* token location, or -1 if unknown */
902 } CollateExpr;
903 
904 /*----------
905  * CaseExpr - a CASE expression
906  *
907  * We support two distinct forms of CASE expression:
908  *		CASE WHEN boolexpr THEN expr [ WHEN boolexpr THEN expr ... ]
909  *		CASE testexpr WHEN compexpr THEN expr [ WHEN compexpr THEN expr ... ]
910  * These are distinguishable by the "arg" field being NULL in the first case
911  * and the testexpr in the second case.
912  *
913  * In the raw grammar output for the second form, the condition expressions
914  * of the WHEN clauses are just the comparison values.  Parse analysis
915  * converts these to valid boolean expressions of the form
916  *		CaseTestExpr '=' compexpr
917  * where the CaseTestExpr node is a placeholder that emits the correct
918  * value at runtime.  This structure is used so that the testexpr need be
919  * evaluated only once.  Note that after parse analysis, the condition
920  * expressions always yield boolean.
921  *
922  * Note: we can test whether a CaseExpr has been through parse analysis
923  * yet by checking whether casetype is InvalidOid or not.
924  *----------
925  */
926 typedef struct CaseExpr
927 {
928 	Expr		xpr;
929 	Oid			casetype;		/* type of expression result */
930 	Oid			casecollid;		/* OID of collation, or InvalidOid if none */
931 	Expr	   *arg;			/* implicit equality comparison argument */
932 	List	   *args;			/* the arguments (list of WHEN clauses) */
933 	Expr	   *defresult;		/* the default result (ELSE clause) */
934 	int			location;		/* token location, or -1 if unknown */
935 } CaseExpr;
936 
937 /*
938  * CaseWhen - one arm of a CASE expression
939  */
940 typedef struct CaseWhen
941 {
942 	Expr		xpr;
943 	Expr	   *expr;			/* condition expression */
944 	Expr	   *result;			/* substitution result */
945 	int			location;		/* token location, or -1 if unknown */
946 } CaseWhen;
947 
948 /*
949  * Placeholder node for the test value to be processed by a CASE expression.
950  * This is effectively like a Param, but can be implemented more simply
951  * since we need only one replacement value at a time.
952  *
953  * We also abuse this node type for some other purposes, including:
954  *	* Placeholder for the current array element value in ArrayCoerceExpr;
955  *	  see build_coercion_expression().
956  *	* Nested FieldStore/ArrayRef assignment expressions in INSERT/UPDATE;
957  *	  see transformAssignmentIndirection().
958  *
959  * The uses in CaseExpr and ArrayCoerceExpr are safe only to the extent that
960  * there is not any other CaseExpr or ArrayCoerceExpr between the value source
961  * node and its child CaseTestExpr(s).  This is true in the parse analysis
962  * output, but the planner's function-inlining logic has to be careful not to
963  * break it.
964  *
965  * The nested-assignment-expression case is safe because the only node types
966  * that can be above such CaseTestExprs are FieldStore and ArrayRef.
967  */
968 typedef struct CaseTestExpr
969 {
970 	Expr		xpr;
971 	Oid			typeId;			/* type for substituted value */
972 	int32		typeMod;		/* typemod for substituted value */
973 	Oid			collation;		/* collation for the substituted value */
974 } CaseTestExpr;
975 
976 /*
977  * ArrayExpr - an ARRAY[] expression
978  *
979  * Note: if multidims is false, the constituent expressions all yield the
980  * scalar type identified by element_typeid.  If multidims is true, the
981  * constituent expressions all yield arrays of element_typeid (ie, the same
982  * type as array_typeid); at runtime we must check for compatible subscripts.
983  */
984 typedef struct ArrayExpr
985 {
986 	Expr		xpr;
987 	Oid			array_typeid;	/* type of expression result */
988 	Oid			array_collid;	/* OID of collation, or InvalidOid if none */
989 	Oid			element_typeid; /* common type of array elements */
990 	List	   *elements;		/* the array elements or sub-arrays */
991 	bool		multidims;		/* true if elements are sub-arrays */
992 	int			location;		/* token location, or -1 if unknown */
993 } ArrayExpr;
994 
995 /*
996  * RowExpr - a ROW() expression
997  *
998  * Note: the list of fields must have a one-for-one correspondence with
999  * physical fields of the associated rowtype, although it is okay for it
1000  * to be shorter than the rowtype.  That is, the N'th list element must
1001  * match up with the N'th physical field.  When the N'th physical field
1002  * is a dropped column (attisdropped) then the N'th list element can just
1003  * be a NULL constant.  (This case can only occur for named composite types,
1004  * not RECORD types, since those are built from the RowExpr itself rather
1005  * than vice versa.)  It is important not to assume that length(args) is
1006  * the same as the number of columns logically present in the rowtype.
1007  *
1008  * colnames provides field names in cases where the names can't easily be
1009  * obtained otherwise.  Names *must* be provided if row_typeid is RECORDOID.
1010  * If row_typeid identifies a known composite type, colnames can be NIL to
1011  * indicate the type's cataloged field names apply.  Note that colnames can
1012  * be non-NIL even for a composite type, and typically is when the RowExpr
1013  * was created by expanding a whole-row Var.  This is so that we can retain
1014  * the column alias names of the RTE that the Var referenced (which would
1015  * otherwise be very difficult to extract from the parsetree).  Like the
1016  * args list, colnames is one-for-one with physical fields of the rowtype.
1017  */
1018 typedef struct RowExpr
1019 {
1020 	Expr		xpr;
1021 	List	   *args;			/* the fields */
1022 	Oid			row_typeid;		/* RECORDOID or a composite type's ID */
1023 
1024 	/*
1025 	 * row_typeid cannot be a domain over composite, only plain composite.  To
1026 	 * create a composite domain value, apply CoerceToDomain to the RowExpr.
1027 	 *
1028 	 * Note: we deliberately do NOT store a typmod.  Although a typmod will be
1029 	 * associated with specific RECORD types at runtime, it will differ for
1030 	 * different backends, and so cannot safely be stored in stored
1031 	 * parsetrees.  We must assume typmod -1 for a RowExpr node.
1032 	 *
1033 	 * We don't need to store a collation either.  The result type is
1034 	 * necessarily composite, and composite types never have a collation.
1035 	 */
1036 	CoercionForm row_format;	/* how to display this node */
1037 	List	   *colnames;		/* list of String, or NIL */
1038 	int			location;		/* token location, or -1 if unknown */
1039 } RowExpr;
1040 
1041 /*
1042  * RowCompareExpr - row-wise comparison, such as (a, b) <= (1, 2)
1043  *
1044  * We support row comparison for any operator that can be determined to
1045  * act like =, <>, <, <=, >, or >= (we determine this by looking for the
1046  * operator in btree opfamilies).  Note that the same operator name might
1047  * map to a different operator for each pair of row elements, since the
1048  * element datatypes can vary.
1049  *
1050  * A RowCompareExpr node is only generated for the < <= > >= cases;
1051  * the = and <> cases are translated to simple AND or OR combinations
1052  * of the pairwise comparisons.  However, we include = and <> in the
1053  * RowCompareType enum for the convenience of parser logic.
1054  */
1055 typedef enum RowCompareType
1056 {
1057 	/* Values of this enum are chosen to match btree strategy numbers */
1058 	ROWCOMPARE_LT = 1,			/* BTLessStrategyNumber */
1059 	ROWCOMPARE_LE = 2,			/* BTLessEqualStrategyNumber */
1060 	ROWCOMPARE_EQ = 3,			/* BTEqualStrategyNumber */
1061 	ROWCOMPARE_GE = 4,			/* BTGreaterEqualStrategyNumber */
1062 	ROWCOMPARE_GT = 5,			/* BTGreaterStrategyNumber */
1063 	ROWCOMPARE_NE = 6			/* no such btree strategy */
1064 } RowCompareType;
1065 
1066 typedef struct RowCompareExpr
1067 {
1068 	Expr		xpr;
1069 	RowCompareType rctype;		/* LT LE GE or GT, never EQ or NE */
1070 	List	   *opnos;			/* OID list of pairwise comparison ops */
1071 	List	   *opfamilies;		/* OID list of containing operator families */
1072 	List	   *inputcollids;	/* OID list of collations for comparisons */
1073 	List	   *largs;			/* the left-hand input arguments */
1074 	List	   *rargs;			/* the right-hand input arguments */
1075 } RowCompareExpr;
1076 
1077 /*
1078  * CoalesceExpr - a COALESCE expression
1079  */
1080 typedef struct CoalesceExpr
1081 {
1082 	Expr		xpr;
1083 	Oid			coalescetype;	/* type of expression result */
1084 	Oid			coalescecollid; /* OID of collation, or InvalidOid if none */
1085 	List	   *args;			/* the arguments */
1086 	int			location;		/* token location, or -1 if unknown */
1087 } CoalesceExpr;
1088 
1089 /*
1090  * MinMaxExpr - a GREATEST or LEAST function
1091  */
1092 typedef enum MinMaxOp
1093 {
1094 	IS_GREATEST,
1095 	IS_LEAST
1096 } MinMaxOp;
1097 
1098 typedef struct MinMaxExpr
1099 {
1100 	Expr		xpr;
1101 	Oid			minmaxtype;		/* common type of arguments and result */
1102 	Oid			minmaxcollid;	/* OID of collation of result */
1103 	Oid			inputcollid;	/* OID of collation that function should use */
1104 	MinMaxOp	op;				/* function to execute */
1105 	List	   *args;			/* the arguments */
1106 	int			location;		/* token location, or -1 if unknown */
1107 } MinMaxExpr;
1108 
1109 /*
1110  * SQLValueFunction - parameterless functions with special grammar productions
1111  *
1112  * The SQL standard categorizes some of these as <datetime value function>
1113  * and others as <general value specification>.  We call 'em SQLValueFunctions
1114  * for lack of a better term.  We store type and typmod of the result so that
1115  * some code doesn't need to know each function individually, and because
1116  * we would need to store typmod anyway for some of the datetime functions.
1117  * Note that currently, all variants return non-collating datatypes, so we do
1118  * not need a collation field; also, all these functions are stable.
1119  */
1120 typedef enum SQLValueFunctionOp
1121 {
1122 	SVFOP_CURRENT_DATE,
1123 	SVFOP_CURRENT_TIME,
1124 	SVFOP_CURRENT_TIME_N,
1125 	SVFOP_CURRENT_TIMESTAMP,
1126 	SVFOP_CURRENT_TIMESTAMP_N,
1127 	SVFOP_LOCALTIME,
1128 	SVFOP_LOCALTIME_N,
1129 	SVFOP_LOCALTIMESTAMP,
1130 	SVFOP_LOCALTIMESTAMP_N,
1131 	SVFOP_CURRENT_ROLE,
1132 	SVFOP_CURRENT_USER,
1133 	SVFOP_USER,
1134 	SVFOP_SESSION_USER,
1135 	SVFOP_CURRENT_CATALOG,
1136 	SVFOP_CURRENT_SCHEMA
1137 } SQLValueFunctionOp;
1138 
1139 typedef struct SQLValueFunction
1140 {
1141 	Expr		xpr;
1142 	SQLValueFunctionOp op;		/* which function this is */
1143 	Oid			type;			/* result type/typmod */
1144 	int32		typmod;
1145 	int			location;		/* token location, or -1 if unknown */
1146 } SQLValueFunction;
1147 
1148 /*
1149  * XmlExpr - various SQL/XML functions requiring special grammar productions
1150  *
1151  * 'name' carries the "NAME foo" argument (already XML-escaped).
1152  * 'named_args' and 'arg_names' represent an xml_attribute list.
1153  * 'args' carries all other arguments.
1154  *
1155  * Note: result type/typmod/collation are not stored, but can be deduced
1156  * from the XmlExprOp.  The type/typmod fields are just used for display
1157  * purposes, and are NOT necessarily the true result type of the node.
1158  */
1159 typedef enum XmlExprOp
1160 {
1161 	IS_XMLCONCAT,				/* XMLCONCAT(args) */
1162 	IS_XMLELEMENT,				/* XMLELEMENT(name, xml_attributes, args) */
1163 	IS_XMLFOREST,				/* XMLFOREST(xml_attributes) */
1164 	IS_XMLPARSE,				/* XMLPARSE(text, is_doc, preserve_ws) */
1165 	IS_XMLPI,					/* XMLPI(name [, args]) */
1166 	IS_XMLROOT,					/* XMLROOT(xml, version, standalone) */
1167 	IS_XMLSERIALIZE,			/* XMLSERIALIZE(is_document, xmlval) */
1168 	IS_DOCUMENT					/* xmlval IS DOCUMENT */
1169 } XmlExprOp;
1170 
1171 typedef enum
1172 {
1173 	XMLOPTION_DOCUMENT,
1174 	XMLOPTION_CONTENT
1175 } XmlOptionType;
1176 
1177 typedef struct XmlExpr
1178 {
1179 	Expr		xpr;
1180 	XmlExprOp	op;				/* xml function ID */
1181 	char	   *name;			/* name in xml(NAME foo ...) syntaxes */
1182 	List	   *named_args;		/* non-XML expressions for xml_attributes */
1183 	List	   *arg_names;		/* parallel list of Value strings */
1184 	List	   *args;			/* list of expressions */
1185 	XmlOptionType xmloption;	/* DOCUMENT or CONTENT */
1186 	Oid			type;			/* target type/typmod for XMLSERIALIZE */
1187 	int32		typmod;
1188 	int			location;		/* token location, or -1 if unknown */
1189 } XmlExpr;
1190 
1191 /* ----------------
1192  * NullTest
1193  *
1194  * NullTest represents the operation of testing a value for NULLness.
1195  * The appropriate test is performed and returned as a boolean Datum.
1196  *
1197  * When argisrow is false, this simply represents a test for the null value.
1198  *
1199  * When argisrow is true, the input expression must yield a rowtype, and
1200  * the node implements "row IS [NOT] NULL" per the SQL standard.  This
1201  * includes checking individual fields for NULLness when the row datum
1202  * itself isn't NULL.
1203  *
1204  * NOTE: the combination of a rowtype input and argisrow==false does NOT
1205  * correspond to the SQL notation "row IS [NOT] NULL"; instead, this case
1206  * represents the SQL notation "row IS [NOT] DISTINCT FROM NULL".
1207  * ----------------
1208  */
1209 
1210 typedef enum NullTestType
1211 {
1212 	IS_NULL, IS_NOT_NULL
1213 } NullTestType;
1214 
1215 typedef struct NullTest
1216 {
1217 	Expr		xpr;
1218 	Expr	   *arg;			/* input expression */
1219 	NullTestType nulltesttype;	/* IS NULL, IS NOT NULL */
1220 	bool		argisrow;		/* T to perform field-by-field null checks */
1221 	int			location;		/* token location, or -1 if unknown */
1222 } NullTest;
1223 
1224 /*
1225  * BooleanTest
1226  *
1227  * BooleanTest represents the operation of determining whether a boolean
1228  * is TRUE, FALSE, or UNKNOWN (ie, NULL).  All six meaningful combinations
1229  * are supported.  Note that a NULL input does *not* cause a NULL result.
1230  * The appropriate test is performed and returned as a boolean Datum.
1231  */
1232 
1233 typedef enum BoolTestType
1234 {
1235 	IS_TRUE, IS_NOT_TRUE, IS_FALSE, IS_NOT_FALSE, IS_UNKNOWN, IS_NOT_UNKNOWN
1236 } BoolTestType;
1237 
1238 typedef struct BooleanTest
1239 {
1240 	Expr		xpr;
1241 	Expr	   *arg;			/* input expression */
1242 	BoolTestType booltesttype;	/* test type */
1243 	int			location;		/* token location, or -1 if unknown */
1244 } BooleanTest;
1245 
1246 /*
1247  * CoerceToDomain
1248  *
1249  * CoerceToDomain represents the operation of coercing a value to a domain
1250  * type.  At runtime (and not before) the precise set of constraints to be
1251  * checked will be determined.  If the value passes, it is returned as the
1252  * result; if not, an error is raised.  Note that this is equivalent to
1253  * RelabelType in the scenario where no constraints are applied.
1254  */
1255 typedef struct CoerceToDomain
1256 {
1257 	Expr		xpr;
1258 	Expr	   *arg;			/* input expression */
1259 	Oid			resulttype;		/* domain type ID (result type) */
1260 	int32		resulttypmod;	/* output typmod (currently always -1) */
1261 	Oid			resultcollid;	/* OID of collation, or InvalidOid if none */
1262 	CoercionForm coercionformat;	/* how to display this node */
1263 	int			location;		/* token location, or -1 if unknown */
1264 } CoerceToDomain;
1265 
1266 /*
1267  * Placeholder node for the value to be processed by a domain's check
1268  * constraint.  This is effectively like a Param, but can be implemented more
1269  * simply since we need only one replacement value at a time.
1270  *
1271  * Note: the typeId/typeMod/collation will be set from the domain's base type,
1272  * not the domain itself.  This is because we shouldn't consider the value
1273  * to be a member of the domain if we haven't yet checked its constraints.
1274  */
1275 typedef struct CoerceToDomainValue
1276 {
1277 	Expr		xpr;
1278 	Oid			typeId;			/* type for substituted value */
1279 	int32		typeMod;		/* typemod for substituted value */
1280 	Oid			collation;		/* collation for the substituted value */
1281 	int			location;		/* token location, or -1 if unknown */
1282 } CoerceToDomainValue;
1283 
1284 /*
1285  * Placeholder node for a DEFAULT marker in an INSERT or UPDATE command.
1286  *
1287  * This is not an executable expression: it must be replaced by the actual
1288  * column default expression during rewriting.  But it is convenient to
1289  * treat it as an expression node during parsing and rewriting.
1290  */
1291 typedef struct SetToDefault
1292 {
1293 	Expr		xpr;
1294 	Oid			typeId;			/* type for substituted value */
1295 	int32		typeMod;		/* typemod for substituted value */
1296 	Oid			collation;		/* collation for the substituted value */
1297 	int			location;		/* token location, or -1 if unknown */
1298 } SetToDefault;
1299 
1300 /*
1301  * Node representing [WHERE] CURRENT OF cursor_name
1302  *
1303  * CURRENT OF is a bit like a Var, in that it carries the rangetable index
1304  * of the target relation being constrained; this aids placing the expression
1305  * correctly during planning.  We can assume however that its "levelsup" is
1306  * always zero, due to the syntactic constraints on where it can appear.
1307  *
1308  * The referenced cursor can be represented either as a hardwired string
1309  * or as a reference to a run-time parameter of type REFCURSOR.  The latter
1310  * case is for the convenience of plpgsql.
1311  */
1312 typedef struct CurrentOfExpr
1313 {
1314 	Expr		xpr;
1315 	Index		cvarno;			/* RT index of target relation */
1316 	char	   *cursor_name;	/* name of referenced cursor, or NULL */
1317 	int			cursor_param;	/* refcursor parameter number, or 0 */
1318 } CurrentOfExpr;
1319 
1320 /*
1321  * NextValueExpr - get next value from sequence
1322  *
1323  * This has the same effect as calling the nextval() function, but it does not
1324  * check permissions on the sequence.  This is used for identity columns,
1325  * where the sequence is an implicit dependency without its own permissions.
1326  */
1327 typedef struct NextValueExpr
1328 {
1329 	Expr		xpr;
1330 	Oid			seqid;
1331 	Oid			typeId;
1332 } NextValueExpr;
1333 
1334 /*
1335  * InferenceElem - an element of a unique index inference specification
1336  *
1337  * This mostly matches the structure of IndexElems, but having a dedicated
1338  * primnode allows for a clean separation between the use of index parameters
1339  * by utility commands, and this node.
1340  */
1341 typedef struct InferenceElem
1342 {
1343 	Expr		xpr;
1344 	Node	   *expr;			/* expression to infer from, or NULL */
1345 	Oid			infercollid;	/* OID of collation, or InvalidOid */
1346 	Oid			inferopclass;	/* OID of att opclass, or InvalidOid */
1347 } InferenceElem;
1348 
1349 /*--------------------
1350  * TargetEntry -
1351  *	   a target entry (used in query target lists)
1352  *
1353  * Strictly speaking, a TargetEntry isn't an expression node (since it can't
1354  * be evaluated by ExecEvalExpr).  But we treat it as one anyway, since in
1355  * very many places it's convenient to process a whole query targetlist as a
1356  * single expression tree.
1357  *
1358  * In a SELECT's targetlist, resno should always be equal to the item's
1359  * ordinal position (counting from 1).  However, in an INSERT or UPDATE
1360  * targetlist, resno represents the attribute number of the destination
1361  * column for the item; so there may be missing or out-of-order resnos.
1362  * It is even legal to have duplicated resnos; consider
1363  *		UPDATE table SET arraycol[1] = ..., arraycol[2] = ..., ...
1364  * The two meanings come together in the executor, because the planner
1365  * transforms INSERT/UPDATE tlists into a normalized form with exactly
1366  * one entry for each column of the destination table.  Before that's
1367  * happened, however, it is risky to assume that resno == position.
1368  * Generally get_tle_by_resno() should be used rather than list_nth()
1369  * to fetch tlist entries by resno, and only in SELECT should you assume
1370  * that resno is a unique identifier.
1371  *
1372  * resname is required to represent the correct column name in non-resjunk
1373  * entries of top-level SELECT targetlists, since it will be used as the
1374  * column title sent to the frontend.  In most other contexts it is only
1375  * a debugging aid, and may be wrong or even NULL.  (In particular, it may
1376  * be wrong in a tlist from a stored rule, if the referenced column has been
1377  * renamed by ALTER TABLE since the rule was made.  Also, the planner tends
1378  * to store NULL rather than look up a valid name for tlist entries in
1379  * non-toplevel plan nodes.)  In resjunk entries, resname should be either
1380  * a specific system-generated name (such as "ctid") or NULL; anything else
1381  * risks confusing ExecGetJunkAttribute!
1382  *
1383  * ressortgroupref is used in the representation of ORDER BY, GROUP BY, and
1384  * DISTINCT items.  Targetlist entries with ressortgroupref=0 are not
1385  * sort/group items.  If ressortgroupref>0, then this item is an ORDER BY,
1386  * GROUP BY, and/or DISTINCT target value.  No two entries in a targetlist
1387  * may have the same nonzero ressortgroupref --- but there is no particular
1388  * meaning to the nonzero values, except as tags.  (For example, one must
1389  * not assume that lower ressortgroupref means a more significant sort key.)
1390  * The order of the associated SortGroupClause lists determine the semantics.
1391  *
1392  * resorigtbl/resorigcol identify the source of the column, if it is a
1393  * simple reference to a column of a base table (or view).  If it is not
1394  * a simple reference, these fields are zeroes.
1395  *
1396  * If resjunk is true then the column is a working column (such as a sort key)
1397  * that should be removed from the final output of the query.  Resjunk columns
1398  * must have resnos that cannot duplicate any regular column's resno.  Also
1399  * note that there are places that assume resjunk columns come after non-junk
1400  * columns.
1401  *--------------------
1402  */
1403 typedef struct TargetEntry
1404 {
1405 	Expr		xpr;
1406 	Expr	   *expr;			/* expression to evaluate */
1407 	AttrNumber	resno;			/* attribute number (see notes above) */
1408 	char	   *resname;		/* name of the column (could be NULL) */
1409 	Index		ressortgroupref;	/* nonzero if referenced by a sort/group
1410 									 * clause */
1411 	Oid			resorigtbl;		/* OID of column's source table */
1412 	AttrNumber	resorigcol;		/* column's number in source table */
1413 	bool		resjunk;		/* set to true to eliminate the attribute from
1414 								 * final target list */
1415 } TargetEntry;
1416 
1417 
1418 /* ----------------------------------------------------------------
1419  *					node types for join trees
1420  *
1421  * The leaves of a join tree structure are RangeTblRef nodes.  Above
1422  * these, JoinExpr nodes can appear to denote a specific kind of join
1423  * or qualified join.  Also, FromExpr nodes can appear to denote an
1424  * ordinary cross-product join ("FROM foo, bar, baz WHERE ...").
1425  * FromExpr is like a JoinExpr of jointype JOIN_INNER, except that it
1426  * may have any number of child nodes, not just two.
1427  *
1428  * NOTE: the top level of a Query's jointree is always a FromExpr.
1429  * Even if the jointree contains no rels, there will be a FromExpr.
1430  *
1431  * NOTE: the qualification expressions present in JoinExpr nodes are
1432  * *in addition to* the query's main WHERE clause, which appears as the
1433  * qual of the top-level FromExpr.  The reason for associating quals with
1434  * specific nodes in the jointree is that the position of a qual is critical
1435  * when outer joins are present.  (If we enforce a qual too soon or too late,
1436  * that may cause the outer join to produce the wrong set of NULL-extended
1437  * rows.)  If all joins are inner joins then all the qual positions are
1438  * semantically interchangeable.
1439  *
1440  * NOTE: in the raw output of gram.y, a join tree contains RangeVar,
1441  * RangeSubselect, and RangeFunction nodes, which are all replaced by
1442  * RangeTblRef nodes during the parse analysis phase.  Also, the top-level
1443  * FromExpr is added during parse analysis; the grammar regards FROM and
1444  * WHERE as separate.
1445  * ----------------------------------------------------------------
1446  */
1447 
1448 /*
1449  * RangeTblRef - reference to an entry in the query's rangetable
1450  *
1451  * We could use direct pointers to the RT entries and skip having these
1452  * nodes, but multiple pointers to the same node in a querytree cause
1453  * lots of headaches, so it seems better to store an index into the RT.
1454  */
1455 typedef struct RangeTblRef
1456 {
1457 	NodeTag		type;
1458 	int			rtindex;
1459 } RangeTblRef;
1460 
1461 /*----------
1462  * JoinExpr - for SQL JOIN expressions
1463  *
1464  * isNatural, usingClause, and quals are interdependent.  The user can write
1465  * only one of NATURAL, USING(), or ON() (this is enforced by the grammar).
1466  * If he writes NATURAL then parse analysis generates the equivalent USING()
1467  * list, and from that fills in "quals" with the right equality comparisons.
1468  * If he writes USING() then "quals" is filled with equality comparisons.
1469  * If he writes ON() then only "quals" is set.  Note that NATURAL/USING
1470  * are not equivalent to ON() since they also affect the output column list.
1471  *
1472  * alias is an Alias node representing the AS alias-clause attached to the
1473  * join expression, or NULL if no clause.  NB: presence or absence of the
1474  * alias has a critical impact on semantics, because a join with an alias
1475  * restricts visibility of the tables/columns inside it.
1476  *
1477  * During parse analysis, an RTE is created for the Join, and its index
1478  * is filled into rtindex.  This RTE is present mainly so that Vars can
1479  * be created that refer to the outputs of the join.  The planner sometimes
1480  * generates JoinExprs internally; these can have rtindex = 0 if there are
1481  * no join alias variables referencing such joins.
1482  *----------
1483  */
1484 typedef struct JoinExpr
1485 {
1486 	NodeTag		type;
1487 	JoinType	jointype;		/* type of join */
1488 	bool		isNatural;		/* Natural join? Will need to shape table */
1489 	Node	   *larg;			/* left subtree */
1490 	Node	   *rarg;			/* right subtree */
1491 	List	   *usingClause;	/* USING clause, if any (list of String) */
1492 	Node	   *quals;			/* qualifiers on join, if any */
1493 	Alias	   *alias;			/* user-written alias clause, if any */
1494 	int			rtindex;		/* RT index assigned for join, or 0 */
1495 } JoinExpr;
1496 
1497 /*----------
1498  * FromExpr - represents a FROM ... WHERE ... construct
1499  *
1500  * This is both more flexible than a JoinExpr (it can have any number of
1501  * children, including zero) and less so --- we don't need to deal with
1502  * aliases and so on.  The output column set is implicitly just the union
1503  * of the outputs of the children.
1504  *----------
1505  */
1506 typedef struct FromExpr
1507 {
1508 	NodeTag		type;
1509 	List	   *fromlist;		/* List of join subtrees */
1510 	Node	   *quals;			/* qualifiers on join, if any */
1511 } FromExpr;
1512 
1513 /*----------
1514  * OnConflictExpr - represents an ON CONFLICT DO ... expression
1515  *
1516  * The optimizer requires a list of inference elements, and optionally a WHERE
1517  * clause to infer a unique index.  The unique index (or, occasionally,
1518  * indexes) inferred are used to arbitrate whether or not the alternative ON
1519  * CONFLICT path is taken.
1520  *----------
1521  */
1522 typedef struct OnConflictExpr
1523 {
1524 	NodeTag		type;
1525 	OnConflictAction action;	/* DO NOTHING or UPDATE? */
1526 
1527 	/* Arbiter */
1528 	List	   *arbiterElems;	/* unique index arbiter list (of
1529 								 * InferenceElem's) */
1530 	Node	   *arbiterWhere;	/* unique index arbiter WHERE clause */
1531 	Oid			constraint;		/* pg_constraint OID for arbiter */
1532 
1533 	/* ON CONFLICT UPDATE */
1534 	List	   *onConflictSet;	/* List of ON CONFLICT SET TargetEntrys */
1535 	Node	   *onConflictWhere;	/* qualifiers to restrict UPDATE to */
1536 	int			exclRelIndex;	/* RT index of 'excluded' relation */
1537 	List	   *exclRelTlist;	/* tlist of the EXCLUDED pseudo relation */
1538 } OnConflictExpr;
1539 
1540 #endif							/* PRIMNODES_H */
1541