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