1 /*-------------------------------------------------------------------------
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
10 * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
11 * Portions Copyright (c) 1994, Regents of the University of California
13 * src/include/nodes/primnodes.h
15 *-------------------------------------------------------------------------
20 #include "access/attnum.h"
21 #include "nodes/pg_list.h"
24 /* ----------------------------------------------------------------
26 * ----------------------------------------------------------------
31 * specifies an alias for a range variable; the alias might also
32 * specify renaming of columns within the table.
34 * Note: colnames is a list of Value nodes (always strings). In Alias structs
35 * associated with RTEs, there may be entries corresponding to dropped
36 * columns; these are normally empty strings (""). See parsenodes.h for info.
41 char *aliasname; /* aliased rel name (never qualified) */
42 List *colnames; /* optional list of column aliases */
45 typedef enum InhOption
47 INH_NO, /* Do NOT scan child tables */
48 INH_YES, /* DO scan child tables */
49 INH_DEFAULT /* Use current SQL_inheritance option */
52 /* What to do at commit time for temporary relations */
53 typedef enum OnCommitAction
55 ONCOMMIT_NOOP, /* No ON COMMIT clause (do nothing) */
56 ONCOMMIT_PRESERVE_ROWS, /* ON COMMIT PRESERVE ROWS (do nothing) */
57 ONCOMMIT_DELETE_ROWS, /* ON COMMIT DELETE ROWS */
58 ONCOMMIT_DROP /* ON COMMIT DROP */
62 * RangeVar - range variable, used in FROM clauses
64 * Also used to represent table names in utility statements; there, the alias
65 * field is not used, and inhOpt shows whether to apply the operation
66 * recursively to child tables. In some contexts it is also useful to carry
67 * a TEMP table indication here.
69 typedef struct RangeVar
72 char *catalogname; /* the catalog (database) name, or NULL */
73 char *schemaname; /* the schema name, or NULL */
74 char *relname; /* the relation/sequence name */
75 InhOption inhOpt; /* expand rel by inheritance? recursively act
77 char relpersistence; /* see RELPERSISTENCE_* in pg_class.h */
78 Alias *alias; /* table alias & optional column aliases */
79 int location; /* token location, or -1 if unknown */
83 * IntoClause - target information for SELECT INTO, CREATE TABLE AS, and
84 * CREATE MATERIALIZED VIEW
86 * For CREATE MATERIALIZED VIEW, viewQuery is the parsed-but-not-rewritten
87 * SELECT Query for the view; otherwise it's NULL. (Although it's actually
88 * Query*, we declare it as Node* to avoid a forward reference.)
90 typedef struct IntoClause
94 RangeVar *rel; /* target relation name */
95 List *colNames; /* column names to assign, or NIL */
96 List *options; /* options from WITH clause */
97 OnCommitAction onCommit; /* what do we do at COMMIT? */
98 char *tableSpaceName; /* table space to use, or NULL */
99 Node *viewQuery; /* materialized view's SELECT query */
100 bool skipData; /* true for WITH NO DATA */
104 /* ----------------------------------------------------------------
105 * node types for executable expressions
106 * ----------------------------------------------------------------
110 * Expr - generic superclass for executable-expression nodes
112 * All node types that are used in executable expression trees should derive
113 * from Expr (that is, have Expr as their first field). Since Expr only
114 * contains NodeTag, this is a formality, but it is an easy form of
115 * documentation. See also the ExprState node types in execnodes.h.
123 * Var - expression node representing a variable (ie, a table column)
125 * Note: during parsing/planning, varnoold/varoattno are always just copies
126 * of varno/varattno. At the tail end of planning, Var nodes appearing in
127 * upper-level plan nodes are reassigned to point to the outputs of their
128 * subplans; for example, in a join node varno becomes INNER_VAR or OUTER_VAR
129 * and varattno becomes the index of the proper element of that subplan's
130 * target list. But varnoold/varoattno continue to hold the original values.
131 * The code doesn't really need varnoold/varoattno, but they are very useful
132 * for debugging and interpreting completed plans, so we keep them around.
134 #define INNER_VAR 65000 /* reference to inner subplan */
135 #define OUTER_VAR 65001 /* reference to outer subplan */
136 #define INDEX_VAR 65002 /* reference to index column */
138 #define IS_SPECIAL_VARNO(varno) ((varno) >= INNER_VAR)
140 /* Symbols for the indexes of the special RTE entries in rules */
141 #define PRS2_OLD_VARNO 1
142 #define PRS2_NEW_VARNO 2
147 Index varno; /* index of this var's relation in the range
148 * table, or INNER_VAR/OUTER_VAR/INDEX_VAR */
149 AttrNumber varattno; /* attribute number of this var, or zero for
151 Oid vartype; /* pg_type OID for the type of this var */
152 int32 vartypmod; /* pg_attribute typmod value */
153 Oid varcollid; /* OID of collation, or InvalidOid if none */
154 Index varlevelsup; /* for subquery variables referencing outer
155 * relations; 0 in a normal var, >0 means N
157 Index varnoold; /* original value of varno, for debugging */
158 AttrNumber varoattno; /* original value of varattno */
159 int location; /* token location, or -1 if unknown */
168 Oid consttype; /* pg_type OID of the constant's datatype */
169 int32 consttypmod; /* typmod value, if any */
170 Oid constcollid; /* OID of collation, or InvalidOid if none */
171 int constlen; /* typlen of the constant's datatype */
172 Datum constvalue; /* the constant's value */
173 bool constisnull; /* whether the constant is null (if true,
174 * constvalue is undefined) */
175 bool constbyval; /* whether this datatype is passed by value.
176 * If true, then all the information is stored
177 * in the Datum. If false, then the Datum
178 * contains a pointer to the information. */
179 int location; /* token location, or -1 if unknown */
184 * paramkind - specifies the kind of parameter. The possible values
185 * for this field are:
187 * PARAM_EXTERN: The parameter value is supplied from outside the plan.
188 * Such parameters are numbered from 1 to n.
190 * PARAM_EXEC: The parameter is an internal executor parameter, used
191 * for passing values into and out of sub-queries or from
192 * nestloop joins to their inner scans.
193 * For historical reasons, such parameters are numbered from 0.
194 * These numbers are independent of PARAM_EXTERN numbers.
196 * PARAM_SUBLINK: The parameter represents an output column of a SubLink
197 * node's sub-select. The column number is contained in the
198 * `paramid' field. (This type of Param is converted to
199 * PARAM_EXEC during planning.)
201 * Note: currently, paramtypmod is valid for PARAM_SUBLINK Params, and for
202 * PARAM_EXEC Params generated from them; it is always -1 for PARAM_EXTERN
203 * params, since the APIs that supply values for such parameters don't carry
207 typedef enum ParamKind
217 ParamKind paramkind; /* kind of parameter. See above */
218 int paramid; /* numeric ID for parameter */
219 Oid paramtype; /* pg_type OID of parameter's datatype */
220 int32 paramtypmod; /* typmod value, if known */
221 Oid paramcollid; /* OID of collation, or InvalidOid if none */
222 int location; /* token location, or -1 if unknown */
228 * The aggregate's args list is a targetlist, ie, a list of TargetEntry nodes.
230 * For a normal (non-ordered-set) aggregate, the non-resjunk TargetEntries
231 * represent the aggregate's regular arguments (if any) and resjunk TLEs can
232 * be added at the end to represent ORDER BY expressions that are not also
233 * arguments. As in a top-level Query, the TLEs can be marked with
234 * ressortgroupref indexes to let them be referenced by SortGroupClause
235 * entries in the aggorder and/or aggdistinct lists. This represents ORDER BY
236 * and DISTINCT operations to be applied to the aggregate input rows before
237 * they are passed to the transition function. The grammar only allows a
238 * simple "DISTINCT" specifier for the arguments, but we use the full
239 * query-level representation to allow more code sharing.
241 * For an ordered-set aggregate, the args list represents the WITHIN GROUP
242 * (aggregated) arguments, all of which will be listed in the aggorder list.
243 * DISTINCT is not supported in this case, so aggdistinct will be NIL.
244 * The direct arguments appear in aggdirectargs (as a list of plain
245 * expressions, not TargetEntry nodes).
247 typedef struct Aggref
250 Oid aggfnoid; /* pg_proc Oid of the aggregate */
251 Oid aggtype; /* type Oid of result of the aggregate */
252 Oid aggcollid; /* OID of collation of result */
253 Oid inputcollid; /* OID of collation that function should use */
254 List *aggdirectargs; /* direct arguments, if an ordered-set agg */
255 List *args; /* aggregated arguments and sort expressions */
256 List *aggorder; /* ORDER BY (list of SortGroupClause) */
257 List *aggdistinct; /* DISTINCT (list of SortGroupClause) */
258 Expr *aggfilter; /* FILTER expression, if any */
259 bool aggstar; /* TRUE if argument list was really '*' */
260 bool aggvariadic; /* TRUE if VARIADIC was used in call */
261 char aggkind; /* aggregate kind (see pg_aggregate.h) */
262 Index agglevelsup; /* > 0 if agg belongs to outer query */
263 int location; /* token location, or -1 if unknown */
269 typedef struct WindowFunc
272 Oid winfnoid; /* pg_proc Oid of the function */
273 Oid wintype; /* type Oid of result of the window function */
274 Oid wincollid; /* OID of collation of result */
275 Oid inputcollid; /* OID of collation that function should use */
276 List *args; /* arguments to the window function */
277 Expr *aggfilter; /* FILTER expression, if any */
278 Index winref; /* index of associated WindowClause */
279 bool winstar; /* TRUE if argument list was really '*' */
280 bool winagg; /* is function a simple aggregate? */
281 int location; /* token location, or -1 if unknown */
285 * ArrayRef: describes an array subscripting operation
287 * An ArrayRef can describe fetching a single element from an array,
288 * fetching a subarray (array slice), storing a single element into
289 * an array, or storing a slice. The "store" cases work with an
290 * initial array value and a source value that is inserted into the
291 * appropriate part of the array; the result of the operation is an
292 * entire new modified array value.
294 * If reflowerindexpr = NIL, then we are fetching or storing a single array
295 * element at the subscripts given by refupperindexpr. Otherwise we are
296 * fetching or storing an array slice, that is a rectangular subarray
297 * with lower and upper bounds given by the index expressions.
298 * reflowerindexpr must be the same length as refupperindexpr when it
301 * Note: the result datatype is the element type when fetching a single
302 * element; but it is the array type when doing subarray fetch or either
306 typedef struct ArrayRef
309 Oid refarraytype; /* type of the array proper */
310 Oid refelemtype; /* type of the array elements */
311 int32 reftypmod; /* typmod of the array (and elements too) */
312 Oid refcollid; /* OID of collation, or InvalidOid if none */
313 List *refupperindexpr;/* expressions that evaluate to upper array
315 List *reflowerindexpr;/* expressions that evaluate to lower array
317 Expr *refexpr; /* the expression that evaluates to an array
319 Expr *refassgnexpr; /* expression for the source value, or NULL if
324 * CoercionContext - distinguishes the allowed set of type casts
326 * NB: ordering of the alternatives is significant; later (larger) values
327 * allow more casts than earlier ones.
329 typedef enum CoercionContext
331 COERCION_IMPLICIT, /* coercion in context of expression */
332 COERCION_ASSIGNMENT, /* coercion in context of assignment */
333 COERCION_EXPLICIT /* explicit cast operation */
337 * CoercionForm - how to display a node that could have come from a cast
339 * NB: equal() ignores CoercionForm fields, therefore this *must* not carry
340 * any semantically significant information. We need that behavior so that
341 * the planner will consider equivalent implicit and explicit casts to be
342 * equivalent. In cases where those actually behave differently, the coercion
343 * function's arguments will be different.
345 typedef enum CoercionForm
347 COERCE_EXPLICIT_CALL, /* display as a function call */
348 COERCE_EXPLICIT_CAST, /* display as an explicit cast */
349 COERCE_IMPLICIT_CAST /* implicit cast, so hide it */
353 * FuncExpr - expression node for a function call
355 typedef struct FuncExpr
358 Oid funcid; /* PG_PROC OID of the function */
359 Oid funcresulttype; /* PG_TYPE OID of result value */
360 bool funcretset; /* true if function returns set */
361 bool funcvariadic; /* true if VARIADIC was used in call */
362 CoercionForm funcformat; /* how to display this function call */
363 Oid funccollid; /* OID of collation of result */
364 Oid inputcollid; /* OID of collation that function should use */
365 List *args; /* arguments to the function */
366 int location; /* token location, or -1 if unknown */
370 * NamedArgExpr - a named argument of a function
372 * This node type can only appear in the args list of a FuncCall or FuncExpr
373 * node. We support pure positional call notation (no named arguments),
374 * named notation (all arguments are named), and mixed notation (unnamed
375 * arguments followed by named ones).
377 * Parse analysis sets argnumber to the positional index of the argument,
378 * but doesn't rearrange the argument list.
380 * The planner will convert argument lists to pure positional notation
381 * during expression preprocessing, so execution never sees a NamedArgExpr.
383 typedef struct NamedArgExpr
386 Expr *arg; /* the argument expression */
387 char *name; /* the name */
388 int argnumber; /* argument's number in positional notation */
389 int location; /* argument name location, or -1 if unknown */
393 * OpExpr - expression node for an operator invocation
395 * Semantically, this is essentially the same as a function call.
397 * Note that opfuncid is not necessarily filled in immediately on creation
398 * of the node. The planner makes sure it is valid before passing the node
399 * tree to the executor, but during parsing/planning opfuncid can be 0.
401 typedef struct OpExpr
404 Oid opno; /* PG_OPERATOR OID of the operator */
405 Oid opfuncid; /* PG_PROC OID of underlying function */
406 Oid opresulttype; /* PG_TYPE OID of result value */
407 bool opretset; /* true if operator returns set */
408 Oid opcollid; /* OID of collation of result */
409 Oid inputcollid; /* OID of collation that operator should use */
410 List *args; /* arguments to the operator (1 or 2) */
411 int location; /* token location, or -1 if unknown */
415 * DistinctExpr - expression node for "x IS DISTINCT FROM y"
417 * Except for the nodetag, this is represented identically to an OpExpr
418 * referencing the "=" operator for x and y.
419 * We use "=", not the more obvious "<>", because more datatypes have "="
420 * than "<>". This means the executor must invert the operator result.
421 * Note that the operator function won't be called at all if either input
422 * is NULL, since then the result can be determined directly.
424 typedef OpExpr DistinctExpr;
427 * NullIfExpr - a NULLIF expression
429 * Like DistinctExpr, this is represented the same as an OpExpr referencing
430 * the "=" operator for x and y.
432 typedef OpExpr NullIfExpr;
435 * ScalarArrayOpExpr - expression node for "scalar op ANY/ALL (array)"
437 * The operator must yield boolean. It is applied to the left operand
438 * and each element of the righthand array, and the results are combined
439 * with OR or AND (for ANY or ALL respectively). The node representation
440 * is almost the same as for the underlying operator, but we need a useOr
441 * flag to remember whether it's ANY or ALL, and we don't have to store
442 * the result type (or the collation) because it must be boolean.
444 typedef struct ScalarArrayOpExpr
447 Oid opno; /* PG_OPERATOR OID of the operator */
448 Oid opfuncid; /* PG_PROC OID of underlying function */
449 bool useOr; /* true for ANY, false for ALL */
450 Oid inputcollid; /* OID of collation that operator should use */
451 List *args; /* the scalar and array operands */
452 int location; /* token location, or -1 if unknown */
456 * BoolExpr - expression node for the basic Boolean operators AND, OR, NOT
458 * Notice the arguments are given as a List. For NOT, of course the list
459 * must always have exactly one element. For AND and OR, the executor can
460 * handle any number of arguments. The parser generally treats AND and OR
461 * as binary and so it typically only produces two-element lists, but the
462 * optimizer will flatten trees of AND and OR nodes to produce longer lists
463 * when possible. There are also a few special cases where more arguments
464 * can appear before optimization.
466 typedef enum BoolExprType
468 AND_EXPR, OR_EXPR, NOT_EXPR
471 typedef struct BoolExpr
475 List *args; /* arguments to this expression */
476 int location; /* token location, or -1 if unknown */
482 * A SubLink represents a subselect appearing in an expression, and in some
483 * cases also the combining operator(s) just above it. The subLinkType
484 * indicates the form of the expression represented:
485 * EXISTS_SUBLINK EXISTS(SELECT ...)
486 * ALL_SUBLINK (lefthand) op ALL (SELECT ...)
487 * ANY_SUBLINK (lefthand) op ANY (SELECT ...)
488 * ROWCOMPARE_SUBLINK (lefthand) op (SELECT ...)
489 * EXPR_SUBLINK (SELECT with single targetlist item ...)
490 * ARRAY_SUBLINK ARRAY(SELECT with single targetlist item ...)
491 * CTE_SUBLINK WITH query (never actually part of an expression)
492 * For ALL, ANY, and ROWCOMPARE, the lefthand is a list of expressions of the
493 * same length as the subselect's targetlist. ROWCOMPARE will *always* have
494 * a list with more than one entry; if the subselect has just one target
495 * then the parser will create an EXPR_SUBLINK instead (and any operator
496 * above the subselect will be represented separately). Note that both
497 * ROWCOMPARE and EXPR require the subselect to deliver only one row.
498 * ALL, ANY, and ROWCOMPARE require the combining operators to deliver boolean
499 * results. ALL and ANY combine the per-row results using AND and OR
500 * semantics respectively.
501 * ARRAY requires just one target column, and creates an array of the target
502 * column's type using any number of rows resulting from the subselect.
504 * SubLink is classed as an Expr node, but it is not actually executable;
505 * it must be replaced in the expression tree by a SubPlan node during
508 * NOTE: in the raw output of gram.y, testexpr contains just the raw form
509 * of the lefthand expression (if any), and operName is the String name of
510 * the combining operator. Also, subselect is a raw parsetree. During parse
511 * analysis, the parser transforms testexpr into a complete boolean expression
512 * that compares the lefthand value(s) to PARAM_SUBLINK nodes representing the
513 * output columns of the subselect. And subselect is transformed to a Query.
514 * This is the representation seen in saved rules and in the rewriter.
516 * In EXISTS, EXPR, and ARRAY SubLinks, testexpr and operName are unused and
519 * The CTE_SUBLINK case never occurs in actual SubLink nodes, but it is used
520 * in SubPlans generated for WITH subqueries.
522 typedef enum SubLinkType
530 CTE_SUBLINK /* for SubPlans only */
534 typedef struct SubLink
537 SubLinkType subLinkType; /* see above */
538 Node *testexpr; /* outer-query test for ALL/ANY/ROWCOMPARE */
539 List *operName; /* originally specified operator name */
540 Node *subselect; /* subselect as Query* or parsetree */
541 int location; /* token location, or -1 if unknown */
545 * SubPlan - executable expression node for a subplan (sub-SELECT)
547 * The planner replaces SubLink nodes in expression trees with SubPlan
548 * nodes after it has finished planning the subquery. SubPlan references
549 * a sub-plantree stored in the subplans list of the toplevel PlannedStmt.
550 * (We avoid a direct link to make it easier to copy expression trees
551 * without causing multiple processing of the subplan.)
553 * In an ordinary subplan, testexpr points to an executable expression
554 * (OpExpr, an AND/OR tree of OpExprs, or RowCompareExpr) for the combining
555 * operator(s); the left-hand arguments are the original lefthand expressions,
556 * and the right-hand arguments are PARAM_EXEC Param nodes representing the
557 * outputs of the sub-select. (NOTE: runtime coercion functions may be
558 * inserted as well.) This is just the same expression tree as testexpr in
559 * the original SubLink node, but the PARAM_SUBLINK nodes are replaced by
560 * suitably numbered PARAM_EXEC nodes.
562 * If the sub-select becomes an initplan rather than a subplan, the executable
563 * expression is part of the outer plan's expression tree (and the SubPlan
564 * node itself is not, but rather is found in the outer plan's initPlan
565 * list). In this case testexpr is NULL to avoid duplication.
567 * The planner also derives lists of the values that need to be passed into
568 * and out of the subplan. Input values are represented as a list "args" of
569 * expressions to be evaluated in the outer-query context (currently these
570 * args are always just Vars, but in principle they could be any expression).
571 * The values are assigned to the global PARAM_EXEC params indexed by parParam
572 * (the parParam and args lists must have the same ordering). setParam is a
573 * list of the PARAM_EXEC params that are computed by the sub-select, if it
574 * is an initplan; they are listed in order by sub-select output column
575 * position. (parParam and setParam are integer Lists, not Bitmapsets,
576 * because their ordering is significant.)
578 * Also, the planner computes startup and per-call costs for use of the
579 * SubPlan. Note that these include the cost of the subquery proper,
580 * evaluation of the testexpr if any, and any hashtable management overhead.
582 typedef struct SubPlan
585 /* Fields copied from original SubLink: */
586 SubLinkType subLinkType; /* see above */
587 /* The combining operators, transformed to an executable expression: */
588 Node *testexpr; /* OpExpr or RowCompareExpr expression tree */
589 List *paramIds; /* IDs of Params embedded in the above */
590 /* Identification of the Plan tree to use: */
591 int plan_id; /* Index (from 1) in PlannedStmt.subplans */
592 /* Identification of the SubPlan for EXPLAIN and debugging purposes: */
593 char *plan_name; /* A name assigned during planning */
594 /* Extra data useful for determining subplan's output type: */
595 Oid firstColType; /* Type of first column of subplan result */
596 int32 firstColTypmod; /* Typmod of first column of subplan result */
597 Oid firstColCollation; /* Collation of first column of
599 /* Information about execution strategy: */
600 bool useHashTable; /* TRUE to store subselect output in a hash
601 * table (implies we are doing "IN") */
602 bool unknownEqFalse; /* TRUE if it's okay to return FALSE when the
603 * spec result is UNKNOWN; this allows much
604 * simpler handling of null values */
605 /* Information for passing params into and out of the subselect: */
606 /* setParam and parParam are lists of integers (param IDs) */
607 List *setParam; /* initplan subqueries have to set these
608 * Params for parent plan */
609 List *parParam; /* indices of input Params from parent plan */
610 List *args; /* exprs to pass as parParam values */
611 /* Estimated execution costs: */
612 Cost startup_cost; /* one-time setup cost */
613 Cost per_call_cost; /* cost for each subplan evaluation */
617 * AlternativeSubPlan - expression node for a choice among SubPlans
619 * The subplans are given as a List so that the node definition need not
620 * change if there's ever more than two alternatives. For the moment,
621 * though, there are always exactly two; and the first one is the fast-start
624 typedef struct AlternativeSubPlan
627 List *subplans; /* SubPlan(s) with equivalent results */
628 } AlternativeSubPlan;
633 * FieldSelect represents the operation of extracting one field from a tuple
634 * value. At runtime, the input expression is expected to yield a rowtype
635 * Datum. The specified field number is extracted and returned as a Datum.
639 typedef struct FieldSelect
642 Expr *arg; /* input expression */
643 AttrNumber fieldnum; /* attribute number of field to extract */
644 Oid resulttype; /* type of the field (result type of this
646 int32 resulttypmod; /* output typmod (usually -1) */
647 Oid resultcollid; /* OID of collation of the field */
653 * FieldStore represents the operation of modifying one field in a tuple
654 * value, yielding a new tuple value (the input is not touched!). Like
655 * the assign case of ArrayRef, this is used to implement UPDATE of a
656 * portion of a column.
658 * A single FieldStore can actually represent updates of several different
659 * fields. The parser only generates FieldStores with single-element lists,
660 * but the planner will collapse multiple updates of the same base column
661 * into one FieldStore.
665 typedef struct FieldStore
668 Expr *arg; /* input tuple value */
669 List *newvals; /* new value(s) for field(s) */
670 List *fieldnums; /* integer list of field attnums */
671 Oid resulttype; /* type of result (same as type of arg) */
672 /* Like RowExpr, we deliberately omit a typmod and collation here */
678 * RelabelType represents a "dummy" type coercion between two binary-
679 * compatible datatypes, such as reinterpreting the result of an OID
680 * expression as an int4. It is a no-op at runtime; we only need it
681 * to provide a place to store the correct type to be attributed to
682 * the expression result during type resolution. (We can't get away
683 * with just overwriting the type field of the input expression node,
684 * so we need a separate node to show the coercion's result type.)
688 typedef struct RelabelType
691 Expr *arg; /* input expression */
692 Oid resulttype; /* output type of coercion expression */
693 int32 resulttypmod; /* output typmod (usually -1) */
694 Oid resultcollid; /* OID of collation, or InvalidOid if none */
695 CoercionForm relabelformat; /* how to display this node */
696 int location; /* token location, or -1 if unknown */
702 * CoerceViaIO represents a type coercion between two types whose textual
703 * representations are compatible, implemented by invoking the source type's
704 * typoutput function then the destination type's typinput function.
708 typedef struct CoerceViaIO
711 Expr *arg; /* input expression */
712 Oid resulttype; /* output type of coercion */
713 /* output typmod is not stored, but is presumed -1 */
714 Oid resultcollid; /* OID of collation, or InvalidOid if none */
715 CoercionForm coerceformat; /* how to display this node */
716 int location; /* token location, or -1 if unknown */
722 * ArrayCoerceExpr represents a type coercion from one array type to another,
723 * which is implemented by applying the indicated element-type coercion
724 * function to each element of the source array. If elemfuncid is InvalidOid
725 * then the element types are binary-compatible, but the coercion still
726 * requires some effort (we have to fix the element type ID stored in the
731 typedef struct ArrayCoerceExpr
734 Expr *arg; /* input expression (yields an array) */
735 Oid elemfuncid; /* OID of element coercion function, or 0 */
736 Oid resulttype; /* output type of coercion (an array type) */
737 int32 resulttypmod; /* output typmod (also element typmod) */
738 Oid resultcollid; /* OID of collation, or InvalidOid if none */
739 bool isExplicit; /* conversion semantics flag to pass to func */
740 CoercionForm coerceformat; /* how to display this node */
741 int location; /* token location, or -1 if unknown */
747 * ConvertRowtypeExpr represents a type coercion from one composite type
748 * to another, where the source type is guaranteed to contain all the columns
749 * needed for the destination type plus possibly others; the columns need not
750 * be in the same positions, but are matched up by name. This is primarily
751 * used to convert a whole-row value of an inheritance child table into a
752 * valid whole-row value of its parent table's rowtype.
756 typedef struct ConvertRowtypeExpr
759 Expr *arg; /* input expression */
760 Oid resulttype; /* output type (always a composite type) */
761 /* Like RowExpr, we deliberately omit a typmod and collation here */
762 CoercionForm convertformat; /* how to display this node */
763 int location; /* token location, or -1 if unknown */
764 } ConvertRowtypeExpr;
767 * CollateExpr - COLLATE
769 * The planner replaces CollateExpr with RelabelType during expression
770 * preprocessing, so execution never sees a CollateExpr.
773 typedef struct CollateExpr
776 Expr *arg; /* input expression */
777 Oid collOid; /* collation's OID */
778 int location; /* token location, or -1 if unknown */
782 * CaseExpr - a CASE expression
784 * We support two distinct forms of CASE expression:
785 * CASE WHEN boolexpr THEN expr [ WHEN boolexpr THEN expr ... ]
786 * CASE testexpr WHEN compexpr THEN expr [ WHEN compexpr THEN expr ... ]
787 * These are distinguishable by the "arg" field being NULL in the first case
788 * and the testexpr in the second case.
790 * In the raw grammar output for the second form, the condition expressions
791 * of the WHEN clauses are just the comparison values. Parse analysis
792 * converts these to valid boolean expressions of the form
793 * CaseTestExpr '=' compexpr
794 * where the CaseTestExpr node is a placeholder that emits the correct
795 * value at runtime. This structure is used so that the testexpr need be
796 * evaluated only once. Note that after parse analysis, the condition
797 * expressions always yield boolean.
799 * Note: we can test whether a CaseExpr has been through parse analysis
800 * yet by checking whether casetype is InvalidOid or not.
803 typedef struct CaseExpr
806 Oid casetype; /* type of expression result */
807 Oid casecollid; /* OID of collation, or InvalidOid if none */
808 Expr *arg; /* implicit equality comparison argument */
809 List *args; /* the arguments (list of WHEN clauses) */
810 Expr *defresult; /* the default result (ELSE clause) */
811 int location; /* token location, or -1 if unknown */
815 * CaseWhen - one arm of a CASE expression
817 typedef struct CaseWhen
820 Expr *expr; /* condition expression */
821 Expr *result; /* substitution result */
822 int location; /* token location, or -1 if unknown */
826 * Placeholder node for the test value to be processed by a CASE expression.
827 * This is effectively like a Param, but can be implemented more simply
828 * since we need only one replacement value at a time.
830 * We also use this in nested UPDATE expressions.
831 * See transformAssignmentIndirection().
833 typedef struct CaseTestExpr
836 Oid typeId; /* type for substituted value */
837 int32 typeMod; /* typemod for substituted value */
838 Oid collation; /* collation for the substituted value */
842 * ArrayExpr - an ARRAY[] expression
844 * Note: if multidims is false, the constituent expressions all yield the
845 * scalar type identified by element_typeid. If multidims is true, the
846 * constituent expressions all yield arrays of element_typeid (ie, the same
847 * type as array_typeid); at runtime we must check for compatible subscripts.
849 typedef struct ArrayExpr
852 Oid array_typeid; /* type of expression result */
853 Oid array_collid; /* OID of collation, or InvalidOid if none */
854 Oid element_typeid; /* common type of array elements */
855 List *elements; /* the array elements or sub-arrays */
856 bool multidims; /* true if elements are sub-arrays */
857 int location; /* token location, or -1 if unknown */
861 * RowExpr - a ROW() expression
863 * Note: the list of fields must have a one-for-one correspondence with
864 * physical fields of the associated rowtype, although it is okay for it
865 * to be shorter than the rowtype. That is, the N'th list element must
866 * match up with the N'th physical field. When the N'th physical field
867 * is a dropped column (attisdropped) then the N'th list element can just
868 * be a NULL constant. (This case can only occur for named composite types,
869 * not RECORD types, since those are built from the RowExpr itself rather
870 * than vice versa.) It is important not to assume that length(args) is
871 * the same as the number of columns logically present in the rowtype.
873 * colnames provides field names in cases where the names can't easily be
874 * obtained otherwise. Names *must* be provided if row_typeid is RECORDOID.
875 * If row_typeid identifies a known composite type, colnames can be NIL to
876 * indicate the type's cataloged field names apply. Note that colnames can
877 * be non-NIL even for a composite type, and typically is when the RowExpr
878 * was created by expanding a whole-row Var. This is so that we can retain
879 * the column alias names of the RTE that the Var referenced (which would
880 * otherwise be very difficult to extract from the parsetree). Like the
881 * args list, colnames is one-for-one with physical fields of the rowtype.
883 typedef struct RowExpr
886 List *args; /* the fields */
887 Oid row_typeid; /* RECORDOID or a composite type's ID */
890 * Note: we deliberately do NOT store a typmod. Although a typmod will be
891 * associated with specific RECORD types at runtime, it will differ for
892 * different backends, and so cannot safely be stored in stored
893 * parsetrees. We must assume typmod -1 for a RowExpr node.
895 * We don't need to store a collation either. The result type is
896 * necessarily composite, and composite types never have a collation.
898 CoercionForm row_format; /* how to display this node */
899 List *colnames; /* list of String, or NIL */
900 int location; /* token location, or -1 if unknown */
904 * RowCompareExpr - row-wise comparison, such as (a, b) <= (1, 2)
906 * We support row comparison for any operator that can be determined to
907 * act like =, <>, <, <=, >, or >= (we determine this by looking for the
908 * operator in btree opfamilies). Note that the same operator name might
909 * map to a different operator for each pair of row elements, since the
910 * element datatypes can vary.
912 * A RowCompareExpr node is only generated for the < <= > >= cases;
913 * the = and <> cases are translated to simple AND or OR combinations
914 * of the pairwise comparisons. However, we include = and <> in the
915 * RowCompareType enum for the convenience of parser logic.
917 typedef enum RowCompareType
919 /* Values of this enum are chosen to match btree strategy numbers */
920 ROWCOMPARE_LT = 1, /* BTLessStrategyNumber */
921 ROWCOMPARE_LE = 2, /* BTLessEqualStrategyNumber */
922 ROWCOMPARE_EQ = 3, /* BTEqualStrategyNumber */
923 ROWCOMPARE_GE = 4, /* BTGreaterEqualStrategyNumber */
924 ROWCOMPARE_GT = 5, /* BTGreaterStrategyNumber */
925 ROWCOMPARE_NE = 6 /* no such btree strategy */
928 typedef struct RowCompareExpr
931 RowCompareType rctype; /* LT LE GE or GT, never EQ or NE */
932 List *opnos; /* OID list of pairwise comparison ops */
933 List *opfamilies; /* OID list of containing operator families */
934 List *inputcollids; /* OID list of collations for comparisons */
935 List *largs; /* the left-hand input arguments */
936 List *rargs; /* the right-hand input arguments */
940 * CoalesceExpr - a COALESCE expression
942 typedef struct CoalesceExpr
945 Oid coalescetype; /* type of expression result */
946 Oid coalescecollid; /* OID of collation, or InvalidOid if none */
947 List *args; /* the arguments */
948 int location; /* token location, or -1 if unknown */
952 * MinMaxExpr - a GREATEST or LEAST function
954 typedef enum MinMaxOp
960 typedef struct MinMaxExpr
963 Oid minmaxtype; /* common type of arguments and result */
964 Oid minmaxcollid; /* OID of collation of result */
965 Oid inputcollid; /* OID of collation that function should use */
966 MinMaxOp op; /* function to execute */
967 List *args; /* the arguments */
968 int location; /* token location, or -1 if unknown */
972 * XmlExpr - various SQL/XML functions requiring special grammar productions
974 * 'name' carries the "NAME foo" argument (already XML-escaped).
975 * 'named_args' and 'arg_names' represent an xml_attribute list.
976 * 'args' carries all other arguments.
978 * Note: result type/typmod/collation are not stored, but can be deduced
979 * from the XmlExprOp. The type/typmod fields are just used for display
980 * purposes, and are NOT necessarily the true result type of the node.
981 * (We also use type == InvalidOid to mark a not-yet-parse-analyzed XmlExpr.)
983 typedef enum XmlExprOp
985 IS_XMLCONCAT, /* XMLCONCAT(args) */
986 IS_XMLELEMENT, /* XMLELEMENT(name, xml_attributes, args) */
987 IS_XMLFOREST, /* XMLFOREST(xml_attributes) */
988 IS_XMLPARSE, /* XMLPARSE(text, is_doc, preserve_ws) */
989 IS_XMLPI, /* XMLPI(name [, args]) */
990 IS_XMLROOT, /* XMLROOT(xml, version, standalone) */
991 IS_XMLSERIALIZE, /* XMLSERIALIZE(is_document, xmlval) */
992 IS_DOCUMENT /* xmlval IS DOCUMENT */
1001 typedef struct XmlExpr
1004 XmlExprOp op; /* xml function ID */
1005 char *name; /* name in xml(NAME foo ...) syntaxes */
1006 List *named_args; /* non-XML expressions for xml_attributes */
1007 List *arg_names; /* parallel list of Value strings */
1008 List *args; /* list of expressions */
1009 XmlOptionType xmloption; /* DOCUMENT or CONTENT */
1010 Oid type; /* target type/typmod for XMLSERIALIZE */
1012 int location; /* token location, or -1 if unknown */
1018 * NullTest represents the operation of testing a value for NULLness.
1019 * The appropriate test is performed and returned as a boolean Datum.
1021 * NOTE: the semantics of this for rowtype inputs are noticeably different
1022 * from the scalar case. We provide an "argisrow" flag to reflect that.
1026 typedef enum NullTestType
1028 IS_NULL, IS_NOT_NULL
1031 typedef struct NullTest
1034 Expr *arg; /* input expression */
1035 NullTestType nulltesttype; /* IS NULL, IS NOT NULL */
1036 bool argisrow; /* T if input is of a composite type */
1042 * BooleanTest represents the operation of determining whether a boolean
1043 * is TRUE, FALSE, or UNKNOWN (ie, NULL). All six meaningful combinations
1044 * are supported. Note that a NULL input does *not* cause a NULL result.
1045 * The appropriate test is performed and returned as a boolean Datum.
1048 typedef enum BoolTestType
1050 IS_TRUE, IS_NOT_TRUE, IS_FALSE, IS_NOT_FALSE, IS_UNKNOWN, IS_NOT_UNKNOWN
1053 typedef struct BooleanTest
1056 Expr *arg; /* input expression */
1057 BoolTestType booltesttype; /* test type */
1063 * CoerceToDomain represents the operation of coercing a value to a domain
1064 * type. At runtime (and not before) the precise set of constraints to be
1065 * checked will be determined. If the value passes, it is returned as the
1066 * result; if not, an error is raised. Note that this is equivalent to
1067 * RelabelType in the scenario where no constraints are applied.
1069 typedef struct CoerceToDomain
1072 Expr *arg; /* input expression */
1073 Oid resulttype; /* domain type ID (result type) */
1074 int32 resulttypmod; /* output typmod (currently always -1) */
1075 Oid resultcollid; /* OID of collation, or InvalidOid if none */
1076 CoercionForm coercionformat; /* how to display this node */
1077 int location; /* token location, or -1 if unknown */
1081 * Placeholder node for the value to be processed by a domain's check
1082 * constraint. This is effectively like a Param, but can be implemented more
1083 * simply since we need only one replacement value at a time.
1085 * Note: the typeId/typeMod/collation will be set from the domain's base type,
1086 * not the domain itself. This is because we shouldn't consider the value
1087 * to be a member of the domain if we haven't yet checked its constraints.
1089 typedef struct CoerceToDomainValue
1092 Oid typeId; /* type for substituted value */
1093 int32 typeMod; /* typemod for substituted value */
1094 Oid collation; /* collation for the substituted value */
1095 int location; /* token location, or -1 if unknown */
1096 } CoerceToDomainValue;
1099 * Placeholder node for a DEFAULT marker in an INSERT or UPDATE command.
1101 * This is not an executable expression: it must be replaced by the actual
1102 * column default expression during rewriting. But it is convenient to
1103 * treat it as an expression node during parsing and rewriting.
1105 typedef struct SetToDefault
1108 Oid typeId; /* type for substituted value */
1109 int32 typeMod; /* typemod for substituted value */
1110 Oid collation; /* collation for the substituted value */
1111 int location; /* token location, or -1 if unknown */
1115 * Node representing [WHERE] CURRENT OF cursor_name
1117 * CURRENT OF is a bit like a Var, in that it carries the rangetable index
1118 * of the target relation being constrained; this aids placing the expression
1119 * correctly during planning. We can assume however that its "levelsup" is
1120 * always zero, due to the syntactic constraints on where it can appear.
1122 * The referenced cursor can be represented either as a hardwired string
1123 * or as a reference to a run-time parameter of type REFCURSOR. The latter
1124 * case is for the convenience of plpgsql.
1126 typedef struct CurrentOfExpr
1129 Index cvarno; /* RT index of target relation */
1130 char *cursor_name; /* name of referenced cursor, or NULL */
1131 int cursor_param; /* refcursor parameter number, or 0 */
1134 /*--------------------
1136 * a target entry (used in query target lists)
1138 * Strictly speaking, a TargetEntry isn't an expression node (since it can't
1139 * be evaluated by ExecEvalExpr). But we treat it as one anyway, since in
1140 * very many places it's convenient to process a whole query targetlist as a
1141 * single expression tree.
1143 * In a SELECT's targetlist, resno should always be equal to the item's
1144 * ordinal position (counting from 1). However, in an INSERT or UPDATE
1145 * targetlist, resno represents the attribute number of the destination
1146 * column for the item; so there may be missing or out-of-order resnos.
1147 * It is even legal to have duplicated resnos; consider
1148 * UPDATE table SET arraycol[1] = ..., arraycol[2] = ..., ...
1149 * The two meanings come together in the executor, because the planner
1150 * transforms INSERT/UPDATE tlists into a normalized form with exactly
1151 * one entry for each column of the destination table. Before that's
1152 * happened, however, it is risky to assume that resno == position.
1153 * Generally get_tle_by_resno() should be used rather than list_nth()
1154 * to fetch tlist entries by resno, and only in SELECT should you assume
1155 * that resno is a unique identifier.
1157 * resname is required to represent the correct column name in non-resjunk
1158 * entries of top-level SELECT targetlists, since it will be used as the
1159 * column title sent to the frontend. In most other contexts it is only
1160 * a debugging aid, and may be wrong or even NULL. (In particular, it may
1161 * be wrong in a tlist from a stored rule, if the referenced column has been
1162 * renamed by ALTER TABLE since the rule was made. Also, the planner tends
1163 * to store NULL rather than look up a valid name for tlist entries in
1164 * non-toplevel plan nodes.) In resjunk entries, resname should be either
1165 * a specific system-generated name (such as "ctid") or NULL; anything else
1166 * risks confusing ExecGetJunkAttribute!
1168 * ressortgroupref is used in the representation of ORDER BY, GROUP BY, and
1169 * DISTINCT items. Targetlist entries with ressortgroupref=0 are not
1170 * sort/group items. If ressortgroupref>0, then this item is an ORDER BY,
1171 * GROUP BY, and/or DISTINCT target value. No two entries in a targetlist
1172 * may have the same nonzero ressortgroupref --- but there is no particular
1173 * meaning to the nonzero values, except as tags. (For example, one must
1174 * not assume that lower ressortgroupref means a more significant sort key.)
1175 * The order of the associated SortGroupClause lists determine the semantics.
1177 * resorigtbl/resorigcol identify the source of the column, if it is a
1178 * simple reference to a column of a base table (or view). If it is not
1179 * a simple reference, these fields are zeroes.
1181 * If resjunk is true then the column is a working column (such as a sort key)
1182 * that should be removed from the final output of the query. Resjunk columns
1183 * must have resnos that cannot duplicate any regular column's resno. Also
1184 * note that there are places that assume resjunk columns come after non-junk
1186 *--------------------
1188 typedef struct TargetEntry
1191 Expr *expr; /* expression to evaluate */
1192 AttrNumber resno; /* attribute number (see notes above) */
1193 char *resname; /* name of the column (could be NULL) */
1194 Index ressortgroupref;/* nonzero if referenced by a sort/group
1196 Oid resorigtbl; /* OID of column's source table */
1197 AttrNumber resorigcol; /* column's number in source table */
1198 bool resjunk; /* set to true to eliminate the attribute from
1199 * final target list */
1203 /* ----------------------------------------------------------------
1204 * node types for join trees
1206 * The leaves of a join tree structure are RangeTblRef nodes. Above
1207 * these, JoinExpr nodes can appear to denote a specific kind of join
1208 * or qualified join. Also, FromExpr nodes can appear to denote an
1209 * ordinary cross-product join ("FROM foo, bar, baz WHERE ...").
1210 * FromExpr is like a JoinExpr of jointype JOIN_INNER, except that it
1211 * may have any number of child nodes, not just two.
1213 * NOTE: the top level of a Query's jointree is always a FromExpr.
1214 * Even if the jointree contains no rels, there will be a FromExpr.
1216 * NOTE: the qualification expressions present in JoinExpr nodes are
1217 * *in addition to* the query's main WHERE clause, which appears as the
1218 * qual of the top-level FromExpr. The reason for associating quals with
1219 * specific nodes in the jointree is that the position of a qual is critical
1220 * when outer joins are present. (If we enforce a qual too soon or too late,
1221 * that may cause the outer join to produce the wrong set of NULL-extended
1222 * rows.) If all joins are inner joins then all the qual positions are
1223 * semantically interchangeable.
1225 * NOTE: in the raw output of gram.y, a join tree contains RangeVar,
1226 * RangeSubselect, and RangeFunction nodes, which are all replaced by
1227 * RangeTblRef nodes during the parse analysis phase. Also, the top-level
1228 * FromExpr is added during parse analysis; the grammar regards FROM and
1229 * WHERE as separate.
1230 * ----------------------------------------------------------------
1234 * RangeTblRef - reference to an entry in the query's rangetable
1236 * We could use direct pointers to the RT entries and skip having these
1237 * nodes, but multiple pointers to the same node in a querytree cause
1238 * lots of headaches, so it seems better to store an index into the RT.
1240 typedef struct RangeTblRef
1247 * JoinExpr - for SQL JOIN expressions
1249 * isNatural, usingClause, and quals are interdependent. The user can write
1250 * only one of NATURAL, USING(), or ON() (this is enforced by the grammar).
1251 * If he writes NATURAL then parse analysis generates the equivalent USING()
1252 * list, and from that fills in "quals" with the right equality comparisons.
1253 * If he writes USING() then "quals" is filled with equality comparisons.
1254 * If he writes ON() then only "quals" is set. Note that NATURAL/USING
1255 * are not equivalent to ON() since they also affect the output column list.
1257 * alias is an Alias node representing the AS alias-clause attached to the
1258 * join expression, or NULL if no clause. NB: presence or absence of the
1259 * alias has a critical impact on semantics, because a join with an alias
1260 * restricts visibility of the tables/columns inside it.
1262 * During parse analysis, an RTE is created for the Join, and its index
1263 * is filled into rtindex. This RTE is present mainly so that Vars can
1264 * be created that refer to the outputs of the join. The planner sometimes
1265 * generates JoinExprs internally; these can have rtindex = 0 if there are
1266 * no join alias variables referencing such joins.
1269 typedef struct JoinExpr
1272 JoinType jointype; /* type of join */
1273 bool isNatural; /* Natural join? Will need to shape table */
1274 Node *larg; /* left subtree */
1275 Node *rarg; /* right subtree */
1276 List *usingClause; /* USING clause, if any (list of String) */
1277 Node *quals; /* qualifiers on join, if any */
1278 Alias *alias; /* user-written alias clause, if any */
1279 int rtindex; /* RT index assigned for join, or 0 */
1283 * FromExpr - represents a FROM ... WHERE ... construct
1285 * This is both more flexible than a JoinExpr (it can have any number of
1286 * children, including zero) and less so --- we don't need to deal with
1287 * aliases and so on. The output column set is implicitly just the union
1288 * of the outputs of the children.
1291 typedef struct FromExpr
1294 List *fromlist; /* List of join subtrees */
1295 Node *quals; /* qualifiers on join, if any */
1298 #endif /* PRIMNODES_H */