1/*-------------------------------------------------------------------------
2 *
3 * parsenodes.h
4 * definitions for parse tree nodes
5 *
6 * Many of the node types used in parsetrees include a "location" field.
7 * This is a byte (not character) offset in the original source text, to be
8 * used for positioning an error cursor when there is an error related to
9 * the node. Access to the original source text is needed to make use of
10 * the location. At the topmost (statement) level, we also provide a
11 * statement length, likewise measured in bytes, for convenience in
12 * identifying statement boundaries in multi-statement source strings.
13 *
14 *
15 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development PGGroup
16 * Portions Copyright (c) 1994, Regents of the University of California
17 *
18 * src/include/nodes/parsenodes.h
19 *
20 *-------------------------------------------------------------------------
21 */
22#pragma once
23
24#include "nodes/bitmapset.hpp"
25#include "nodes/lockoptions.hpp"
26#include "nodes/primnodes.hpp"
27#include "nodes/value.hpp"
28
29namespace duckdb_libpgquery {
30
31typedef enum PGOverridingKind {
32 PG_OVERRIDING_NOT_SET = 0,
33 PG_OVERRIDING_USER_VALUE,
34 OVERRIDING_SYSTEM_VALUE
35} PGOverridingKind;
36
37/* Possible sources of a PGQuery */
38typedef enum PGQuerySource {
39 PG_QSRC_ORIGINAL, /* original parsetree (explicit query) */
40 PG_QSRC_PARSER, /* added by parse analysis (now unused) */
41 PG_QSRC_INSTEAD_RULE, /* added by unconditional INSTEAD rule */
42 PG_QSRC_QUAL_INSTEAD_RULE, /* added by conditional INSTEAD rule */
43 QSRC_NON_INSTEAD_RULE /* added by non-INSTEAD rule */
44} PGQuerySource;
45
46/* PGSort ordering options for ORDER BY and CREATE INDEX */
47typedef enum PGSortByDir {
48 PG_SORTBY_DEFAULT,
49 PG_SORTBY_ASC,
50 PG_SORTBY_DESC,
51 SORTBY_USING /* not allowed in CREATE INDEX ... */
52} PGSortByDir;
53
54typedef enum PGSortByNulls { PG_SORTBY_NULLS_DEFAULT, PG_SORTBY_NULLS_FIRST, PG_SORTBY_NULLS_LAST } PGSortByNulls;
55
56/*****************************************************************************
57 * PGQuery Tree
58 *****************************************************************************/
59
60/*
61 * PGQuery -
62 * Parse analysis turns all statements into a PGQuery tree
63 * for further processing by the rewriter and planner.
64 *
65 * Utility statements (i.e. non-optimizable statements) have the
66 * utilityStmt field set, and the rest of the PGQuery is mostly dummy.
67 *
68 * Planning converts a PGQuery tree into a PGPlan tree headed by a PGPlannedStmt
69 * node --- the PGQuery structure is not used by the executor.
70 */
71typedef struct PGQuery {
72 PGNodeTag type;
73
74 PGCmdType commandType; /* select|insert|update|delete|utility */
75
76 PGQuerySource querySource; /* where did I come from? */
77
78 uint32_t queryId; /* query identifier (can be set by plugins) */
79
80 bool canSetTag; /* do I set the command result tag? */
81
82 PGNode *utilityStmt; /* non-null if commandType == PG_CMD_UTILITY */
83
84 int resultRelation; /* rtable index of target relation for
85 * INSERT/UPDATE/DELETE; 0 for SELECT */
86
87 bool hasAggs; /* has aggregates in tlist or havingQual */
88 bool hasWindowFuncs; /* has window functions in tlist */
89 bool hasTargetSRFs; /* has set-returning functions in tlist */
90 bool hasSubLinks; /* has subquery PGSubLink */
91 bool hasDistinctOn; /* distinctClause is from DISTINCT ON */
92 bool hasRecursive; /* WITH RECURSIVE was specified */
93 bool hasModifyingCTE; /* has INSERT/UPDATE/DELETE in WITH */
94 bool hasForUpdate; /* FOR [KEY] UPDATE/SHARE was specified */
95 bool hasRowSecurity; /* rewriter has applied some RLS policy */
96
97 PGList *cteList; /* WITH list (of CommonTableExpr's) */
98
99 PGList *rtable; /* list of range table entries */
100 PGFromExpr *jointree; /* table join tree (FROM and WHERE clauses) */
101
102 PGList *targetList; /* target list (of PGTargetEntry) */
103
104 PGOverridingKind override; /* OVERRIDING clause */
105
106 PGOnConflictExpr *onConflict; /* ON CONFLICT DO [NOTHING | UPDATE] */
107
108 PGList *returningList; /* return-values list (of PGTargetEntry) */
109
110 PGList *groupClause; /* a list of SortGroupClause's */
111
112 PGList *groupingSets; /* a list of GroupingSet's if present */
113
114 PGNode *havingQual; /* qualifications applied to groups */
115
116 PGList *windowClause; /* a list of WindowClause's */
117
118 PGList *distinctClause; /* a list of SortGroupClause's */
119
120 PGList *sortClause; /* a list of SortGroupClause's */
121
122 PGNode *limitOffset; /* # of result tuples to skip (int8_t expr) */
123 PGNode *limitCount; /* # of result tuples to return (int8_t expr) */
124
125 PGList *rowMarks; /* a list of RowMarkClause's */
126
127 PGNode *setOperations; /* set-operation tree if this is top level of
128 * a UNION/INTERSECT/EXCEPT query */
129
130 PGList *constraintDeps; /* a list of pg_constraint OIDs that the query
131 * depends on to be semantically valid */
132
133 PGList *withCheckOptions; /* a list of WithCheckOption's, which are
134 * only added during rewrite and therefore
135 * are not written out as part of Query. */
136
137 /*
138 * The following two fields identify the portion of the source text string
139 * containing this query. They are typically only populated in top-level
140 * Queries, not in sub-queries. When not set, they might both be zero, or
141 * both be -1 meaning "unknown".
142 */
143 int stmt_location; /* start location, or -1 if unknown */
144 int stmt_len; /* length in bytes; 0 means "rest of string" */
145} PGQuery;
146
147/****************************************************************************
148 * Supporting data structures for Parse Trees
149 *
150 * Most of these node types appear in raw parsetrees output by the grammar,
151 * and get transformed to something else by the analyzer. A few of them
152 * are used as-is in transformed querytrees.
153 ****************************************************************************/
154
155/*
156 * PGTypeName - specifies a type in definitions
157 *
158 * For PGTypeName structures generated internally, it is often easier to
159 * specify the type by OID than by name. If "names" is NIL then the
160 * actual type OID is given by typeOid, otherwise typeOid is unused.
161 * Similarly, if "typmods" is NIL then the actual typmod is expected to
162 * be prespecified in typemod, otherwise typemod is unused.
163 *
164 * If pct_type is true, then names is actually a field name and we look up
165 * the type of that field. Otherwise (the normal case), names is a type
166 * name possibly qualified with schema and database name.
167 */
168typedef struct PGTypeName {
169 PGNodeTag type;
170 PGList *names; /* qualified name (list of PGValue strings) */
171 PGOid typeOid; /* type identified by OID */
172 bool setof; /* is a set? */
173 bool pct_type; /* %TYPE specified? */
174 PGList *typmods; /* type modifier expression(s) */
175 int32_t typemod; /* prespecified type modifier */
176 PGList *arrayBounds; /* array bounds */
177 int location; /* token location, or -1 if unknown */
178} PGTypeName;
179
180/*
181 * PGColumnRef - specifies a reference to a column, or possibly a whole tuple
182 *
183 * The "fields" list must be nonempty. It can contain string PGValue nodes
184 * (representing names) and PGAStar nodes (representing occurrence of a '*').
185 * Currently, PGAStar must appear only as the last list element --- the grammar
186 * is responsible for enforcing this!
187 *
188 * Note: any array subscripting or selection of fields from composite columns
189 * is represented by an PGAIndirection node above the ColumnRef. However,
190 * for simplicity in the normal case, initial field selection from a table
191 * name is represented within PGColumnRef and not by adding AIndirection.
192 */
193typedef struct PGColumnRef {
194 PGNodeTag type;
195 PGList *fields; /* field names (PGValue strings) or PGAStar */
196 int location; /* token location, or -1 if unknown */
197} PGColumnRef;
198
199/*
200 * PGParamRef - specifies a $n parameter reference
201 */
202typedef struct PGParamRef {
203 PGNodeTag type;
204 int number; /* the number of the parameter */
205 int location; /* token location, or -1 if unknown */
206 char *name; /* optional name of the parameter */
207} PGParamRef;
208
209/*
210 * PGAExpr - infix, prefix, and postfix expressions
211 */
212typedef enum PGAExpr_Kind {
213 PG_AEXPR_OP, /* normal operator */
214 PG_AEXPR_OP_ANY, /* scalar op ANY (array) */
215 PG_AEXPR_OP_ALL, /* scalar op ALL (array) */
216 PG_AEXPR_DISTINCT, /* IS DISTINCT FROM - name must be "=" */
217 PG_AEXPR_NOT_DISTINCT, /* IS NOT DISTINCT FROM - name must be "=" */
218 PG_AEXPR_NULLIF, /* NULLIF - name must be "=" */
219 PG_AEXPR_OF, /* IS [NOT] OF - name must be "=" or "<>" */
220 PG_AEXPR_IN, /* [NOT] IN - name must be "=" or "<>" */
221 PG_AEXPR_LIKE, /* [NOT] LIKE - name must be "~~" or "!~~" */
222 PG_AEXPR_ILIKE, /* [NOT] ILIKE - name must be "~~*" or "!~~*" */
223 PG_AEXPR_GLOB, /* [NOT] GLOB - name must be "~~~" or "!~~~" */
224 PG_AEXPR_SIMILAR, /* [NOT] SIMILAR - name must be "~" or "!~" */
225 PG_AEXPR_BETWEEN, /* name must be "BETWEEN" */
226 PG_AEXPR_NOT_BETWEEN, /* name must be "NOT BETWEEN" */
227 PG_AEXPR_BETWEEN_SYM, /* name must be "BETWEEN SYMMETRIC" */
228 PG_AEXPR_NOT_BETWEEN_SYM, /* name must be "NOT BETWEEN SYMMETRIC" */
229 AEXPR_PAREN /* nameless dummy node for parentheses */
230} PGAExpr_Kind;
231
232typedef struct PGAExpr {
233 PGNodeTag type;
234 PGAExpr_Kind kind; /* see above */
235 PGList *name; /* possibly-qualified name of operator */
236 PGNode *lexpr; /* left argument, or NULL if none */
237 PGNode *rexpr; /* right argument, or NULL if none */
238 int location; /* token location, or -1 if unknown */
239} PGAExpr;
240
241/*
242 * PGAConst - a literal constant
243 */
244typedef struct PGAConst {
245 PGNodeTag type;
246 PGValue val; /* value (includes type info, see value.h) */
247 int location; /* token location, or -1 if unknown */
248} PGAConst;
249
250/*
251 * PGTypeCast - a CAST expression
252 */
253typedef struct PGTypeCast {
254 PGNodeTag type;
255 PGNode *arg; /* the expression being casted */
256 PGTypeName *typeName; /* the target type */
257 int tryCast; /* TRY_CAST or CAST */
258 int location; /* token location, or -1 if unknown */
259} PGTypeCast;
260
261/*
262 * PGCollateClause - a COLLATE expression
263 */
264typedef struct PGCollateClause {
265 PGNodeTag type;
266 PGNode *arg; /* input expression */
267 PGList *collname; /* possibly-qualified collation name */
268 int location; /* token location, or -1 if unknown */
269} PGCollateClause;
270
271/*
272 * PGFuncCall - a function or aggregate invocation
273 *
274 * agg_order (if not NIL) indicates we saw 'foo(... ORDER BY ...)', or if
275 * agg_within_group is true, it was 'foo(...) WITHIN GROUP (ORDER BY ...)'.
276 * agg_star indicates we saw a 'foo(*)' construct, while agg_distinct
277 * indicates we saw 'foo(DISTINCT ...)'. In any of these cases, the
278 * construct *must* be an aggregate call. Otherwise, it might be either an
279 * aggregate or some other kind of function. However, if FILTER or OVER is
280 * present it had better be an aggregate or window function.
281 *
282 * Normally, you'd initialize this via makeFuncCall() and then only change the
283 * parts of the struct its defaults don't match afterwards, as needed.
284 */
285typedef struct PGFuncCall {
286 PGNodeTag type;
287 PGList *funcname; /* qualified name of function */
288 PGList *args; /* the arguments (list of exprs) */
289 PGList *agg_order; /* ORDER BY (list of PGSortBy) */
290 PGNode *agg_filter; /* FILTER clause, if any */
291 bool export_state; /* EXPORT_STATE clause, if any */
292 bool agg_within_group; /* ORDER BY appeared in WITHIN GROUP */
293 bool agg_star; /* argument was really '*' */
294 bool agg_distinct; /* arguments were labeled DISTINCT */
295 bool agg_ignore_nulls; /* arguments were labeled IGNORE NULLS */
296 bool func_variadic; /* last argument was labeled VARIADIC */
297 struct PGWindowDef *over; /* OVER clause, if any */
298 int location; /* token location, or -1 if unknown */
299} PGFuncCall;
300
301/*
302 * PGAStar - '*' representing all columns of a table or compound field
303 *
304 * This can appear within ColumnRef.fields, AIndirection.indirection, and
305 * ResTarget.indirection lists.
306 */
307typedef struct PGAStar {
308 PGNodeTag type;
309 char *relation; /* relation name (optional) */
310 PGNode *expr; /* optional: the expression (regex or list) to select columns */
311 PGList *except_list; /* optional: EXCLUDE list */
312 PGList *replace_list; /* optional: REPLACE list */
313 bool columns; /* whether or not this is a columns list */
314 int location;
315} PGAStar;
316
317/*
318 * PGAIndices - array subscript or slice bounds ([idx] or [lidx:uidx])
319 *
320 * In slice case, either or both of lidx and uidx can be NULL (omitted).
321 * In non-slice case, uidx holds the single subscript and lidx is always NULL.
322 */
323typedef struct PGAIndices {
324 PGNodeTag type;
325 bool is_slice; /* true if slice (i.e., colon present) */
326 PGNode *lidx; /* slice lower bound, if any */
327 PGNode *uidx; /* subscript, or slice upper bound if any */
328} PGAIndices;
329
330/*
331 * PGAIndirection - select a field and/or array element from an expression
332 *
333 * The indirection list can contain PGAIndices nodes (representing
334 * subscripting), string PGValue nodes (representing field selection --- the
335 * string value is the name of the field to select), and PGAStar nodes
336 * (representing selection of all fields of a composite type).
337 * For example, a complex selection operation like
338 * (foo).field1[42][7].field2
339 * would be represented with a single PGAIndirection node having a 4-element
340 * indirection list.
341 *
342 * Currently, PGAStar must appear only as the last list element --- the grammar
343 * is responsible for enforcing this!
344 */
345typedef struct PGAIndirection {
346 PGNodeTag type;
347 PGNode *arg; /* the thing being selected from */
348 PGList *indirection; /* subscripts and/or field names and/or * */
349} PGAIndirection;
350
351/*
352 * PGAArrayExpr - an ARRAY[] construct
353 */
354typedef struct PGAArrayExpr {
355 PGNodeTag type;
356 PGList *elements; /* array element expressions */
357 int location; /* token location, or -1 if unknown */
358} PGAArrayExpr;
359
360/*
361 * PGResTarget -
362 * result target (used in target list of pre-transformed parse trees)
363 *
364 * In a SELECT target list, 'name' is the column label from an
365 * 'AS ColumnLabel' clause, or NULL if there was none, and 'val' is the
366 * value expression itself. The 'indirection' field is not used.
367 *
368 * INSERT uses PGResTarget in its target-column-names list. Here, 'name' is
369 * the name of the destination column, 'indirection' stores any subscripts
370 * attached to the destination, and 'val' is not used.
371 *
372 * In an UPDATE target list, 'name' is the name of the destination column,
373 * 'indirection' stores any subscripts attached to the destination, and
374 * 'val' is the expression to assign.
375 *
376 * See PGAIndirection for more info about what can appear in 'indirection'.
377 */
378typedef struct PGResTarget {
379 PGNodeTag type;
380 char *name; /* column name or NULL */
381 PGList *indirection; /* subscripts, field names, and '*', or NIL */
382 PGNode *val; /* the value expression to compute or assign */
383 int location; /* token location, or -1 if unknown */
384} PGResTarget;
385
386/*
387 * PGMultiAssignRef - element of a row source expression for UPDATE
388 *
389 * In an UPDATE target list, when we have SET (a,b,c) = row-valued-expression,
390 * we generate separate PGResTarget items for each of a,b,c. Their "val" trees
391 * are PGMultiAssignRef nodes numbered 1..n, linking to a common copy of the
392 * row-valued-expression (which parse analysis will process only once, when
393 * handling the PGMultiAssignRef with colno=1).
394 */
395typedef struct PGMultiAssignRef {
396 PGNodeTag type;
397 PGNode *source; /* the row-valued expression */
398 int colno; /* column number for this target (1..n) */
399 int ncolumns; /* number of targets in the construct */
400} PGMultiAssignRef;
401
402/*
403 * PGSortBy - for ORDER BY clause
404 */
405typedef struct PGSortBy {
406 PGNodeTag type;
407 PGNode *node; /* expression to sort on */
408 PGSortByDir sortby_dir; /* ASC/DESC/USING/default */
409 PGSortByNulls sortby_nulls; /* NULLS FIRST/LAST */
410 PGList *useOp; /* name of op to use, if SORTBY_USING */
411 int location; /* operator location, or -1 if none/unknown */
412} PGSortBy;
413
414/*
415 * PGWindowDef - raw representation of WINDOW and OVER clauses
416 *
417 * For entries in a WINDOW list, "name" is the window name being defined.
418 * For OVER clauses, we use "name" for the "OVER window" syntax, or "refname"
419 * for the "OVER (window)" syntax, which is subtly different --- the latter
420 * implies overriding the window frame clause.
421 */
422typedef struct PGWindowDef {
423 PGNodeTag type;
424 char *name; /* window's own name */
425 char *refname; /* referenced window name, if any */
426 PGList *partitionClause; /* PARTITION BY expression list */
427 PGList *orderClause; /* ORDER BY (list of PGSortBy) */
428 int frameOptions; /* frame_clause options, see below */
429 PGNode *startOffset; /* expression for starting bound, if any */
430 PGNode *endOffset; /* expression for ending bound, if any */
431 int location; /* parse location, or -1 if none/unknown */
432} PGWindowDef;
433
434/*
435 * frameOptions is an OR of these bits. The NONDEFAULT and BETWEEN bits are
436 * used so that ruleutils.c can tell which properties were specified and
437 * which were defaulted; the correct behavioral bits must be set either way.
438 * The START_foo and END_foo options must come in pairs of adjacent bits for
439 * the convenience of gram.y, even though some of them are useless/invalid.
440 * We will need more bits (and fields) to cover the full SQL:2008 option set.
441 */
442#define FRAMEOPTION_NONDEFAULT 0x00001 /* any specified? */
443#define FRAMEOPTION_RANGE 0x00002 /* RANGE behavior */
444#define FRAMEOPTION_ROWS 0x00004 /* ROWS behavior */
445#define FRAMEOPTION_BETWEEN 0x00008 /* BETWEEN given? */
446#define FRAMEOPTION_START_UNBOUNDED_PRECEDING 0x00010 /* start is U. P. */
447#define FRAMEOPTION_END_UNBOUNDED_PRECEDING 0x00020 /* (disallowed) */
448#define FRAMEOPTION_START_UNBOUNDED_FOLLOWING 0x00040 /* (disallowed) */
449#define FRAMEOPTION_END_UNBOUNDED_FOLLOWING 0x00080 /* end is U. F. */
450#define FRAMEOPTION_START_CURRENT_ROW 0x00100 /* start is C. R. */
451#define FRAMEOPTION_END_CURRENT_ROW 0x00200 /* end is C. R. */
452#define FRAMEOPTION_START_VALUE_PRECEDING 0x00400 /* start is V. P. */
453#define FRAMEOPTION_END_VALUE_PRECEDING 0x00800 /* end is V. P. */
454#define FRAMEOPTION_START_VALUE_FOLLOWING 0x01000 /* start is V. F. */
455#define FRAMEOPTION_END_VALUE_FOLLOWING 0x02000 /* end is V. F. */
456
457#define FRAMEOPTION_START_VALUE (FRAMEOPTION_START_VALUE_PRECEDING | FRAMEOPTION_START_VALUE_FOLLOWING)
458#define FRAMEOPTION_END_VALUE (FRAMEOPTION_END_VALUE_PRECEDING | FRAMEOPTION_END_VALUE_FOLLOWING)
459
460#define FRAMEOPTION_DEFAULTS (FRAMEOPTION_RANGE | FRAMEOPTION_START_UNBOUNDED_PRECEDING | FRAMEOPTION_END_CURRENT_ROW)
461
462/*
463 * PGRangeSubselect - subquery appearing in a FROM clause
464 */
465typedef struct PGRangeSubselect {
466 PGNodeTag type;
467 bool lateral; /* does it have LATERAL prefix? */
468 PGNode *subquery; /* the untransformed sub-select clause */
469 PGAlias *alias; /* table alias & optional column aliases */
470 PGNode *sample; /* sample options (if any) */
471} PGRangeSubselect;
472
473/*
474 * PGRangeFunction - function call appearing in a FROM clause
475 *
476 * functions is a PGList because we use this to represent the construct
477 * ROWS FROM(func1(...), func2(...), ...). Each element of this list is a
478 * two-element sublist, the first element being the untransformed function
479 * call tree, and the second element being a possibly-empty list of PGColumnDef
480 * nodes representing any columndef list attached to that function within the
481 * ROWS FROM() syntax.
482 *
483 * alias and coldeflist represent any alias and/or columndef list attached
484 * at the top level. (We disallow coldeflist appearing both here and
485 * per-function, but that's checked in parse analysis, not by the grammar.)
486 */
487typedef struct PGRangeFunction {
488 PGNodeTag type;
489 bool lateral; /* does it have LATERAL prefix? */
490 bool ordinality; /* does it have WITH ORDINALITY suffix? */
491 bool is_rowsfrom; /* is result of ROWS FROM() syntax? */
492 PGList *functions; /* per-function information, see above */
493 PGAlias *alias; /* table alias & optional column aliases */
494 PGList *coldeflist; /* list of PGColumnDef nodes to describe result
495 * of function returning RECORD */
496 PGNode *sample; /* sample options (if any) */
497} PGRangeFunction;
498
499/* Category of the column */
500typedef enum ColumnCategory {
501 COL_STANDARD, /* regular column */
502 COL_GENERATED /* generated (VIRTUAL|STORED) */
503} ColumnCategory;
504
505/*
506 * PGColumnDef - column definition (used in various creates)
507 *
508 * If the column has a default value, we may have the value expression
509 * in either "raw" form (an untransformed parse tree) or "cooked" form
510 * (a post-parse-analysis, executable expression tree), depending on
511 * how this PGColumnDef node was created (by parsing, or by inheritance
512 * from an existing relation). We should never have both in the same node!
513 *
514 * Similarly, we may have a COLLATE specification in either raw form
515 * (represented as a PGCollateClause with arg==NULL) or cooked form
516 * (the collation's OID).
517 *
518 * The constraints list may contain a PG_CONSTR_DEFAULT item in a raw
519 * parsetree produced by gram.y, but transformCreateStmt will remove
520 * the item and set raw_default instead. PG_CONSTR_DEFAULT items
521 * should not appear in any subsequent processing.
522 */
523
524typedef struct PGColumnDef {
525 PGNodeTag type; /* ENSURES COMPATIBILITY WITH 'PGNode' - has to be first line */
526 char *colname; /* name of column */
527 PGTypeName *typeName; /* type of column */
528 int inhcount; /* number of times column is inherited */
529 bool is_local; /* column has local (non-inherited) def'n */
530 bool is_not_null; /* NOT NULL constraint specified? */
531 bool is_from_type; /* column definition came from table type */
532 bool is_from_parent; /* column def came from partition parent */
533 char storage; /* attstorage setting, or 0 for default */
534 PGNode *raw_default; /* default value (untransformed parse tree) */
535 PGNode *cooked_default; /* default value (transformed expr tree) */
536 char identity; /* attidentity setting */
537 PGRangeVar *identitySequence; /* to store identity sequence name for ALTER
538 * TABLE ... ADD COLUMN */
539 PGCollateClause *collClause; /* untransformed COLLATE spec, if any */
540 PGOid collOid; /* collation OID (InvalidOid if not set) */
541 PGList *constraints; /* other constraints on column */
542 PGList *fdwoptions; /* per-column FDW options */
543 int location; /* parse location, or -1 if none/unknown */
544 ColumnCategory category; /* category of the column */
545} PGColumnDef;
546
547/*
548 * PGTableLikeClause - CREATE TABLE ( ... LIKE ... ) clause
549 */
550typedef struct PGTableLikeClause {
551 PGNodeTag type;
552 PGRangeVar *relation;
553 uint32_t options; /* OR of PGTableLikeOption flags */
554} PGTableLikeClause;
555
556typedef enum PGTableLikeOption {
557 PG_CREATE_TABLE_LIKE_DEFAULTS = 1 << 0,
558 PG_CREATE_TABLE_LIKE_CONSTRAINTS = 1 << 1,
559 PG_CREATE_TABLE_LIKE_IDENTITY = 1 << 2,
560 PG_CREATE_TABLE_LIKE_INDEXES = 1 << 3,
561 PG_CREATE_TABLE_LIKE_STORAGE = 1 << 4,
562 PG_CREATE_TABLE_LIKE_COMMENTS = 1 << 5,
563 PG_CREATE_TABLE_LIKE_STATISTICS = 1 << 6,
564 PG_CREATE_TABLE_LIKE_ALL = INT_MAX
565} PGTableLikeOption;
566
567/*
568 * PGIndexElem - index parameters (used in CREATE INDEX, and in ON CONFLICT)
569 *
570 * For a plain index attribute, 'name' is the name of the table column to
571 * index, and 'expr' is NULL. For an index expression, 'name' is NULL and
572 * 'expr' is the expression tree.
573 */
574typedef struct PGIndexElem {
575 PGNodeTag type;
576 char *name; /* name of attribute to index, or NULL */
577 PGNode *expr; /* expression to index, or NULL */
578 char *indexcolname; /* name for index column; NULL = default */
579 PGList *collation; /* name of collation; NIL = default */
580 PGList *opclass; /* name of desired opclass; NIL = default */
581 PGSortByDir ordering; /* ASC/DESC/default */
582 PGSortByNulls nulls_ordering; /* FIRST/LAST/default */
583} PGIndexElem;
584
585/*
586 * PGDefElem - a generic "name = value" option definition
587 *
588 * In some contexts the name can be qualified. Also, certain SQL commands
589 * allow a SET/ADD/DROP action to be attached to option settings, so it's
590 * convenient to carry a field for that too. (Note: currently, it is our
591 * practice that the grammar allows namespace and action only in statements
592 * where they are relevant; C code can just ignore those fields in other
593 * statements.)
594 */
595typedef enum PGDefElemAction {
596 PG_DEFELEM_UNSPEC, /* no action given */
597 PG_DEFELEM_SET,
598 PG_DEFELEM_ADD,
599 DEFELEM_DROP
600} PGDefElemAction;
601
602typedef struct PGDefElem {
603 PGNodeTag type;
604 char *defnamespace; /* NULL if unqualified name */
605 char *defname;
606 PGNode *arg; /* a (PGValue *) or a (PGTypeName *) */
607 PGDefElemAction defaction; /* unspecified action, or SET/ADD/DROP */
608 int location; /* token location, or -1 if unknown */
609} PGDefElem;
610
611/*
612 * PGLockingClause - raw representation of FOR [NO KEY] UPDATE/[KEY] SHARE
613 * options
614 *
615 * Note: lockedRels == NIL means "all relations in query". Otherwise it
616 * is a list of PGRangeVar nodes. (We use PGRangeVar mainly because it carries
617 * a location field --- currently, parse analysis insists on unqualified
618 * names in LockingClause.)
619 */
620typedef struct PGLockingClause {
621 PGNodeTag type;
622 PGList *lockedRels; /* FOR [KEY] UPDATE/SHARE relations */
623 PGLockClauseStrength strength;
624 PGLockWaitPolicy waitPolicy; /* NOWAIT and SKIP LOCKED */
625} PGLockingClause;
626
627/****************************************************************************
628 * Nodes for a PGQuery tree
629 ****************************************************************************/
630
631/*--------------------
632 * PGRangeTblEntry -
633 * A range table is a PGList of PGRangeTblEntry nodes.
634 *
635 * A range table entry may represent a plain relation, a sub-select in
636 * FROM, or the result of a JOIN clause. (Only explicit JOIN syntax
637 * produces an RTE, not the implicit join resulting from multiple FROM
638 * items. This is because we only need the RTE to deal with SQL features
639 * like outer joins and join-output-column aliasing.) Other special
640 * RTE types also exist, as indicated by RTEKind.
641 *
642 * Note that we consider PG_RTE_RELATION to cover anything that has a pg_class
643 * entry. relkind distinguishes the sub-cases.
644 *
645 * alias is an PGAlias node representing the AS alias-clause attached to the
646 * FROM expression, or NULL if no clause.
647 *
648 * eref is the table reference name and column reference names (either
649 * real or aliases). Note that system columns (OID etc) are not included
650 * in the column list.
651 * eref->aliasname is required to be present, and should generally be used
652 * to identify the RTE for error messages etc.
653 *
654 * In RELATION RTEs, the colnames in both alias and eref are indexed by
655 * physical attribute number; this means there must be colname entries for
656 * dropped columns. When building an RTE we insert empty strings ("") for
657 * dropped columns. Note however that a stored rule may have nonempty
658 * colnames for columns dropped since the rule was created (and for that
659 * matter the colnames might be out of date due to column renamings).
660 * The same comments apply to FUNCTION RTEs when a function's return type
661 * is a named composite type.
662 *
663 * In JOIN RTEs, the colnames in both alias and eref are one-to-one with
664 * joinaliasvars entries. A JOIN RTE will omit columns of its inputs when
665 * those columns are known to be dropped at parse time. Again, however,
666 * a stored rule might contain entries for columns dropped since the rule
667 * was created. (This is only possible for columns not actually referenced
668 * in the rule.) When loading a stored rule, we replace the joinaliasvars
669 * items for any such columns with null pointers. (We can't simply delete
670 * them from the joinaliasvars list, because that would affect the attnums
671 * of Vars referencing the rest of the list.)
672 *
673 * inh is true for relation references that should be expanded to include
674 * inheritance children, if the rel has any. This *must* be false for
675 * RTEs other than PG_RTE_RELATION entries.
676 *
677 * inFromCl marks those range variables that are listed in the FROM clause.
678 * It's false for RTEs that are added to a query behind the scenes, such
679 * as the NEW and OLD variables for a rule, or the subqueries of a UNION.
680 * This flag is not used anymore during parsing, since the parser now uses
681 * a separate "namespace" data structure to control visibility, but it is
682 * needed by ruleutils.c to determine whether RTEs should be shown in
683 * decompiled queries.
684 *--------------------
685 */
686typedef enum PGRTEKind {
687 PG_RTE_RELATION, /* ordinary relation reference */
688 PG_RTE_SUBQUERY, /* subquery in FROM */
689 PG_RTE_JOIN, /* join */
690 PG_RTE_FUNCTION, /* function in FROM */
691 PG_RTE_TABLEFUNC, /* TableFunc(.., column list) */
692 PG_RTE_VALUES, /* VALUES (<exprlist>), (<exprlist>), ... */
693 PG_RTE_CTE, /* common table expr (WITH list element) */
694 RTE_NAMEDTUPLESTORE /* tuplestore, e.g. for AFTER triggers */
695} PGRTEKind;
696
697typedef struct PGRangeTblEntry {
698 PGNodeTag type;
699
700 PGRTEKind rtekind; /* see above */
701
702 /*
703 * XXX the fields applicable to only some rte kinds should be merged into
704 * a union. I didn't do this yet because the diffs would impact a lot of
705 * code that is being actively worked on. FIXME someday.
706 */
707
708 /*
709 * Fields valid for a plain relation RTE (else zero):
710 *
711 * As a special case, RTE_NAMEDTUPLESTORE can also set relid to indicate
712 * that the tuple format of the tuplestore is the same as the referenced
713 * relation. This allows plans referencing AFTER trigger transition
714 * tables to be invalidated if the underlying table is altered.
715 */
716 PGOid relid; /* OID of the relation */
717 char relkind; /* relation kind (see pg_class.relkind) */
718 struct PGTableSampleClause *tablesample; /* sampling info, or NULL */
719
720 /*
721 * Fields valid for a subquery RTE (else NULL):
722 */
723 PGQuery *subquery; /* the sub-query */
724
725 /*
726 * Fields valid for a join RTE (else NULL/zero):
727 *
728 * joinaliasvars is a list of (usually) Vars corresponding to the columns
729 * of the join result. An alias PGVar referencing column K of the join
730 * result can be replaced by the K'th element of joinaliasvars --- but to
731 * simplify the task of reverse-listing aliases correctly, we do not do
732 * that until planning time. In detail: an element of joinaliasvars can
733 * be a PGVar of one of the join's input relations, or such a PGVar with an
734 * implicit coercion to the join's output column type, or a COALESCE
735 * expression containing the two input column Vars (possibly coerced).
736 * Within a PGQuery loaded from a stored rule, it is also possible for
737 * joinaliasvars items to be null pointers, which are placeholders for
738 * (necessarily unreferenced) columns dropped since the rule was made.
739 * Also, once planning begins, joinaliasvars items can be almost anything,
740 * as a result of subquery-flattening substitutions.
741 */
742 PGJoinType jointype; /* type of join */
743 PGList *joinaliasvars; /* list of alias-var expansions */
744
745 /*
746 * Fields valid for a function RTE (else NIL/zero):
747 *
748 * When funcordinality is true, the eref->colnames list includes an alias
749 * for the ordinality column. The ordinality column is otherwise
750 * implicit, and must be accounted for "by hand" in places such as
751 * expandRTE().
752 */
753 PGList *functions; /* list of PGRangeTblFunction nodes */
754 bool funcordinality; /* is this called WITH ORDINALITY? */
755
756 /*
757 * Fields valid for a PGTableFunc RTE (else NULL):
758 */
759 PGTableFunc *tablefunc;
760
761 /*
762 * Fields valid for a values RTE (else NIL):
763 */
764 PGList *values_lists; /* list of expression lists */
765
766 /*
767 * Fields valid for a CTE RTE (else NULL/zero):
768 */
769 char *ctename; /* name of the WITH list item */
770 PGIndex ctelevelsup; /* number of query levels up */
771 bool self_reference; /* is this a recursive self-reference? */
772
773 /*
774 * Fields valid for table functions, values, CTE and ENR RTEs (else NIL):
775 *
776 * We need these for CTE RTEs so that the types of self-referential
777 * columns are well-defined. For VALUES RTEs, storing these explicitly
778 * saves having to re-determine the info by scanning the values_lists. For
779 * ENRs, we store the types explicitly here (we could get the information
780 * from the catalogs if 'relid' was supplied, but we'd still need these
781 * for TupleDesc-based ENRs, so we might as well always store the type
782 * info here).
783 *
784 * For ENRs only, we have to consider the possibility of dropped columns.
785 * A dropped column is included in these lists, but it will have zeroes in
786 * all three lists (as well as an empty-string entry in eref). Testing
787 * for zero coltype is the standard way to detect a dropped column.
788 */
789 PGList *coltypes; /* OID list of column type OIDs */
790 PGList *coltypmods; /* integer list of column typmods */
791 PGList *colcollations; /* OID list of column collation OIDs */
792
793 /*
794 * Fields valid for ENR RTEs (else NULL/zero):
795 */
796 char *enrname; /* name of ephemeral named relation */
797 double enrtuples; /* estimated or actual from caller */
798
799 /*
800 * Fields valid in all RTEs:
801 */
802 PGAlias *alias; /* user-written alias clause, if any */
803 PGAlias *eref; /* expanded reference names */
804 bool lateral; /* subquery, function, or values is LATERAL? */
805 bool inh; /* inheritance requested? */
806 bool inFromCl; /* present in FROM clause? */
807} PGRangeTblEntry;
808
809/*
810 * PGRangeTblFunction -
811 * PGRangeTblEntry subsidiary data for one function in a FUNCTION RTE.
812 *
813 * If the function had a column definition list (required for an
814 * otherwise-unspecified RECORD result), funccolnames lists the names given
815 * in the definition list, funccoltypes lists their declared column types,
816 * funccoltypmods lists their typmods, funccolcollations their collations.
817 * Otherwise, those fields are NIL.
818 *
819 * Notice we don't attempt to store info about the results of functions
820 * returning named composite types, because those can change from time to
821 * time. We do however remember how many columns we thought the type had
822 * (including dropped columns!), so that we can successfully ignore any
823 * columns added after the query was parsed.
824 */
825typedef struct PGRangeTblFunction {
826 PGNodeTag type;
827
828 PGNode *funcexpr; /* expression tree for func call */
829 int funccolcount; /* number of columns it contributes to RTE */
830 /* These fields record the contents of a column definition list, if any: */
831 PGList *funccolnames; /* column names (list of String) */
832 PGList *funccoltypes; /* OID list of column type OIDs */
833 PGList *funccoltypmods; /* integer list of column typmods */
834 PGList *funccolcollations; /* OID list of column collation OIDs */
835 /* This is set during planning for use by the executor: */
836 PGBitmapset *funcparams; /* PG_PARAM_EXEC PGParam IDs affecting this func */
837} PGRangeTblFunction;
838
839/*
840 * PGSortGroupClause -
841 * representation of ORDER BY, GROUP BY, PARTITION BY,
842 * DISTINCT, DISTINCT ON items
843 *
844 * You might think that ORDER BY is only interested in defining ordering,
845 * and GROUP/DISTINCT are only interested in defining equality. However,
846 * one way to implement grouping is to sort and then apply a "uniq"-like
847 * filter. So it's also interesting to keep track of possible sort operators
848 * for GROUP/DISTINCT, and in particular to try to sort for the grouping
849 * in a way that will also yield a requested ORDER BY ordering. So we need
850 * to be able to compare ORDER BY and GROUP/DISTINCT lists, which motivates
851 * the decision to give them the same representation.
852 *
853 * tleSortGroupRef must match ressortgroupref of exactly one entry of the
854 * query's targetlist; that is the expression to be sorted or grouped by.
855 * eqop is the OID of the equality operator.
856 * sortop is the OID of the ordering operator (a "<" or ">" operator),
857 * or InvalidOid if not available.
858 * nulls_first means about what you'd expect. If sortop is InvalidOid
859 * then nulls_first is meaningless and should be set to false.
860 * hashable is true if eqop is hashable (note this condition also depends
861 * on the datatype of the input expression).
862 *
863 * In an ORDER BY item, all fields must be valid. (The eqop isn't essential
864 * here, but it's cheap to get it along with the sortop, and requiring it
865 * to be valid eases comparisons to grouping items.) Note that this isn't
866 * actually enough information to determine an ordering: if the sortop is
867 * collation-sensitive, a collation OID is needed too. We don't store the
868 * collation in PGSortGroupClause because it's not available at the time the
869 * parser builds the PGSortGroupClause; instead, consult the exposed collation
870 * of the referenced targetlist expression to find out what it is.
871 *
872 * In a grouping item, eqop must be valid. If the eqop is a btree equality
873 * operator, then sortop should be set to a compatible ordering operator.
874 * We prefer to set eqop/sortop/nulls_first to match any ORDER BY item that
875 * the query presents for the same tlist item. If there is none, we just
876 * use the default ordering op for the datatype.
877 *
878 * If the tlist item's type has a hash opclass but no btree opclass, then
879 * we will set eqop to the hash equality operator, sortop to InvalidOid,
880 * and nulls_first to false. A grouping item of this kind can only be
881 * implemented by hashing, and of course it'll never match an ORDER BY item.
882 *
883 * The hashable flag is provided since we generally have the requisite
884 * information readily available when the PGSortGroupClause is constructed,
885 * and it's relatively expensive to get it again later. Note there is no
886 * need for a "sortable" flag since OidIsValid(sortop) serves the purpose.
887 *
888 * A query might have both ORDER BY and DISTINCT (or DISTINCT ON) clauses.
889 * In SELECT DISTINCT, the distinctClause list is as long or longer than the
890 * sortClause list, while in SELECT DISTINCT ON it's typically shorter.
891 * The two lists must match up to the end of the shorter one --- the parser
892 * rearranges the distinctClause if necessary to make this true. (This
893 * restriction ensures that only one sort step is needed to both satisfy the
894 * ORDER BY and set up for the PGUnique step. This is semantically necessary
895 * for DISTINCT ON, and presents no real drawback for DISTINCT.)
896 */
897typedef struct PGSortGroupClause {
898 PGNodeTag type;
899 PGIndex tleSortGroupRef; /* reference into targetlist */
900 PGOid eqop; /* the equality operator ('=' op) */
901 PGOid sortop; /* the ordering operator ('<' op), or 0 */
902 bool nulls_first; /* do NULLs come before normal values? */
903 bool hashable; /* can eqop be implemented by hashing? */
904} PGSortGroupClause;
905
906/*
907 * PGGroupingSet -
908 * representation of CUBE, ROLLUP and GROUPING SETS clauses
909 *
910 * In a PGQuery with grouping sets, the groupClause contains a flat list of
911 * PGSortGroupClause nodes for each distinct expression used. The actual
912 * structure of the GROUP BY clause is given by the groupingSets tree.
913 *
914 * In the raw parser output, PGGroupingSet nodes (of all types except SIMPLE
915 * which is not used) are potentially mixed in with the expressions in the
916 * groupClause of the SelectStmt. (An expression can't contain a PGGroupingSet,
917 * but a list may mix PGGroupingSet and expression nodes.) At this stage, the
918 * content of each node is a list of expressions, some of which may be RowExprs
919 * which represent sublists rather than actual row constructors, and nested
920 * PGGroupingSet nodes where legal in the grammar. The structure directly
921 * reflects the query syntax.
922 *
923 * In parse analysis, the transformed expressions are used to build the tlist
924 * and groupClause list (of PGSortGroupClause nodes), and the groupingSets tree
925 * is eventually reduced to a fixed format:
926 *
927 * EMPTY nodes represent (), and obviously have no content
928 *
929 * SIMPLE nodes represent a list of one or more expressions to be treated as an
930 * atom by the enclosing structure; the content is an integer list of
931 * ressortgroupref values (see PGSortGroupClause)
932 *
933 * CUBE and ROLLUP nodes contain a list of one or more SIMPLE nodes.
934 *
935 * SETS nodes contain a list of EMPTY, SIMPLE, CUBE or ROLLUP nodes, but after
936 * parse analysis they cannot contain more SETS nodes; enough of the syntactic
937 * transforms of the spec have been applied that we no longer have arbitrarily
938 * deep nesting (though we still preserve the use of cube/rollup).
939 *
940 * Note that if the groupingSets tree contains no SIMPLE nodes (only EMPTY
941 * nodes at the leaves), then the groupClause will be empty, but this is still
942 * an aggregation query (similar to using aggs or HAVING without GROUP BY).
943 *
944 * As an example, the following clause:
945 *
946 * GROUP BY GROUPING SETS ((a,b), CUBE(c,(d,e)))
947 *
948 * looks like this after raw parsing:
949 *
950 * SETS( RowExpr(a,b) , CUBE( c, RowExpr(d,e) ) )
951 *
952 * and parse analysis converts it to:
953 *
954 * SETS( SIMPLE(1,2), CUBE( SIMPLE(3), SIMPLE(4,5) ) )
955 */
956typedef enum {
957 GROUPING_SET_EMPTY,
958 GROUPING_SET_SIMPLE,
959 GROUPING_SET_ROLLUP,
960 GROUPING_SET_CUBE,
961 GROUPING_SET_SETS,
962 GROUPING_SET_ALL
963} GroupingSetKind;
964
965typedef struct PGGroupingSet {
966 PGNodeTag type;
967 GroupingSetKind kind;
968 PGList *content;
969 int location;
970} PGGroupingSet;
971
972/*
973 * PGWindowClause -
974 * transformed representation of WINDOW and OVER clauses
975 *
976 * A parsed Query's windowClause list contains these structs. "name" is set
977 * if the clause originally came from WINDOW, and is NULL if it originally
978 * was an OVER clause (but note that we collapse out duplicate OVERs).
979 * partitionClause and orderClause are lists of PGSortGroupClause structs.
980 * winref is an ID number referenced by PGWindowFunc nodes; it must be unique
981 * among the members of a Query's windowClause list.
982 * When refname isn't null, the partitionClause is always copied from there;
983 * the orderClause might or might not be copied (see copiedOrder); the framing
984 * options are never copied, per spec.
985 */
986typedef struct PGWindowClause {
987 PGNodeTag type;
988 char *name; /* window name (NULL in an OVER clause) */
989 char *refname; /* referenced window name, if any */
990 PGList *partitionClause; /* PARTITION BY list */
991 PGList *orderClause; /* ORDER BY list */
992 int frameOptions; /* frame_clause options, see PGWindowDef */
993 PGNode *startOffset; /* expression for starting bound, if any */
994 PGNode *endOffset; /* expression for ending bound, if any */
995 PGIndex winref; /* ID referenced by window functions */
996 bool copiedOrder; /* did we copy orderClause from refname? */
997} PGWindowClause;
998
999/*
1000 * RowMarkClause -
1001 * parser output representation of FOR [KEY] UPDATE/SHARE clauses
1002 *
1003 * Query.rowMarks contains a separate RowMarkClause node for each relation
1004 * identified as a FOR [KEY] UPDATE/SHARE target. If one of these clauses
1005 * is applied to a subquery, we generate RowMarkClauses for all normal and
1006 * subquery rels in the subquery, but they are marked pushedDown = true to
1007 * distinguish them from clauses that were explicitly written at this query
1008 * level. Also, Query.hasForUpdate tells whether there were explicit FOR
1009 * UPDATE/SHARE/KEY SHARE clauses in the current query level.
1010 */
1011
1012/*
1013 * PGWithClause -
1014 * representation of WITH clause
1015 *
1016 * Note: PGWithClause does not propagate into the PGQuery representation;
1017 * but PGCommonTableExpr does.
1018 */
1019typedef struct PGWithClause {
1020 PGNodeTag type;
1021 PGList *ctes; /* list of CommonTableExprs */
1022 bool recursive; /* true = WITH RECURSIVE */
1023 int location; /* token location, or -1 if unknown */
1024} PGWithClause;
1025
1026/*
1027 * PGInferClause -
1028 * ON CONFLICT unique index inference clause
1029 *
1030 * Note: PGInferClause does not propagate into the PGQuery representation.
1031 */
1032typedef struct PGInferClause {
1033 PGNodeTag type;
1034 PGList *indexElems; /* IndexElems to infer unique index */
1035 PGNode *whereClause; /* qualification (partial-index predicate) */
1036 char *conname; /* PGConstraint name, or NULL if unnamed */
1037 int location; /* token location, or -1 if unknown */
1038} PGInferClause;
1039
1040/*
1041 * PGOnConflictClause -
1042 * representation of ON CONFLICT clause
1043 *
1044 * Note: PGOnConflictClause does not propagate into the PGQuery representation.
1045 */
1046typedef struct PGOnConflictClause {
1047 PGNodeTag type;
1048 PGOnConflictAction action; /* DO NOTHING or UPDATE? */
1049 PGInferClause *infer; /* Optional index inference clause */
1050 PGList *targetList; /* the target list (of PGResTarget) */
1051 PGNode *whereClause; /* qualifications */
1052 int location; /* token location, or -1 if unknown */
1053} PGOnConflictClause;
1054
1055/*
1056 * PGCommonTableExpr -
1057 * representation of WITH list element
1058 *
1059 * We don't currently support the SEARCH or CYCLE clause.
1060 */
1061typedef struct PGCommonTableExpr {
1062 PGNodeTag type;
1063 char *ctename; /* query name (never qualified) */
1064 PGList *aliascolnames; /* optional list of column names */
1065 /* SelectStmt/InsertStmt/etc before parse analysis, PGQuery afterwards: */
1066 PGNode *ctequery; /* the CTE's subquery */
1067 int location; /* token location, or -1 if unknown */
1068 /* These fields are set during parse analysis: */
1069 bool cterecursive; /* is this CTE actually recursive? */
1070 int cterefcount; /* number of RTEs referencing this CTE
1071 * (excluding internal self-references) */
1072 PGList *ctecolnames; /* list of output column names */
1073 PGList *ctecoltypes; /* OID list of output column type OIDs */
1074 PGList *ctecoltypmods; /* integer list of output column typmods */
1075 PGList *ctecolcollations; /* OID list of column collation OIDs */
1076} PGCommonTableExpr;
1077
1078/* Convenience macro to get the output tlist of a CTE's query */
1079#define GetCTETargetList(cte) \
1080 (AssertMacro(IsA((cte)->ctequery, PGQuery)), ((PGQuery *)(cte)->ctequery)->commandType == PG_CMD_SELECT ? ((PGQuery *)(cte)->ctequery)->targetList : ((PGQuery *)(cte)->ctequery)->returningList)
1081
1082/*
1083 * TriggerTransition -
1084 * representation of transition row or table naming clause
1085 *
1086 * Only transition tables are initially supported in the syntax, and only for
1087 * AFTER triggers, but other permutations are accepted by the parser so we can
1088 * give a meaningful message from C code.
1089 */
1090
1091/*****************************************************************************
1092 * Raw Grammar Output Statements
1093 *****************************************************************************/
1094
1095/*
1096 * PGRawStmt --- container for any one statement's raw parse tree
1097 *
1098 * Parse analysis converts a raw parse tree headed by a PGRawStmt node into
1099 * an analyzed statement headed by a PGQuery node. For optimizable statements,
1100 * the conversion is complex. For utility statements, the parser usually just
1101 * transfers the raw parse tree (sans PGRawStmt) into the utilityStmt field of
1102 * the PGQuery node, and all the useful work happens at execution time.
1103 *
1104 * stmt_location/stmt_len identify the portion of the source text string
1105 * containing this raw statement (useful for multi-statement strings).
1106 */
1107typedef struct PGRawStmt {
1108 PGNodeTag type;
1109 PGNode *stmt; /* raw parse tree */
1110 int stmt_location; /* start location, or -1 if unknown */
1111 int stmt_len; /* length in bytes; 0 means "rest of string" */
1112} PGRawStmt;
1113
1114/*****************************************************************************
1115 * Optimizable Statements
1116 *****************************************************************************/
1117
1118/* ----------------------
1119 * Insert Statement
1120 *
1121 * The source expression is represented by PGSelectStmt for both the
1122 * SELECT and VALUES cases. If selectStmt is NULL, then the query
1123 * is INSERT ... DEFAULT VALUES.
1124 * ----------------------
1125 */
1126typedef struct PGInsertStmt {
1127 PGNodeTag type;
1128 PGRangeVar *relation; /* relation to insert into */
1129 PGList *cols; /* optional: names of the target columns */
1130 PGNode *selectStmt; /* the source SELECT/VALUES, or NULL */
1131 PGOnConflictActionAlias onConflictAlias; /* the (optional) shorthand provided for the onConflictClause */
1132 PGOnConflictClause *onConflictClause; /* ON CONFLICT clause */
1133 PGList *returningList; /* list of expressions to return */
1134 PGWithClause *withClause; /* WITH clause */
1135 PGOverridingKind override; /* OVERRIDING clause */
1136 PGInsertColumnOrder insert_column_order; /* INSERT BY NAME or INSERT BY POSITION */
1137} PGInsertStmt;
1138
1139/* ----------------------
1140 * Delete Statement
1141 * ----------------------
1142 */
1143typedef struct PGDeleteStmt {
1144 PGNodeTag type;
1145 PGRangeVar *relation; /* relation to delete from */
1146 PGList *usingClause; /* optional using clause for more tables */
1147 PGNode *whereClause; /* qualifications */
1148 PGList *returningList; /* list of expressions to return */
1149 PGWithClause *withClause; /* WITH clause */
1150} PGDeleteStmt;
1151
1152/* ----------------------
1153 * Update Statement
1154 * ----------------------
1155 */
1156typedef struct PGUpdateStmt {
1157 PGNodeTag type;
1158 PGRangeVar *relation; /* relation to update */
1159 PGList *targetList; /* the target list (of PGResTarget) */
1160 PGNode *whereClause; /* qualifications */
1161 PGList *fromClause; /* optional from clause for more tables */
1162 PGList *returningList; /* list of expressions to return */
1163 PGWithClause *withClause; /* WITH clause */
1164} PGUpdateStmt;
1165
1166/* ----------------------
1167 * Pivot Expression
1168 * ----------------------
1169 */
1170typedef struct PGPivot {
1171 PGNodeTag type;
1172 PGList *pivot_columns; /* The column names to pivot on */
1173 PGList *unpivot_columns;/* The column names to unpivot */
1174 PGList *pivot_value; /* The set of pivot values */
1175 PGNode *subquery; /* Subquery to fetch valid pivot values (if any) */
1176 char *pivot_enum; /* The enum to fetch the unique values from */
1177} PGPivot;
1178
1179typedef struct PGPivotExpr {
1180 PGNodeTag type;
1181 PGNode *source; /* the source subtree */
1182 PGList *aggrs; /* The aggregations to pivot over (PIVOT only) */
1183 PGList *unpivots; /* The names to unpivot over (UNPIVOT only) */
1184 PGList *pivots; /* The set of pivot values */
1185 PGList *groups; /* The set of groups to pivot over (if any) */
1186 PGAlias *alias; /* table alias & optional column aliases */
1187 bool include_nulls; /* Whether or not to include NULL values (UNPIVOT only */
1188} PGPivotExpr;
1189
1190typedef struct PGPivotStmt {
1191 PGNodeTag type;
1192 PGNode *source; /* The source to pivot */
1193 PGList *aggrs; /* The aggregations to pivot over (PIVOT only) */
1194 PGList *unpivots; /* The names to unpivot over (UNPIVOT only) */
1195 PGList *columns; /* The set of columns to pivot over */
1196 PGList *groups; /* The set of groups to pivot over (if any) */
1197} PGPivotStmt;
1198
1199/* ----------------------
1200 * Select Statement
1201 *
1202 * A "simple" SELECT is represented in the output of gram.y by a single
1203 * PGSelectStmt node; so is a VALUES construct. A query containing set
1204 * operators (UNION, INTERSECT, EXCEPT) is represented by a tree of PGSelectStmt
1205 * nodes, in which the leaf nodes are component SELECTs and the internal nodes
1206 * represent UNION, INTERSECT, or EXCEPT operators. Using the same node
1207 * type for both leaf and internal nodes allows gram.y to stick ORDER BY,
1208 * LIMIT, etc, clause values into a SELECT statement without worrying
1209 * whether it is a simple or compound SELECT.
1210 * ----------------------
1211 */
1212typedef enum PGSetOperation { PG_SETOP_NONE = 0, PG_SETOP_UNION, PG_SETOP_INTERSECT, PG_SETOP_EXCEPT, PG_SETOP_UNION_BY_NAME } PGSetOperation;
1213
1214typedef struct PGSelectStmt {
1215 PGNodeTag type;
1216
1217 /*
1218 * These fields are used only in "leaf" SelectStmts.
1219 */
1220 PGList *distinctClause; /* NULL, list of DISTINCT ON exprs, or
1221 * lcons(NIL,NIL) for all (SELECT DISTINCT) */
1222 PGIntoClause *intoClause; /* target for SELECT INTO */
1223 PGList *targetList; /* the target list (of PGResTarget) */
1224 PGList *fromClause; /* the FROM clause */
1225 PGNode *whereClause; /* WHERE qualification */
1226 PGList *groupClause; /* GROUP BY clauses */
1227 PGNode *havingClause; /* HAVING conditional-expression */
1228 PGList *windowClause; /* WINDOW window_name AS (...), ... */
1229 PGNode *qualifyClause; /* QUALIFY conditional-expression */
1230
1231 /*
1232 * In a "leaf" node representing a VALUES list, the above fields are all
1233 * null, and instead this field is set. Note that the elements of the
1234 * sublists are just expressions, without PGResTarget decoration. Also note
1235 * that a list element can be DEFAULT (represented as a PGSetToDefault
1236 * node), regardless of the context of the VALUES list. It's up to parse
1237 * analysis to reject that where not valid.
1238 */
1239 PGList *valuesLists; /* untransformed list of expression lists */
1240
1241 /* When representing a pivot statement, all values are NULL besides the pivot field */
1242 PGPivotStmt *pivot; /* PIVOT statement */
1243
1244 /*
1245 * These fields are used in both "leaf" SelectStmts and upper-level
1246 * SelectStmts.
1247 */
1248 PGList *sortClause; /* sort clause (a list of SortBy's) */
1249 PGNode *limitOffset; /* # of result tuples to skip */
1250 PGNode *limitCount; /* # of result tuples to return */
1251 PGNode *sampleOptions; /* sample options (if any) */
1252 PGList *lockingClause; /* FOR UPDATE (list of LockingClause's) */
1253 PGWithClause *withClause; /* WITH clause */
1254
1255 /*
1256 * These fields are used only in upper-level SelectStmts.
1257 */
1258 PGSetOperation op; /* type of set op */
1259 bool all; /* ALL specified? */
1260 struct PGSelectStmt *larg; /* left child */
1261 struct PGSelectStmt *rarg; /* right child */
1262 /* Eventually add fields for CORRESPONDING spec here */
1263} PGSelectStmt;
1264
1265/* ----------------------
1266 * Set Operation node for post-analysis query trees
1267 *
1268 * After parse analysis, a SELECT with set operations is represented by a
1269 * top-level PGQuery node containing the leaf SELECTs as subqueries in its
1270 * range table. Its setOperations field shows the tree of set operations,
1271 * with leaf PGSelectStmt nodes replaced by PGRangeTblRef nodes, and internal
1272 * nodes replaced by SetOperationStmt nodes. Information about the output
1273 * column types is added, too. (Note that the child nodes do not necessarily
1274 * produce these types directly, but we've checked that their output types
1275 * can be coerced to the output column type.) Also, if it's not UNION ALL,
1276 * information about the types' sort/group semantics is provided in the form
1277 * of a PGSortGroupClause list (same representation as, eg, DISTINCT).
1278 * The resolved common column collations are provided too; but note that if
1279 * it's not UNION ALL, it's okay for a column to not have a common collation,
1280 * so a member of the colCollations list could be InvalidOid even though the
1281 * column has a collatable type.
1282 * ----------------------
1283 */
1284
1285/*****************************************************************************
1286 * Other Statements (no optimizations required)
1287 *
1288 * These are not touched by parser/analyze.c except to put them into
1289 * the utilityStmt field of a Query. This is eventually passed to
1290 * ProcessUtility (by-passing rewriting and planning). Some of the
1291 * statements do need attention from parse analysis, and this is
1292 * done by routines in parser/parse_utilcmd.c after ProcessUtility
1293 * receives the command for execution.
1294 * DECLARE CURSOR, EXPLAIN, and CREATE TABLE AS are special cases:
1295 * they contain optimizable statements, which get processed normally
1296 * by parser/analyze.c.
1297 *****************************************************************************/
1298
1299/*
1300 * When a command can act on several kinds of objects with only one
1301 * parse structure required, use these constants to designate the
1302 * object type. Note that commands typically don't support all the types.
1303 */
1304
1305typedef enum PGObjectType {
1306 PG_OBJECT_ACCESS_METHOD,
1307 PG_OBJECT_AGGREGATE,
1308 PG_OBJECT_AMOP,
1309 PG_OBJECT_AMPROC,
1310 PG_OBJECT_ATTRIBUTE, /* type's attribute, when distinct from column */
1311 PG_OBJECT_CAST,
1312 PG_OBJECT_COLUMN,
1313 PG_OBJECT_COLLATION,
1314 PG_OBJECT_CONVERSION,
1315 PG_OBJECT_DATABASE,
1316 PG_OBJECT_DEFAULT,
1317 PG_OBJECT_DEFACL,
1318 PG_OBJECT_DOMAIN,
1319 PG_OBJECT_DOMCONSTRAINT,
1320 PG_OBJECT_EVENT_TRIGGER,
1321 PG_OBJECT_EXTENSION,
1322 PG_OBJECT_FDW,
1323 PG_OBJECT_FOREIGN_SERVER,
1324 PG_OBJECT_FOREIGN_TABLE,
1325 PG_OBJECT_FUNCTION,
1326 PG_OBJECT_TABLE_MACRO,
1327 PG_OBJECT_INDEX,
1328 PG_OBJECT_LANGUAGE,
1329 PG_OBJECT_LARGEOBJECT,
1330 PG_OBJECT_MATVIEW,
1331 PG_OBJECT_OPCLASS,
1332 PG_OBJECT_OPERATOR,
1333 PG_OBJECT_OPFAMILY,
1334 PG_OBJECT_POLICY,
1335 PG_OBJECT_PUBLICATION,
1336 PG_OBJECT_PUBLICATION_REL,
1337 PG_OBJECT_ROLE,
1338 PG_OBJECT_RULE,
1339 PG_OBJECT_SCHEMA,
1340 PG_OBJECT_SEQUENCE,
1341 PG_OBJECT_SUBSCRIPTION,
1342 PG_OBJECT_STATISTIC_EXT,
1343 PG_OBJECT_TABCONSTRAINT,
1344 PG_OBJECT_TABLE,
1345 PG_OBJECT_TABLESPACE,
1346 PG_OBJECT_TRANSFORM,
1347 PG_OBJECT_TRIGGER,
1348 PG_OBJECT_TSCONFIGURATION,
1349 PG_OBJECT_TSDICTIONARY,
1350 PG_OBJECT_TSPARSER,
1351 PG_OBJECT_TSTEMPLATE,
1352 PG_OBJECT_TYPE,
1353 PG_OBJECT_USER_MAPPING,
1354 PG_OBJECT_VIEW
1355} PGObjectType;
1356
1357/* ----------------------
1358 * Create Schema Statement
1359 *
1360 * NOTE: the schemaElts list contains raw parsetrees for component statements
1361 * of the schema, such as CREATE TABLE, GRANT, etc. These are analyzed and
1362 * executed after the schema itself is created.
1363 * ----------------------
1364 */
1365typedef struct PGCreateSchemaStmt {
1366 PGNodeTag type;
1367 char *catalogname; /* the name of the catalog in which to create the schema */
1368 char *schemaname; /* the name of the schema to create */
1369 PGList *schemaElts; /* schema components (list of parsenodes) */
1370 PGOnCreateConflict onconflict; /* what to do on create conflict */
1371} PGCreateSchemaStmt;
1372
1373typedef enum PGDropBehavior {
1374 PG_DROP_RESTRICT, /* drop fails if any dependent objects */
1375 PG_DROP_CASCADE /* remove dependent objects too */
1376} PGDropBehavior;
1377
1378/* ----------------------
1379 * Alter Table
1380 * ----------------------
1381 */
1382typedef struct PGAlterTableStmt {
1383 PGNodeTag type;
1384 PGRangeVar *relation; /* table to work on */
1385 PGList *cmds; /* list of subcommands */
1386 PGObjectType relkind; /* type of object */
1387 bool missing_ok; /* skip error if table missing */
1388} PGAlterTableStmt;
1389
1390typedef enum PGAlterTableType {
1391 PG_AT_AddColumn, /* add column */
1392 PG_AT_AddColumnRecurse, /* internal to commands/tablecmds.c */
1393 PG_AT_AddColumnToView, /* implicitly via CREATE OR REPLACE VIEW */
1394 PG_AT_ColumnDefault, /* alter column default */
1395 PG_AT_DropNotNull, /* alter column drop not null */
1396 PG_AT_SetNotNull, /* alter column set not null */
1397 PG_AT_SetStatistics, /* alter column set statistics */
1398 PG_AT_SetOptions, /* alter column set ( options ) */
1399 PG_AT_ResetOptions, /* alter column reset ( options ) */
1400 PG_AT_SetStorage, /* alter column set storage */
1401 PG_AT_DropColumn, /* drop column */
1402 PG_AT_DropColumnRecurse, /* internal to commands/tablecmds.c */
1403 PG_AT_AddIndex, /* add index */
1404 PG_AT_ReAddIndex, /* internal to commands/tablecmds.c */
1405 PG_AT_AddConstraint, /* add constraint */
1406 PG_AT_AddConstraintRecurse, /* internal to commands/tablecmds.c */
1407 PG_AT_ReAddConstraint, /* internal to commands/tablecmds.c */
1408 PG_AT_AlterConstraint, /* alter constraint */
1409 PG_AT_ValidateConstraint, /* validate constraint */
1410 PG_AT_ValidateConstraintRecurse, /* internal to commands/tablecmds.c */
1411 PG_AT_ProcessedConstraint, /* pre-processed add constraint (local in
1412 * parser/parse_utilcmd.c) */
1413 PG_AT_AddIndexConstraint, /* add constraint using existing index */
1414 PG_AT_DropConstraint, /* drop constraint */
1415 PG_AT_DropConstraintRecurse, /* internal to commands/tablecmds.c */
1416 PG_AT_ReAddComment, /* internal to commands/tablecmds.c */
1417 PG_AT_AlterColumnType, /* alter column type */
1418 PG_AT_AlterColumnGenericOptions, /* alter column OPTIONS (...) */
1419 PG_AT_ChangeOwner, /* change owner */
1420 PG_AT_ClusterOn, /* CLUSTER ON */
1421 PG_AT_DropCluster, /* SET WITHOUT CLUSTER */
1422 PG_AT_SetLogged, /* SET LOGGED */
1423 PG_AT_SetUnLogged, /* SET UNLOGGED */
1424 PG_AT_AddOids, /* SET WITH OIDS */
1425 PG_AT_AddOidsRecurse, /* internal to commands/tablecmds.c */
1426 PG_AT_DropOids, /* SET WITHOUT OIDS */
1427 PG_AT_SetTableSpace, /* SET TABLESPACE */
1428 PG_AT_SetRelOptions, /* SET (...) -- AM specific parameters */
1429 PG_AT_ResetRelOptions, /* RESET (...) -- AM specific parameters */
1430 PG_AT_ReplaceRelOptions, /* replace reloption list in its entirety */
1431 PG_AT_EnableTrig, /* ENABLE TRIGGER name */
1432 PG_AT_EnableAlwaysTrig, /* ENABLE ALWAYS TRIGGER name */
1433 PG_AT_EnableReplicaTrig, /* ENABLE REPLICA TRIGGER name */
1434 PG_AT_DisableTrig, /* DISABLE TRIGGER name */
1435 PG_AT_EnableTrigAll, /* ENABLE TRIGGER ALL */
1436 PG_AT_DisableTrigAll, /* DISABLE TRIGGER ALL */
1437 PG_AT_EnableTrigUser, /* ENABLE TRIGGER USER */
1438 PG_AT_DisableTrigUser, /* DISABLE TRIGGER USER */
1439 PG_AT_EnableRule, /* ENABLE RULE name */
1440 PG_AT_EnableAlwaysRule, /* ENABLE ALWAYS RULE name */
1441 PG_AT_EnableReplicaRule, /* ENABLE REPLICA RULE name */
1442 PG_AT_DisableRule, /* DISABLE RULE name */
1443 PG_AT_AddInherit, /* INHERIT parent */
1444 PG_AT_DropInherit, /* NO INHERIT parent */
1445 PG_AT_AddOf, /* OF <type_name> */
1446 PG_AT_DropOf, /* NOT OF */
1447 PG_AT_ReplicaIdentity, /* REPLICA IDENTITY */
1448 PG_AT_EnableRowSecurity, /* ENABLE ROW SECURITY */
1449 PG_AT_DisableRowSecurity, /* DISABLE ROW SECURITY */
1450 PG_AT_ForceRowSecurity, /* FORCE ROW SECURITY */
1451 PG_AT_NoForceRowSecurity, /* NO FORCE ROW SECURITY */
1452 PG_AT_GenericOptions, /* OPTIONS (...) */
1453 PG_AT_AttachPartition, /* ATTACH PARTITION */
1454 PG_AT_DetachPartition, /* DETACH PARTITION */
1455 PG_AT_AddIdentity, /* ADD IDENTITY */
1456 PG_AT_SetIdentity, /* SET identity column options */
1457 AT_DropIdentity /* DROP IDENTITY */
1458} PGAlterTableType;
1459
1460typedef struct PGAlterTableCmd /* one subcommand of an ALTER TABLE */
1461{
1462 PGNodeTag type;
1463 PGAlterTableType subtype; /* Type of table alteration to apply */
1464 char *name; /* column, constraint, or trigger to act on,
1465 * or tablespace */
1466 PGNode *def; /* definition of new column, index,
1467 * constraint, or parent table */
1468 PGDropBehavior behavior; /* RESTRICT or CASCADE for DROP cases */
1469 bool missing_ok; /* skip error if missing? */
1470} PGAlterTableCmd;
1471
1472/*
1473 * Note: PGObjectWithArgs carries only the types of the input parameters of the
1474 * function. So it is sufficient to identify an existing function, but it
1475 * is not enough info to define a function nor to call it.
1476 */
1477typedef struct PGObjectWithArgs {
1478 PGNodeTag type;
1479 PGList *objname; /* qualified name of function/operator */
1480 PGList *objargs; /* list of Typename nodes */
1481 bool args_unspecified; /* argument list was omitted, so name must
1482 * be unique (note that objargs == NIL
1483 * means zero args) */
1484} PGObjectWithArgs;
1485
1486/* ----------------------
1487 * Copy Statement
1488 *
1489 * We support "COPY relation FROM file", "COPY relation TO file", and
1490 * "COPY (query) TO file". In any given PGCopyStmt, exactly one of "relation"
1491 * and "query" must be non-NULL.
1492 * ----------------------
1493 */
1494typedef struct PGCopyStmt {
1495 PGNodeTag type;
1496 PGRangeVar *relation; /* the relation to copy */
1497 PGNode *query; /* the query (SELECT or DML statement with
1498 * RETURNING) to copy, as a raw parse tree */
1499 PGList *attlist; /* PGList of column names (as Strings), or NIL
1500 * for all columns */
1501 bool is_from; /* TO or FROM */
1502 bool is_program; /* is 'filename' a program to popen? */
1503 char *filename; /* filename, or NULL for STDIN/STDOUT */
1504 PGList *options; /* PGList of PGDefElem nodes */
1505} PGCopyStmt;
1506
1507/* ----------------------
1508 * SET Statement (includes RESET)
1509 *
1510 * "SET var TO DEFAULT" and "RESET var" are semantically equivalent, but we
1511 * preserve the distinction in VariableSetKind for CreateCommandTag().
1512 * ----------------------
1513 */
1514typedef enum {
1515 VAR_SET_VALUE, /* SET var = value */
1516 VAR_SET_DEFAULT, /* SET var TO DEFAULT */
1517 VAR_SET_CURRENT, /* SET var FROM CURRENT */
1518 VAR_SET_MULTI, /* special case for SET TRANSACTION ... */
1519 VAR_RESET, /* RESET var */
1520 VAR_RESET_ALL /* RESET ALL */
1521} VariableSetKind;
1522
1523typedef enum {
1524 VAR_SET_SCOPE_LOCAL, /* SET LOCAL var */
1525 VAR_SET_SCOPE_SESSION, /* SET SESSION var */
1526 VAR_SET_SCOPE_GLOBAL, /* SET GLOBAL var */
1527 VAR_SET_SCOPE_DEFAULT /* SET var (same as SET_SESSION) */
1528} VariableSetScope;
1529
1530typedef struct PGVariableSetStmt {
1531 PGNodeTag type;
1532 VariableSetKind kind;
1533 VariableSetScope scope;
1534 char *name; /* variable to be set */
1535 PGList *args; /* PGList of PGAConst nodes */
1536} PGVariableSetStmt;
1537
1538/* ----------------------
1539 * Show Statement
1540 * ----------------------
1541 */
1542typedef struct PGVariableShowStmt {
1543 PGNodeTag type;
1544 char *name;
1545 int is_summary; // whether or not this is a DESCRIBE or a SUMMARIZE
1546} PGVariableShowStmt;
1547
1548/* ----------------------
1549 * Show Statement with Select Statement
1550 * ----------------------
1551 */
1552typedef struct PGVariableShowSelectStmt
1553{
1554 PGNodeTag type;
1555 PGNode *stmt;
1556 char *name;
1557 int is_summary; // whether or not this is a DESCRIBE or a SUMMARIZE
1558} PGVariableShowSelectStmt;
1559
1560
1561/* ----------------------
1562 * Create Table Statement
1563 *
1564 * NOTE: in the raw gram.y output, PGColumnDef and PGConstraint nodes are
1565 * intermixed in tableElts, and constraints is NIL. After parse analysis,
1566 * tableElts contains just ColumnDefs, and constraints contains just
1567 * PGConstraint nodes (in fact, only PG_CONSTR_CHECK nodes, in the present
1568 * implementation).
1569 * ----------------------
1570 */
1571
1572typedef struct PGCreateStmt {
1573 PGNodeTag type;
1574 PGRangeVar *relation; /* relation to create */
1575 PGList *tableElts; /* column definitions (list of PGColumnDef) */
1576 PGList *inhRelations; /* relations to inherit from (list of
1577 * inhRelation) */
1578 PGTypeName *ofTypename; /* OF typename */
1579 PGList *constraints; /* constraints (list of PGConstraint nodes) */
1580 PGList *options; /* options from WITH clause */
1581 PGOnCommitAction oncommit; /* what do we do at COMMIT? */
1582 char *tablespacename; /* table space to use, or NULL */
1583 PGOnCreateConflict onconflict; /* what to do on create conflict */
1584} PGCreateStmt;
1585
1586/* ----------
1587 * Definitions for constraints in PGCreateStmt
1588 *
1589 * Note that column defaults are treated as a type of constraint,
1590 * even though that's a bit odd semantically.
1591 *
1592 * For constraints that use expressions (CONSTR_CHECK, PG_CONSTR_DEFAULT)
1593 * we may have the expression in either "raw" form (an untransformed
1594 * parse tree) or "cooked" form (the nodeToString representation of
1595 * an executable expression tree), depending on how this PGConstraint
1596 * node was created (by parsing, or by inheritance from an existing
1597 * relation). We should never have both in the same node!
1598 *
1599 * PG_FKCONSTR_ACTION_xxx values are stored into pg_constraint.confupdtype
1600 * and pg_constraint.confdeltype columns; PG_FKCONSTR_MATCH_xxx values are
1601 * stored into pg_constraint.confmatchtype. Changing the code values may
1602 * require an initdb!
1603 *
1604 * If skip_validation is true then we skip checking that the existing rows
1605 * in the table satisfy the constraint, and just install the catalog entries
1606 * for the constraint. A new FK constraint is marked as valid iff
1607 * initially_valid is true. (Usually skip_validation and initially_valid
1608 * are inverses, but we can set both true if the table is known empty.)
1609 *
1610 * PGConstraint attributes (DEFERRABLE etc) are initially represented as
1611 * separate PGConstraint nodes for simplicity of parsing. parse_utilcmd.c makes
1612 * a pass through the constraints list to insert the info into the appropriate
1613 * PGConstraint node.
1614 * ----------
1615 */
1616
1617typedef enum PGConstrType /* types of constraints */
1618{ PG_CONSTR_NULL, /* not standard SQL, but a lot of people
1619 * expect it */
1620 PG_CONSTR_NOTNULL,
1621 PG_CONSTR_DEFAULT,
1622 PG_CONSTR_IDENTITY,
1623 PG_CONSTR_CHECK,
1624 PG_CONSTR_PRIMARY,
1625 PG_CONSTR_UNIQUE,
1626 PG_CONSTR_EXCLUSION,
1627 PG_CONSTR_FOREIGN,
1628 PG_CONSTR_ATTR_DEFERRABLE, /* attributes for previous constraint node */
1629 PG_CONSTR_ATTR_NOT_DEFERRABLE,
1630 PG_CONSTR_ATTR_DEFERRED,
1631 PG_CONSTR_ATTR_IMMEDIATE,
1632 PG_CONSTR_COMPRESSION,
1633 PG_CONSTR_GENERATED_VIRTUAL,
1634 PG_CONSTR_GENERATED_STORED,
1635 } PGConstrType;
1636
1637/* Foreign key action codes */
1638#define PG_FKCONSTR_ACTION_NOACTION 'a'
1639#define PG_FKCONSTR_ACTION_RESTRICT 'r'
1640#define PG_FKCONSTR_ACTION_CASCADE 'c'
1641#define PG_FKCONSTR_ACTION_SETNULL 'n'
1642#define PG_FKCONSTR_ACTION_SETDEFAULT 'd'
1643
1644/* Foreign key matchtype codes */
1645#define PG_FKCONSTR_MATCH_FULL 'f'
1646#define PG_FKCONSTR_MATCH_PARTIAL 'p'
1647#define PG_FKCONSTR_MATCH_SIMPLE 's'
1648
1649typedef struct PGConstraint {
1650 PGNodeTag type;
1651 PGConstrType contype; /* see above */
1652
1653 /* Fields used for most/all constraint types: */
1654 char *conname; /* PGConstraint name, or NULL if unnamed */
1655 bool deferrable; /* DEFERRABLE? */
1656 bool initdeferred; /* INITIALLY DEFERRED? */
1657 int location; /* token location, or -1 if unknown */
1658
1659 /* Fields used for constraints with expressions (CHECK and DEFAULT): */
1660 bool is_no_inherit; /* is constraint non-inheritable? */
1661 PGNode *raw_expr; /* expr, as untransformed parse tree */
1662 char *cooked_expr; /* expr, as nodeToString representation */
1663 char generated_when;
1664
1665 /* Fields used for unique constraints (UNIQUE and PRIMARY KEY): */
1666 PGList *keys; /* String nodes naming referenced column(s) */
1667
1668 /* Fields used for EXCLUSION constraints: */
1669 PGList *exclusions; /* list of (PGIndexElem, operator name) pairs */
1670
1671 /* Fields used for index constraints (UNIQUE, PRIMARY KEY, EXCLUSION): */
1672 PGList *options; /* options from WITH clause */
1673 char *indexname; /* existing index to use; otherwise NULL */
1674 char *indexspace; /* index tablespace; NULL for default */
1675 /* These could be, but currently are not, used for UNIQUE/PKEY: */
1676 char *access_method; /* index access method; NULL for default */
1677 PGNode *where_clause; /* partial index predicate */
1678
1679 /* Fields used for FOREIGN KEY constraints: */
1680 PGRangeVar *pktable; /* Primary key table */
1681 PGList *fk_attrs; /* Attributes of foreign key */
1682 PGList *pk_attrs; /* Corresponding attrs in PK table */
1683 char fk_matchtype; /* FULL, PARTIAL, SIMPLE */
1684 char fk_upd_action; /* ON UPDATE action */
1685 char fk_del_action; /* ON DELETE action */
1686 PGList *old_conpfeqop; /* pg_constraint.conpfeqop of my former self */
1687 PGOid old_pktable_oid; /* pg_constraint.confrelid of my former
1688 * self */
1689
1690 /* Fields used for constraints that allow a NOT VALID specification */
1691 bool skip_validation; /* skip validation of existing rows? */
1692 bool initially_valid; /* mark the new constraint as valid? */
1693
1694
1695 /* Field Used for COMPRESSION constraint */
1696 char *compression_name; /* existing index to use; otherwise NULL */
1697
1698} PGConstraint;
1699
1700/* ----------------------
1701 * {Create|Alter} SEQUENCE Statement
1702 * ----------------------
1703 */
1704
1705typedef struct PGCreateSeqStmt {
1706 PGNodeTag type;
1707 PGRangeVar *sequence; /* the sequence to create */
1708 PGList *options;
1709 PGOid ownerId; /* ID of owner, or InvalidOid for default */
1710 bool for_identity;
1711 PGOnCreateConflict onconflict; /* what to do on create conflict */
1712} PGCreateSeqStmt;
1713
1714typedef struct PGAlterSeqStmt {
1715 PGNodeTag type;
1716 PGRangeVar *sequence; /* the sequence to alter */
1717 PGList *options;
1718 bool for_identity;
1719 bool missing_ok; /* skip error if a role is missing? */
1720} PGAlterSeqStmt;
1721
1722/* ----------------------
1723 * CREATE FUNCTION Statement
1724 * ----------------------
1725 */
1726
1727typedef struct PGCreateFunctionStmt {
1728 PGNodeTag type;
1729 PGRangeVar *name;
1730 PGList *params;
1731 PGNode *function;
1732 PGNode *query;
1733 PGOnCreateConflict onconflict;
1734} PGCreateFunctionStmt;
1735
1736/* ----------------------
1737 * Drop Table|Sequence|View|Index|Type|Domain|Conversion|Schema Statement
1738 * ----------------------
1739 */
1740
1741typedef struct PGDropStmt {
1742 PGNodeTag type;
1743 PGList *objects; /* list of names */
1744 PGObjectType removeType; /* object type */
1745 PGDropBehavior behavior; /* RESTRICT or CASCADE behavior */
1746 bool missing_ok; /* skip error if object is missing? */
1747 bool concurrent; /* drop index concurrently? */
1748} PGDropStmt;
1749
1750/* ----------------------
1751 * Create PGIndex Statement
1752 *
1753 * This represents creation of an index and/or an associated constraint.
1754 * If isconstraint is true, we should create a pg_constraint entry along
1755 * with the index. But if indexOid isn't InvalidOid, we are not creating an
1756 * index, just a UNIQUE/PKEY constraint using an existing index. isconstraint
1757 * must always be true in this case, and the fields describing the index
1758 * properties are empty.
1759 * ----------------------
1760 */
1761typedef struct PGIndexStmt {
1762 PGNodeTag type;
1763 char *idxname; /* name of new index, or NULL for default */
1764 PGRangeVar *relation; /* relation to build index on */
1765 char *accessMethod; /* name of access method (eg. btree) */
1766 char *tableSpace; /* tablespace, or NULL for default */
1767 PGList *indexParams; /* columns to index: a list of PGIndexElem */
1768 PGList *options; /* WITH clause options: a list of PGDefElem */
1769 PGNode *whereClause; /* qualification (partial-index predicate) */
1770 PGList *excludeOpNames; /* exclusion operator names, or NIL if none */
1771 char *idxcomment; /* comment to apply to index, or NULL */
1772 PGOid indexOid; /* OID of an existing index, if any */
1773 PGOid oldNode; /* relfilenode of existing storage, if any */
1774 bool unique; /* is index unique? */
1775 bool primary; /* is index a primary key? */
1776 bool isconstraint; /* is it for a pkey/unique constraint? */
1777 bool deferrable; /* is the constraint DEFERRABLE? */
1778 bool initdeferred; /* is the constraint INITIALLY DEFERRED? */
1779 bool transformed; /* true when transformIndexStmt is finished */
1780 bool concurrent; /* should this be a concurrent index build? */
1781 PGOnCreateConflict onconflict; /* what to do on create conflict */
1782} PGIndexStmt;
1783
1784/* ----------------------
1785 * Alter Object Rename Statement
1786 * ----------------------
1787 */
1788typedef struct PGRenameStmt {
1789 PGNodeTag type;
1790 PGObjectType renameType; /* PG_OBJECT_TABLE, PG_OBJECT_COLUMN, etc */
1791 PGObjectType relationType; /* if column name, associated relation type */
1792 PGRangeVar *relation; /* in case it's a table */
1793 PGNode *object; /* in case it's some other object */
1794 char *subname; /* name of contained object (column, rule,
1795 * trigger, etc) */
1796 char *newname; /* the new name */
1797 PGDropBehavior behavior; /* RESTRICT or CASCADE behavior */
1798 bool missing_ok; /* skip error if missing? */
1799} PGRenameStmt;
1800
1801/* ----------------------
1802 * ALTER object SET SCHEMA Statement
1803 * ----------------------
1804 */
1805typedef struct PGAlterObjectSchemaStmt {
1806 PGNodeTag type;
1807 PGObjectType objectType; /* PG_OBJECT_TABLE, PG_OBJECT_TYPE, etc */
1808 PGRangeVar *relation; /* in case it's a table */
1809 PGNode *object; /* in case it's some other object */
1810 char *newschema; /* the new schema */
1811 bool missing_ok; /* skip error if missing? */
1812} PGAlterObjectSchemaStmt;
1813
1814/* ----------------------
1815 * {Begin|Commit|Rollback} Transaction Statement
1816 * ----------------------
1817 */
1818typedef enum PGTransactionStmtKind {
1819 PG_TRANS_STMT_BEGIN,
1820 PG_TRANS_STMT_START, /* semantically identical to BEGIN */
1821 PG_TRANS_STMT_COMMIT,
1822 PG_TRANS_STMT_ROLLBACK,
1823 PG_TRANS_STMT_SAVEPOINT,
1824 PG_TRANS_STMT_RELEASE,
1825 PG_TRANS_STMT_ROLLBACK_TO,
1826 PG_TRANS_STMT_PREPARE,
1827 PG_TRANS_STMT_COMMIT_PREPARED,
1828 TRANS_STMT_ROLLBACK_PREPARED
1829} PGTransactionStmtKind;
1830
1831typedef struct PGTransactionStmt {
1832 PGNodeTag type;
1833 PGTransactionStmtKind kind; /* see above */
1834 PGList *options; /* for BEGIN/START and savepoint commands */
1835 char *gid; /* for two-phase-commit related commands */
1836} PGTransactionStmt;
1837
1838/* ----------------------
1839 * Create View Statement
1840 * ----------------------
1841 */
1842typedef enum PGViewCheckOption { PG_NO_CHECK_OPTION, PG_LOCAL_CHECK_OPTION, CASCADED_CHECK_OPTION } PGViewCheckOption;
1843
1844typedef struct PGViewStmt {
1845 PGNodeTag type;
1846 PGRangeVar *view; /* the view to be created */
1847 PGList *aliases; /* target column names */
1848 PGNode *query; /* the SELECT query (as a raw parse tree) */
1849 PGOnCreateConflict onconflict; /* what to do on create conflict */
1850 PGList *options; /* options from WITH clause */
1851 PGViewCheckOption withCheckOption; /* WITH CHECK OPTION */
1852} PGViewStmt;
1853
1854/* ----------------------
1855 * Load Statement
1856 * ----------------------
1857 */
1858
1859typedef enum PGLoadInstallType { PG_LOAD_TYPE_LOAD, PG_LOAD_TYPE_INSTALL, PG_LOAD_TYPE_FORCE_INSTALL } PGLoadInstallType;
1860
1861
1862typedef struct PGLoadStmt {
1863 PGNodeTag type;
1864 const char *filename; /* file to load */
1865 PGLoadInstallType load_type;
1866} PGLoadStmt;
1867
1868/* ----------------------
1869 * Vacuum and Analyze Statements
1870 *
1871 * Even though these are nominally two statements, it's convenient to use
1872 * just one node type for both. Note that at least one of PG_VACOPT_VACUUM
1873 * and PG_VACOPT_ANALYZE must be set in options.
1874 * ----------------------
1875 */
1876typedef enum PGVacuumOption {
1877 PG_VACOPT_VACUUM = 1 << 0, /* do VACUUM */
1878 PG_VACOPT_ANALYZE = 1 << 1, /* do ANALYZE */
1879 PG_VACOPT_VERBOSE = 1 << 2, /* print progress info */
1880 PG_VACOPT_FREEZE = 1 << 3, /* FREEZE option */
1881 PG_VACOPT_FULL = 1 << 4, /* FULL (non-concurrent) vacuum */
1882 PG_VACOPT_NOWAIT = 1 << 5, /* don't wait to get lock (autovacuum only) */
1883 PG_VACOPT_SKIPTOAST = 1 << 6, /* don't process the TOAST table, if any */
1884 PG_VACOPT_DISABLE_PAGE_SKIPPING = 1 << 7 /* don't skip any pages */
1885} PGVacuumOption;
1886
1887typedef struct PGVacuumStmt {
1888 PGNodeTag type;
1889 int options; /* OR of PGVacuumOption flags */
1890 PGRangeVar *relation; /* single table to process, or NULL */
1891 PGList *va_cols; /* list of column names, or NIL for all */
1892} PGVacuumStmt;
1893
1894/* ----------------------
1895 * Explain Statement
1896 *
1897 * The "query" field is initially a raw parse tree, and is converted to a
1898 * PGQuery node during parse analysis. Note that rewriting and planning
1899 * of the query are always postponed until execution.
1900 * ----------------------
1901 */
1902typedef struct PGExplainStmt {
1903 PGNodeTag type;
1904 PGNode *query; /* the query (see comments above) */
1905 PGList *options; /* list of PGDefElem nodes */
1906} PGExplainStmt;
1907
1908/* ----------------------
1909 * CREATE TABLE AS Statement (a/k/a SELECT INTO)
1910 *
1911 * A query written as CREATE TABLE AS will produce this node type natively.
1912 * A query written as SELECT ... INTO will be transformed to this form during
1913 * parse analysis.
1914 * A query written as CREATE MATERIALIZED view will produce this node type,
1915 * during parse analysis, since it needs all the same data.
1916 *
1917 * The "query" field is handled similarly to EXPLAIN, though note that it
1918 * can be a SELECT or an EXECUTE, but not other DML statements.
1919 * ----------------------
1920 */
1921typedef struct PGCreateTableAsStmt {
1922 PGNodeTag type;
1923 PGNode *query; /* the query (see comments above) */
1924 PGIntoClause *into; /* destination table */
1925 PGObjectType relkind; /* PG_OBJECT_TABLE or PG_OBJECT_MATVIEW */
1926 bool is_select_into; /* it was written as SELECT INTO */
1927 PGOnCreateConflict onconflict; /* what to do on create conflict */
1928} PGCreateTableAsStmt;
1929
1930/* ----------------------
1931 * Checkpoint Statement
1932 * ----------------------
1933 */
1934typedef struct PGCheckPointStmt {
1935 PGNodeTag type;
1936 bool force;
1937 char *name;
1938} PGCheckPointStmt;
1939
1940/* ----------------------
1941 * PREPARE Statement
1942 * ----------------------
1943 */
1944typedef struct PGPrepareStmt {
1945 PGNodeTag type;
1946 char *name; /* Name of plan, arbitrary */
1947 PGList *argtypes; /* Types of parameters (PGList of PGTypeName) */
1948 PGNode *query; /* The query itself (as a raw parsetree) */
1949} PGPrepareStmt;
1950
1951/* ----------------------
1952 * EXECUTE Statement
1953 * ----------------------
1954 */
1955
1956typedef struct PGExecuteStmt {
1957 PGNodeTag type;
1958 char *name; /* The name of the plan to execute */
1959 PGList *params; /* Values to assign to parameters */
1960} PGExecuteStmt;
1961
1962/* ----------------------
1963 * DEALLOCATE Statement
1964 * ----------------------
1965 */
1966typedef struct PGDeallocateStmt {
1967 PGNodeTag type;
1968 char *name; /* The name of the plan to remove */
1969 /* NULL means DEALLOCATE ALL */
1970} PGDeallocateStmt;
1971
1972/* ----------------------
1973 * PRAGMA statements
1974 * Three types of pragma statements:
1975 * PRAGMA pragma_name; (NOTHING)
1976 * PRAGMA pragma_name='param'; (ASSIGNMENT)
1977 * PRAGMA pragma_name('param'); (CALL)
1978 * ----------------------
1979 */
1980typedef enum { PG_PRAGMA_TYPE_NOTHING, PG_PRAGMA_TYPE_ASSIGNMENT, PG_PRAGMA_TYPE_CALL } PGPragmaKind;
1981
1982typedef struct PGPragmaStmt {
1983 PGNodeTag type;
1984 PGPragmaKind kind;
1985 char *name; /* variable to be set */
1986 PGList *args; /* PGList of PGAConst nodes */
1987} PGPragmaStmt;
1988
1989/* ----------------------
1990 * CALL Statement
1991 * ----------------------
1992 */
1993
1994typedef struct PGCallStmt {
1995 PGNodeTag type;
1996 PGNode *func;
1997} PGCallStmt;
1998
1999/* ----------------------
2000 * EXPORT/IMPORT Statements
2001 * ----------------------
2002 */
2003
2004typedef struct PGExportStmt {
2005 PGNodeTag type;
2006 char *database; /* database name */
2007 char *filename; /* filename */
2008 PGList *options; /* PGList of PGDefElem nodes */
2009} PGExportStmt;
2010
2011typedef struct PGImportStmt {
2012 PGNodeTag type;
2013 char *filename; /* filename */
2014} PGImportStmt;
2015
2016/* ----------------------
2017 * Interval Constant
2018 * ----------------------
2019 */
2020typedef struct PGIntervalConstant {
2021 PGNodeTag type;
2022 int val_type; /* interval constant type, either duckdb_libpgquery::T_PGString, duckdb_libpgquery::T_PGInteger or duckdb_libpgquery::T_PGAExpr */
2023 char *sval; /* duckdb_libpgquery::T_PGString */
2024 int ival; /* duckdb_libpgquery::T_PGString */
2025 PGNode *eval; /* duckdb_libpgquery::T_PGAExpr */
2026 PGList *typmods; /* how to interpret the interval constant (year, month, day, etc) */
2027 int location; /* token location, or -1 if unknown */
2028} PGIntervalConstant;
2029
2030/* ----------------------
2031 * Sample Options
2032 * ----------------------
2033 */
2034typedef struct PGSampleSize {
2035 PGNodeTag type;
2036 bool is_percentage; /* whether or not the sample size is expressed in row numbers or a percentage */
2037 PGValue sample_size; /* sample size */
2038} PGSampleSize;
2039
2040typedef struct PGSampleOptions {
2041 PGNodeTag type;
2042 PGNode *sample_size; /* the size of the sample to take */
2043 char *method; /* sample method, or NULL for default */
2044 bool has_seed; /* if the sample method has seed */
2045 int seed; /* the seed value if set; */
2046 int location; /* token location, or -1 if unknown */
2047} PGSampleOptions;
2048
2049/* ----------------------
2050 * Limit Percentage
2051 * ----------------------
2052 */
2053typedef struct PGLimitPercent {
2054 PGNodeTag type;
2055 PGNode* limit_percent; /* limit percent */
2056} PGLimitPercent;
2057
2058/* ----------------------
2059 * Lambda Function (or Arrow Operator)
2060 * ----------------------
2061 */
2062typedef struct PGLambdaFunction {
2063 PGNodeTag type;
2064 PGNode *lhs; /* parameter expression */
2065 PGNode *rhs; /* lambda expression */
2066 int location; /* token location, or -1 if unknown */
2067} PGLambdaFunction;
2068
2069/* ----------------------
2070 * Positional Reference
2071 * ----------------------
2072 */
2073typedef struct PGPositionalReference {
2074 PGNodeTag type;
2075 int position;
2076 int location; /* token location, or -1 if unknown */
2077} PGPositionalReference;
2078
2079/* ----------------------
2080 * Type Statement
2081 * ----------------------
2082 */
2083
2084typedef enum { PG_NEWTYPE_NONE, PG_NEWTYPE_ENUM, PG_NEWTYPE_ALIAS } PGNewTypeKind;
2085
2086typedef struct PGCreateTypeStmt
2087{
2088 PGNodeTag type;
2089 PGNewTypeKind kind;
2090 PGRangeVar *typeName; /* qualified name (list of Value strings) */
2091 PGList *vals; /* enum values (list of Value strings) */
2092 PGTypeName *ofType; /* original type of alias name */
2093 PGNode *query;
2094} PGCreateTypeStmt;
2095
2096/* ----------------------
2097 * Attach Statement
2098 * ----------------------
2099 */
2100
2101typedef struct PGAttachStmt
2102{
2103 PGNodeTag type;
2104 char *path; /* The file path of the to-be-attached database */
2105 char *name; /* The name of the attached database */
2106 PGList *options; /* PGList of PGDefElem nodes */
2107 PGNode *query;
2108} PGAttachStmt;
2109
2110/* ----------------------
2111 * Dettach Statement
2112 * ----------------------
2113 */
2114
2115typedef struct PGDetachStmt
2116{
2117 PGNodeTag type;
2118 char *db_name; /* list of names of attached databases */
2119 bool missing_ok;
2120} PGDetachStmt;
2121
2122/* ----------------------
2123 * Use Statement
2124 * ----------------------
2125 */
2126
2127typedef struct PGUseStmt {
2128 PGNodeTag type;
2129 PGRangeVar *name; /* variable to be set */
2130} PGUseStmt;
2131
2132
2133}
2134