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