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