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