]> granicus.if.org Git - postgresql/blob - src/include/nodes/parsenodes.h
Implement IF NOT EXISTS for CREATE SEQUENCE.
[postgresql] / src / include / nodes / parsenodes.h
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.
11  *
12  *
13  * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
14  * Portions Copyright (c) 1994, Regents of the University of California
15  *
16  * src/include/nodes/parsenodes.h
17  *
18  *-------------------------------------------------------------------------
19  */
20 #ifndef PARSENODES_H
21 #define PARSENODES_H
22
23 #include "nodes/bitmapset.h"
24 #include "nodes/primnodes.h"
25 #include "nodes/value.h"
26
27 /* Possible sources of a Query */
28 typedef enum QuerySource
29 {
30         QSRC_ORIGINAL,                          /* original parsetree (explicit query) */
31         QSRC_PARSER,                            /* added by parse analysis (now unused) */
32         QSRC_INSTEAD_RULE,                      /* added by unconditional INSTEAD rule */
33         QSRC_QUAL_INSTEAD_RULE,         /* added by conditional INSTEAD rule */
34         QSRC_NON_INSTEAD_RULE           /* added by non-INSTEAD rule */
35 } QuerySource;
36
37 /* Sort ordering options for ORDER BY and CREATE INDEX */
38 typedef enum SortByDir
39 {
40         SORTBY_DEFAULT,
41         SORTBY_ASC,
42         SORTBY_DESC,
43         SORTBY_USING                            /* not allowed in CREATE INDEX ... */
44 } SortByDir;
45
46 typedef enum SortByNulls
47 {
48         SORTBY_NULLS_DEFAULT,
49         SORTBY_NULLS_FIRST,
50         SORTBY_NULLS_LAST
51 } SortByNulls;
52
53 /*
54  * Grantable rights are encoded so that we can OR them together in a bitmask.
55  * The present representation of AclItem limits us to 16 distinct rights,
56  * even though AclMode is defined as uint32.  See utils/acl.h.
57  *
58  * Caution: changing these codes breaks stored ACLs, hence forces initdb.
59  */
60 typedef uint32 AclMode;                 /* a bitmask of privilege bits */
61
62 #define ACL_INSERT              (1<<0)  /* for relations */
63 #define ACL_SELECT              (1<<1)
64 #define ACL_UPDATE              (1<<2)
65 #define ACL_DELETE              (1<<3)
66 #define ACL_TRUNCATE    (1<<4)
67 #define ACL_REFERENCES  (1<<5)
68 #define ACL_TRIGGER             (1<<6)
69 #define ACL_EXECUTE             (1<<7)  /* for functions */
70 #define ACL_USAGE               (1<<8)  /* for languages, namespaces, FDWs, and
71                                                                  * servers */
72 #define ACL_CREATE              (1<<9)  /* for namespaces and databases */
73 #define ACL_CREATE_TEMP (1<<10) /* for databases */
74 #define ACL_CONNECT             (1<<11) /* for databases */
75 #define N_ACL_RIGHTS    12              /* 1 plus the last 1<<x */
76 #define ACL_NO_RIGHTS   0
77 /* Currently, SELECT ... FOR [KEY] UPDATE/SHARE requires UPDATE privileges */
78 #define ACL_SELECT_FOR_UPDATE   ACL_UPDATE
79
80
81 /*****************************************************************************
82  *      Query Tree
83  *****************************************************************************/
84
85 /*
86  * Query -
87  *        Parse analysis turns all statements into a Query tree
88  *        for further processing by the rewriter and planner.
89  *
90  *        Utility statements (i.e. non-optimizable statements) have the
91  *        utilityStmt field set, and the Query itself is mostly dummy.
92  *        DECLARE CURSOR is a special case: it is represented like a SELECT,
93  *        but the original DeclareCursorStmt is stored in utilityStmt.
94  *
95  *        Planning converts a Query tree into a Plan tree headed by a PlannedStmt
96  *        node --- the Query structure is not used by the executor.
97  */
98 typedef struct Query
99 {
100         NodeTag         type;
101
102         CmdType         commandType;    /* select|insert|update|delete|utility */
103
104         QuerySource querySource;        /* where did I come from? */
105
106         uint32          queryId;                /* query identifier (can be set by plugins) */
107
108         bool            canSetTag;              /* do I set the command result tag? */
109
110         Node       *utilityStmt;        /* non-null if this is DECLARE CURSOR or a
111                                                                  * non-optimizable statement */
112
113         int                     resultRelation; /* rtable index of target relation for
114                                                                  * INSERT/UPDATE/DELETE; 0 for SELECT */
115
116         bool            hasAggs;                /* has aggregates in tlist or havingQual */
117         bool            hasWindowFuncs; /* has window functions in tlist */
118         bool            hasSubLinks;    /* has subquery SubLink */
119         bool            hasDistinctOn;  /* distinctClause is from DISTINCT ON */
120         bool            hasRecursive;   /* WITH RECURSIVE was specified */
121         bool            hasModifyingCTE;        /* has INSERT/UPDATE/DELETE in WITH */
122         bool            hasForUpdate;   /* FOR [KEY] UPDATE/SHARE was specified */
123
124         List       *cteList;            /* WITH list (of CommonTableExpr's) */
125
126         List       *rtable;                     /* list of range table entries */
127         FromExpr   *jointree;           /* table join tree (FROM and WHERE clauses) */
128
129         List       *targetList;         /* target list (of TargetEntry) */
130
131         List       *withCheckOptions;           /* a list of WithCheckOption's */
132
133         List       *returningList;      /* return-values list (of TargetEntry) */
134
135         List       *groupClause;        /* a list of SortGroupClause's */
136
137         Node       *havingQual;         /* qualifications applied to groups */
138
139         List       *windowClause;       /* a list of WindowClause's */
140
141         List       *distinctClause; /* a list of SortGroupClause's */
142
143         List       *sortClause;         /* a list of SortGroupClause's */
144
145         Node       *limitOffset;        /* # of result tuples to skip (int8 expr) */
146         Node       *limitCount;         /* # of result tuples to return (int8 expr) */
147
148         List       *rowMarks;           /* a list of RowMarkClause's */
149
150         Node       *setOperations;      /* set-operation tree if this is top level of
151                                                                  * a UNION/INTERSECT/EXCEPT query */
152
153         List       *constraintDeps; /* a list of pg_constraint OIDs that the query
154                                                                  * depends on to be semantically valid */
155 } Query;
156
157
158 /****************************************************************************
159  *      Supporting data structures for Parse Trees
160  *
161  *      Most of these node types appear in raw parsetrees output by the grammar,
162  *      and get transformed to something else by the analyzer.  A few of them
163  *      are used as-is in transformed querytrees.
164  ****************************************************************************/
165
166 /*
167  * TypeName - specifies a type in definitions
168  *
169  * For TypeName structures generated internally, it is often easier to
170  * specify the type by OID than by name.  If "names" is NIL then the
171  * actual type OID is given by typeOid, otherwise typeOid is unused.
172  * Similarly, if "typmods" is NIL then the actual typmod is expected to
173  * be prespecified in typemod, otherwise typemod is unused.
174  *
175  * If pct_type is TRUE, then names is actually a field name and we look up
176  * the type of that field.  Otherwise (the normal case), names is a type
177  * name possibly qualified with schema and database name.
178  */
179 typedef struct TypeName
180 {
181         NodeTag         type;
182         List       *names;                      /* qualified name (list of Value strings) */
183         Oid                     typeOid;                /* type identified by OID */
184         bool            setof;                  /* is a set? */
185         bool            pct_type;               /* %TYPE specified? */
186         List       *typmods;            /* type modifier expression(s) */
187         int32           typemod;                /* prespecified type modifier */
188         List       *arrayBounds;        /* array bounds */
189         int                     location;               /* token location, or -1 if unknown */
190 } TypeName;
191
192 /*
193  * ColumnRef - specifies a reference to a column, or possibly a whole tuple
194  *
195  * The "fields" list must be nonempty.  It can contain string Value nodes
196  * (representing names) and A_Star nodes (representing occurrence of a '*').
197  * Currently, A_Star must appear only as the last list element --- the grammar
198  * is responsible for enforcing this!
199  *
200  * Note: any array subscripting or selection of fields from composite columns
201  * is represented by an A_Indirection node above the ColumnRef.  However,
202  * for simplicity in the normal case, initial field selection from a table
203  * name is represented within ColumnRef and not by adding A_Indirection.
204  */
205 typedef struct ColumnRef
206 {
207         NodeTag         type;
208         List       *fields;                     /* field names (Value strings) or A_Star */
209         int                     location;               /* token location, or -1 if unknown */
210 } ColumnRef;
211
212 /*
213  * ParamRef - specifies a $n parameter reference
214  */
215 typedef struct ParamRef
216 {
217         NodeTag         type;
218         int                     number;                 /* the number of the parameter */
219         int                     location;               /* token location, or -1 if unknown */
220 } ParamRef;
221
222 /*
223  * A_Expr - infix, prefix, and postfix expressions
224  */
225 typedef enum A_Expr_Kind
226 {
227         AEXPR_OP,                                       /* normal operator */
228         AEXPR_OP_ANY,                           /* scalar op ANY (array) */
229         AEXPR_OP_ALL,                           /* scalar op ALL (array) */
230         AEXPR_DISTINCT,                         /* IS DISTINCT FROM - name must be "=" */
231         AEXPR_NULLIF,                           /* NULLIF - name must be "=" */
232         AEXPR_OF,                                       /* IS [NOT] OF - name must be "=" or "<>" */
233         AEXPR_IN                                        /* [NOT] IN - name must be "=" or "<>" */
234 } A_Expr_Kind;
235
236 typedef struct A_Expr
237 {
238         NodeTag         type;
239         A_Expr_Kind kind;                       /* see above */
240         List       *name;                       /* possibly-qualified name of operator */
241         Node       *lexpr;                      /* left argument, or NULL if none */
242         Node       *rexpr;                      /* right argument, or NULL if none */
243         int                     location;               /* token location, or -1 if unknown */
244 } A_Expr;
245
246 /*
247  * A_Const - a literal constant
248  */
249 typedef struct A_Const
250 {
251         NodeTag         type;
252         Value           val;                    /* value (includes type info, see value.h) */
253         int                     location;               /* token location, or -1 if unknown */
254 } A_Const;
255
256 /*
257  * TypeCast - a CAST expression
258  */
259 typedef struct TypeCast
260 {
261         NodeTag         type;
262         Node       *arg;                        /* the expression being casted */
263         TypeName   *typeName;           /* the target type */
264         int                     location;               /* token location, or -1 if unknown */
265 } TypeCast;
266
267 /*
268  * CollateClause - a COLLATE expression
269  */
270 typedef struct CollateClause
271 {
272         NodeTag         type;
273         Node       *arg;                        /* input expression */
274         List       *collname;           /* possibly-qualified collation name */
275         int                     location;               /* token location, or -1 if unknown */
276 } CollateClause;
277
278 /*
279  * FuncCall - a function or aggregate invocation
280  *
281  * agg_order (if not NIL) indicates we saw 'foo(... ORDER BY ...)', or if
282  * agg_within_group is true, it was 'foo(...) WITHIN GROUP (ORDER BY ...)'.
283  * agg_star indicates we saw a 'foo(*)' construct, while agg_distinct
284  * indicates we saw 'foo(DISTINCT ...)'.  In any of these cases, the
285  * construct *must* be an aggregate call.  Otherwise, it might be either an
286  * aggregate or some other kind of function.  However, if FILTER or OVER is
287  * present it had better be an aggregate or window function.
288  *
289  * Normally, you'd initialize this via makeFuncCall() and then only change the
290  * parts of the struct its defaults don't match afterwards, as needed.
291  */
292 typedef struct FuncCall
293 {
294         NodeTag         type;
295         List       *funcname;           /* qualified name of function */
296         List       *args;                       /* the arguments (list of exprs) */
297         List       *agg_order;          /* ORDER BY (list of SortBy) */
298         Node       *agg_filter;         /* FILTER clause, if any */
299         bool            agg_within_group;               /* ORDER BY appeared in WITHIN GROUP */
300         bool            agg_star;               /* argument was really '*' */
301         bool            agg_distinct;   /* arguments were labeled DISTINCT */
302         bool            func_variadic;  /* last argument was labeled VARIADIC */
303         struct WindowDef *over;         /* OVER clause, if any */
304         int                     location;               /* token location, or -1 if unknown */
305 } FuncCall;
306
307 /*
308  * A_Star - '*' representing all columns of a table or compound field
309  *
310  * This can appear within ColumnRef.fields, A_Indirection.indirection, and
311  * ResTarget.indirection lists.
312  */
313 typedef struct A_Star
314 {
315         NodeTag         type;
316 } A_Star;
317
318 /*
319  * A_Indices - array subscript or slice bounds ([lidx:uidx] or [uidx])
320  */
321 typedef struct A_Indices
322 {
323         NodeTag         type;
324         Node       *lidx;                       /* NULL if it's a single subscript */
325         Node       *uidx;
326 } A_Indices;
327
328 /*
329  * A_Indirection - select a field and/or array element from an expression
330  *
331  * The indirection list can contain A_Indices nodes (representing
332  * subscripting), string Value nodes (representing field selection --- the
333  * string value is the name of the field to select), and A_Star nodes
334  * (representing selection of all fields of a composite type).
335  * For example, a complex selection operation like
336  *                              (foo).field1[42][7].field2
337  * would be represented with a single A_Indirection node having a 4-element
338  * indirection list.
339  *
340  * Currently, A_Star must appear only as the last list element --- the grammar
341  * is responsible for enforcing this!
342  */
343 typedef struct A_Indirection
344 {
345         NodeTag         type;
346         Node       *arg;                        /* the thing being selected from */
347         List       *indirection;        /* subscripts and/or field names and/or * */
348 } A_Indirection;
349
350 /*
351  * A_ArrayExpr - an ARRAY[] construct
352  */
353 typedef struct A_ArrayExpr
354 {
355         NodeTag         type;
356         List       *elements;           /* array element expressions */
357         int                     location;               /* token location, or -1 if unknown */
358 } A_ArrayExpr;
359
360 /*
361  * ResTarget -
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 ResTarget 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 A_Indirection for more info about what can appear in 'indirection'.
377  */
378 typedef struct ResTarget
379 {
380         NodeTag         type;
381         char       *name;                       /* column name or NULL */
382         List       *indirection;        /* subscripts, field names, and '*', or NIL */
383         Node       *val;                        /* the value expression to compute or assign */
384         int                     location;               /* token location, or -1 if unknown */
385 } ResTarget;
386
387 /*
388  * MultiAssignRef - element of a row source expression for UPDATE
389  *
390  * In an UPDATE target list, when we have SET (a,b,c) = row-valued-expression,
391  * we generate separate ResTarget items for each of a,b,c.  Their "val" trees
392  * are MultiAssignRef nodes numbered 1..n, linking to a common copy of the
393  * row-valued-expression (which parse analysis will process only once, when
394  * handling the MultiAssignRef with colno=1).
395  */
396 typedef struct MultiAssignRef
397 {
398         NodeTag         type;
399         Node       *source;                     /* the row-valued expression */
400         int                     colno;                  /* column number for this target (1..n) */
401         int                     ncolumns;               /* number of targets in the construct */
402 } MultiAssignRef;
403
404 /*
405  * SortBy - for ORDER BY clause
406  */
407 typedef struct SortBy
408 {
409         NodeTag         type;
410         Node       *node;                       /* expression to sort on */
411         SortByDir       sortby_dir;             /* ASC/DESC/USING/default */
412         SortByNulls sortby_nulls;       /* NULLS FIRST/LAST */
413         List       *useOp;                      /* name of op to use, if SORTBY_USING */
414         int                     location;               /* operator location, or -1 if none/unknown */
415 } SortBy;
416
417 /*
418  * WindowDef - raw representation of WINDOW and OVER clauses
419  *
420  * For entries in a WINDOW list, "name" is the window name being defined.
421  * For OVER clauses, we use "name" for the "OVER window" syntax, or "refname"
422  * for the "OVER (window)" syntax, which is subtly different --- the latter
423  * implies overriding the window frame clause.
424  */
425 typedef struct WindowDef
426 {
427         NodeTag         type;
428         char       *name;                       /* window's own name */
429         char       *refname;            /* referenced window name, if any */
430         List       *partitionClause;    /* PARTITION BY expression list */
431         List       *orderClause;        /* ORDER BY (list of SortBy) */
432         int                     frameOptions;   /* frame_clause options, see below */
433         Node       *startOffset;        /* expression for starting bound, if any */
434         Node       *endOffset;          /* expression for ending bound, if any */
435         int                     location;               /* parse location, or -1 if none/unknown */
436 } WindowDef;
437
438 /*
439  * frameOptions is an OR of these bits.  The NONDEFAULT and BETWEEN bits are
440  * used so that ruleutils.c can tell which properties were specified and
441  * which were defaulted; the correct behavioral bits must be set either way.
442  * The START_foo and END_foo options must come in pairs of adjacent bits for
443  * the convenience of gram.y, even though some of them are useless/invalid.
444  * We will need more bits (and fields) to cover the full SQL:2008 option set.
445  */
446 #define FRAMEOPTION_NONDEFAULT                                  0x00001 /* any specified? */
447 #define FRAMEOPTION_RANGE                                               0x00002 /* RANGE behavior */
448 #define FRAMEOPTION_ROWS                                                0x00004 /* ROWS behavior */
449 #define FRAMEOPTION_BETWEEN                                             0x00008 /* BETWEEN given? */
450 #define FRAMEOPTION_START_UNBOUNDED_PRECEDING   0x00010 /* start is U. P. */
451 #define FRAMEOPTION_END_UNBOUNDED_PRECEDING             0x00020 /* (disallowed) */
452 #define FRAMEOPTION_START_UNBOUNDED_FOLLOWING   0x00040 /* (disallowed) */
453 #define FRAMEOPTION_END_UNBOUNDED_FOLLOWING             0x00080 /* end is U. F. */
454 #define FRAMEOPTION_START_CURRENT_ROW                   0x00100 /* start is C. R. */
455 #define FRAMEOPTION_END_CURRENT_ROW                             0x00200 /* end is C. R. */
456 #define FRAMEOPTION_START_VALUE_PRECEDING               0x00400 /* start is V. P. */
457 #define FRAMEOPTION_END_VALUE_PRECEDING                 0x00800 /* end is V. P. */
458 #define FRAMEOPTION_START_VALUE_FOLLOWING               0x01000 /* start is V. F. */
459 #define FRAMEOPTION_END_VALUE_FOLLOWING                 0x02000 /* end is V. F. */
460
461 #define FRAMEOPTION_START_VALUE \
462         (FRAMEOPTION_START_VALUE_PRECEDING | FRAMEOPTION_START_VALUE_FOLLOWING)
463 #define FRAMEOPTION_END_VALUE \
464         (FRAMEOPTION_END_VALUE_PRECEDING | FRAMEOPTION_END_VALUE_FOLLOWING)
465
466 #define FRAMEOPTION_DEFAULTS \
467         (FRAMEOPTION_RANGE | FRAMEOPTION_START_UNBOUNDED_PRECEDING | \
468          FRAMEOPTION_END_CURRENT_ROW)
469
470 /*
471  * RangeSubselect - subquery appearing in a FROM clause
472  */
473 typedef struct RangeSubselect
474 {
475         NodeTag         type;
476         bool            lateral;                /* does it have LATERAL prefix? */
477         Node       *subquery;           /* the untransformed sub-select clause */
478         Alias      *alias;                      /* table alias & optional column aliases */
479 } RangeSubselect;
480
481 /*
482  * RangeFunction - function call appearing in a FROM clause
483  *
484  * functions is a List because we use this to represent the construct
485  * ROWS FROM(func1(...), func2(...), ...).  Each element of this list is a
486  * two-element sublist, the first element being the untransformed function
487  * call tree, and the second element being a possibly-empty list of ColumnDef
488  * nodes representing any columndef list attached to that function within the
489  * ROWS FROM() syntax.
490  *
491  * alias and coldeflist represent any alias and/or columndef list attached
492  * at the top level.  (We disallow coldeflist appearing both here and
493  * per-function, but that's checked in parse analysis, not by the grammar.)
494  */
495 typedef struct RangeFunction
496 {
497         NodeTag         type;
498         bool            lateral;                /* does it have LATERAL prefix? */
499         bool            ordinality;             /* does it have WITH ORDINALITY suffix? */
500         bool            is_rowsfrom;    /* is result of ROWS FROM() syntax? */
501         List       *functions;          /* per-function information, see above */
502         Alias      *alias;                      /* table alias & optional column aliases */
503         List       *coldeflist;         /* list of ColumnDef nodes to describe result
504                                                                  * of function returning RECORD */
505 } RangeFunction;
506
507 /*
508  * ColumnDef - column definition (used in various creates)
509  *
510  * If the column has a default value, we may have the value expression
511  * in either "raw" form (an untransformed parse tree) or "cooked" form
512  * (a post-parse-analysis, executable expression tree), depending on
513  * how this ColumnDef node was created (by parsing, or by inheritance
514  * from an existing relation).  We should never have both in the same node!
515  *
516  * Similarly, we may have a COLLATE specification in either raw form
517  * (represented as a CollateClause with arg==NULL) or cooked form
518  * (the collation's OID).
519  *
520  * The constraints list may contain a CONSTR_DEFAULT item in a raw
521  * parsetree produced by gram.y, but transformCreateStmt will remove
522  * the item and set raw_default instead.  CONSTR_DEFAULT items
523  * should not appear in any subsequent processing.
524  */
525 typedef struct ColumnDef
526 {
527         NodeTag         type;
528         char       *colname;            /* name of column */
529         TypeName   *typeName;           /* type of column */
530         int                     inhcount;               /* number of times column is inherited */
531         bool            is_local;               /* column has local (non-inherited) def'n */
532         bool            is_not_null;    /* NOT NULL constraint specified? */
533         bool            is_from_type;   /* column definition came from table type */
534         char            storage;                /* attstorage setting, or 0 for default */
535         Node       *raw_default;        /* default value (untransformed parse tree) */
536         Node       *cooked_default; /* default value (transformed expr tree) */
537         CollateClause *collClause;      /* untransformed COLLATE spec, if any */
538         Oid                     collOid;                /* collation OID (InvalidOid if not set) */
539         List       *constraints;        /* other constraints on column */
540         List       *fdwoptions;         /* per-column FDW options */
541         int                     location;               /* parse location, or -1 if none/unknown */
542 } ColumnDef;
543
544 /*
545  * TableLikeClause - CREATE TABLE ( ... LIKE ... ) clause
546  */
547 typedef struct TableLikeClause
548 {
549         NodeTag         type;
550         RangeVar   *relation;
551         bits32          options;                /* OR of TableLikeOption flags */
552 } TableLikeClause;
553
554 typedef enum TableLikeOption
555 {
556         CREATE_TABLE_LIKE_DEFAULTS = 1 << 0,
557         CREATE_TABLE_LIKE_CONSTRAINTS = 1 << 1,
558         CREATE_TABLE_LIKE_INDEXES = 1 << 2,
559         CREATE_TABLE_LIKE_STORAGE = 1 << 3,
560         CREATE_TABLE_LIKE_COMMENTS = 1 << 4,
561         CREATE_TABLE_LIKE_ALL = 0x7FFFFFFF
562 } TableLikeOption;
563
564 /*
565  * IndexElem - index parameters (used in CREATE INDEX)
566  *
567  * For a plain index attribute, 'name' is the name of the table column to
568  * index, and 'expr' is NULL.  For an index expression, 'name' is NULL and
569  * 'expr' is the expression tree.
570  */
571 typedef struct IndexElem
572 {
573         NodeTag         type;
574         char       *name;                       /* name of attribute to index, or NULL */
575         Node       *expr;                       /* expression to index, or NULL */
576         char       *indexcolname;       /* name for index column; NULL = default */
577         List       *collation;          /* name of collation; NIL = default */
578         List       *opclass;            /* name of desired opclass; NIL = default */
579         SortByDir       ordering;               /* ASC/DESC/default */
580         SortByNulls nulls_ordering; /* FIRST/LAST/default */
581 } IndexElem;
582
583 /*
584  * DefElem - a generic "name = value" option definition
585  *
586  * In some contexts the name can be qualified.  Also, certain SQL commands
587  * allow a SET/ADD/DROP action to be attached to option settings, so it's
588  * convenient to carry a field for that too.  (Note: currently, it is our
589  * practice that the grammar allows namespace and action only in statements
590  * where they are relevant; C code can just ignore those fields in other
591  * statements.)
592  */
593 typedef enum DefElemAction
594 {
595         DEFELEM_UNSPEC,                         /* no action given */
596         DEFELEM_SET,
597         DEFELEM_ADD,
598         DEFELEM_DROP
599 } DefElemAction;
600
601 typedef struct DefElem
602 {
603         NodeTag         type;
604         char       *defnamespace;       /* NULL if unqualified name */
605         char       *defname;
606         Node       *arg;                        /* a (Value *) or a (TypeName *) */
607         DefElemAction defaction;        /* unspecified action, or SET/ADD/DROP */
608 } DefElem;
609
610 /*
611  * LockingClause - raw representation of FOR [NO KEY] UPDATE/[KEY] SHARE
612  *              options
613  *
614  * Note: lockedRels == NIL means "all relations in query".  Otherwise it
615  * is a list of RangeVar nodes.  (We use RangeVar mainly because it carries
616  * a location field --- currently, parse analysis insists on unqualified
617  * names in LockingClause.)
618  */
619 typedef enum LockClauseStrength
620 {
621         /* order is important -- see applyLockingClause */
622         LCS_FORKEYSHARE,
623         LCS_FORSHARE,
624         LCS_FORNOKEYUPDATE,
625         LCS_FORUPDATE
626 } LockClauseStrength;
627
628 typedef struct LockingClause
629 {
630         NodeTag         type;
631         List       *lockedRels;         /* FOR [KEY] UPDATE/SHARE relations */
632         LockClauseStrength strength;
633         bool            noWait;                 /* NOWAIT option */
634 } LockingClause;
635
636 /*
637  * XMLSERIALIZE (in raw parse tree only)
638  */
639 typedef struct XmlSerialize
640 {
641         NodeTag         type;
642         XmlOptionType xmloption;        /* DOCUMENT or CONTENT */
643         Node       *expr;
644         TypeName   *typeName;
645         int                     location;               /* token location, or -1 if unknown */
646 } XmlSerialize;
647
648
649 /****************************************************************************
650  *      Nodes for a Query tree
651  ****************************************************************************/
652
653 /*--------------------
654  * RangeTblEntry -
655  *        A range table is a List of RangeTblEntry nodes.
656  *
657  *        A range table entry may represent a plain relation, a sub-select in
658  *        FROM, or the result of a JOIN clause.  (Only explicit JOIN syntax
659  *        produces an RTE, not the implicit join resulting from multiple FROM
660  *        items.  This is because we only need the RTE to deal with SQL features
661  *        like outer joins and join-output-column aliasing.)  Other special
662  *        RTE types also exist, as indicated by RTEKind.
663  *
664  *        Note that we consider RTE_RELATION to cover anything that has a pg_class
665  *        entry.  relkind distinguishes the sub-cases.
666  *
667  *        alias is an Alias node representing the AS alias-clause attached to the
668  *        FROM expression, or NULL if no clause.
669  *
670  *        eref is the table reference name and column reference names (either
671  *        real or aliases).  Note that system columns (OID etc) are not included
672  *        in the column list.
673  *        eref->aliasname is required to be present, and should generally be used
674  *        to identify the RTE for error messages etc.
675  *
676  *        In RELATION RTEs, the colnames in both alias and eref are indexed by
677  *        physical attribute number; this means there must be colname entries for
678  *        dropped columns.  When building an RTE we insert empty strings ("") for
679  *        dropped columns.  Note however that a stored rule may have nonempty
680  *        colnames for columns dropped since the rule was created (and for that
681  *        matter the colnames might be out of date due to column renamings).
682  *        The same comments apply to FUNCTION RTEs when a function's return type
683  *        is a named composite type.
684  *
685  *        In JOIN RTEs, the colnames in both alias and eref are one-to-one with
686  *        joinaliasvars entries.  A JOIN RTE will omit columns of its inputs when
687  *        those columns are known to be dropped at parse time.  Again, however,
688  *        a stored rule might contain entries for columns dropped since the rule
689  *        was created.  (This is only possible for columns not actually referenced
690  *        in the rule.)  When loading a stored rule, we replace the joinaliasvars
691  *        items for any such columns with null pointers.  (We can't simply delete
692  *        them from the joinaliasvars list, because that would affect the attnums
693  *        of Vars referencing the rest of the list.)
694  *
695  *        inh is TRUE for relation references that should be expanded to include
696  *        inheritance children, if the rel has any.  This *must* be FALSE for
697  *        RTEs other than RTE_RELATION entries.
698  *
699  *        inFromCl marks those range variables that are listed in the FROM clause.
700  *        It's false for RTEs that are added to a query behind the scenes, such
701  *        as the NEW and OLD variables for a rule, or the subqueries of a UNION.
702  *        This flag is not used anymore during parsing, since the parser now uses
703  *        a separate "namespace" data structure to control visibility, but it is
704  *        needed by ruleutils.c to determine whether RTEs should be shown in
705  *        decompiled queries.
706  *
707  *        requiredPerms and checkAsUser specify run-time access permissions
708  *        checks to be performed at query startup.  The user must have *all*
709  *        of the permissions that are OR'd together in requiredPerms (zero
710  *        indicates no permissions checking).  If checkAsUser is not zero,
711  *        then do the permissions checks using the access rights of that user,
712  *        not the current effective user ID.  (This allows rules to act as
713  *        setuid gateways.)  Permissions checks only apply to RELATION RTEs.
714  *
715  *        For SELECT/INSERT/UPDATE permissions, if the user doesn't have
716  *        table-wide permissions then it is sufficient to have the permissions
717  *        on all columns identified in selectedCols (for SELECT) and/or
718  *        modifiedCols (for INSERT/UPDATE; we can tell which from the query type).
719  *        selectedCols and modifiedCols are bitmapsets, which cannot have negative
720  *        integer members, so we subtract FirstLowInvalidHeapAttributeNumber from
721  *        column numbers before storing them in these fields.  A whole-row Var
722  *        reference is represented by setting the bit for InvalidAttrNumber.
723  *--------------------
724  */
725 typedef enum RTEKind
726 {
727         RTE_RELATION,                           /* ordinary relation reference */
728         RTE_SUBQUERY,                           /* subquery in FROM */
729         RTE_JOIN,                                       /* join */
730         RTE_FUNCTION,                           /* function in FROM */
731         RTE_VALUES,                                     /* VALUES (<exprlist>), (<exprlist>), ... */
732         RTE_CTE                                         /* common table expr (WITH list element) */
733 } RTEKind;
734
735 typedef struct RangeTblEntry
736 {
737         NodeTag         type;
738
739         RTEKind         rtekind;                /* see above */
740
741         /*
742          * XXX the fields applicable to only some rte kinds should be merged into
743          * a union.  I didn't do this yet because the diffs would impact a lot of
744          * code that is being actively worked on.  FIXME someday.
745          */
746
747         /*
748          * Fields valid for a plain relation RTE (else zero):
749          */
750         Oid                     relid;                  /* OID of the relation */
751         char            relkind;                /* relation kind (see pg_class.relkind) */
752
753         /*
754          * Fields valid for a subquery RTE (else NULL):
755          */
756         Query      *subquery;           /* the sub-query */
757         bool            security_barrier;               /* is from security_barrier view? */
758
759         /*
760          * Fields valid for a join RTE (else NULL/zero):
761          *
762          * joinaliasvars is a list of (usually) Vars corresponding to the columns
763          * of the join result.  An alias Var referencing column K of the join
764          * result can be replaced by the K'th element of joinaliasvars --- but to
765          * simplify the task of reverse-listing aliases correctly, we do not do
766          * that until planning time.  In detail: an element of joinaliasvars can
767          * be a Var of one of the join's input relations, or such a Var with an
768          * implicit coercion to the join's output column type, or a COALESCE
769          * expression containing the two input column Vars (possibly coerced).
770          * Within a Query loaded from a stored rule, it is also possible for
771          * joinaliasvars items to be null pointers, which are placeholders for
772          * (necessarily unreferenced) columns dropped since the rule was made.
773          * Also, once planning begins, joinaliasvars items can be almost anything,
774          * as a result of subquery-flattening substitutions.
775          */
776         JoinType        jointype;               /* type of join */
777         List       *joinaliasvars;      /* list of alias-var expansions */
778
779         /*
780          * Fields valid for a function RTE (else NIL/zero):
781          *
782          * When funcordinality is true, the eref->colnames list includes an alias
783          * for the ordinality column.  The ordinality column is otherwise
784          * implicit, and must be accounted for "by hand" in places such as
785          * expandRTE().
786          */
787         List       *functions;          /* list of RangeTblFunction nodes */
788         bool            funcordinality; /* is this called WITH ORDINALITY? */
789
790         /*
791          * Fields valid for a values RTE (else NIL):
792          */
793         List       *values_lists;       /* list of expression lists */
794         List       *values_collations;          /* OID list of column collation OIDs */
795
796         /*
797          * Fields valid for a CTE RTE (else NULL/zero):
798          */
799         char       *ctename;            /* name of the WITH list item */
800         Index           ctelevelsup;    /* number of query levels up */
801         bool            self_reference; /* is this a recursive self-reference? */
802         List       *ctecoltypes;        /* OID list of column type OIDs */
803         List       *ctecoltypmods;      /* integer list of column typmods */
804         List       *ctecolcollations;           /* OID list of column collation OIDs */
805
806         /*
807          * Fields valid in all RTEs:
808          */
809         Alias      *alias;                      /* user-written alias clause, if any */
810         Alias      *eref;                       /* expanded reference names */
811         bool            lateral;                /* subquery, function, or values is LATERAL? */
812         bool            inh;                    /* inheritance requested? */
813         bool            inFromCl;               /* present in FROM clause? */
814         AclMode         requiredPerms;  /* bitmask of required access permissions */
815         Oid                     checkAsUser;    /* if valid, check access as this role */
816         Bitmapset  *selectedCols;       /* columns needing SELECT permission */
817         Bitmapset  *modifiedCols;       /* columns needing INSERT/UPDATE permission */
818         List       *securityQuals;      /* any security barrier quals to apply */
819 } RangeTblEntry;
820
821 /*
822  * RangeTblFunction -
823  *        RangeTblEntry subsidiary data for one function in a FUNCTION RTE.
824  *
825  * If the function had a column definition list (required for an
826  * otherwise-unspecified RECORD result), funccolnames lists the names given
827  * in the definition list, funccoltypes lists their declared column types,
828  * funccoltypmods lists their typmods, funccolcollations their collations.
829  * Otherwise, those fields are NIL.
830  *
831  * Notice we don't attempt to store info about the results of functions
832  * returning named composite types, because those can change from time to
833  * time.  We do however remember how many columns we thought the type had
834  * (including dropped columns!), so that we can successfully ignore any
835  * columns added after the query was parsed.
836  */
837 typedef struct RangeTblFunction
838 {
839         NodeTag         type;
840
841         Node       *funcexpr;           /* expression tree for func call */
842         int                     funccolcount;   /* number of columns it contributes to RTE */
843         /* These fields record the contents of a column definition list, if any: */
844         List       *funccolnames;       /* column names (list of String) */
845         List       *funccoltypes;       /* OID list of column type OIDs */
846         List       *funccoltypmods; /* integer list of column typmods */
847         List       *funccolcollations;          /* OID list of column collation OIDs */
848         /* This is set during planning for use by the executor: */
849         Bitmapset  *funcparams;         /* PARAM_EXEC Param IDs affecting this func */
850 } RangeTblFunction;
851
852 /*
853  * WithCheckOption -
854  *              representation of WITH CHECK OPTION checks to be applied to new tuples
855  *              when inserting/updating an auto-updatable view.
856  */
857 typedef struct WithCheckOption
858 {
859         NodeTag         type;
860         char       *viewname;           /* name of view that specified the WCO */
861         Node       *qual;                       /* constraint qual to check */
862         bool            cascaded;               /* true = WITH CASCADED CHECK OPTION */
863 } WithCheckOption;
864
865 /*
866  * SortGroupClause -
867  *              representation of ORDER BY, GROUP BY, PARTITION BY,
868  *              DISTINCT, DISTINCT ON items
869  *
870  * You might think that ORDER BY is only interested in defining ordering,
871  * and GROUP/DISTINCT are only interested in defining equality.  However,
872  * one way to implement grouping is to sort and then apply a "uniq"-like
873  * filter.  So it's also interesting to keep track of possible sort operators
874  * for GROUP/DISTINCT, and in particular to try to sort for the grouping
875  * in a way that will also yield a requested ORDER BY ordering.  So we need
876  * to be able to compare ORDER BY and GROUP/DISTINCT lists, which motivates
877  * the decision to give them the same representation.
878  *
879  * tleSortGroupRef must match ressortgroupref of exactly one entry of the
880  *              query's targetlist; that is the expression to be sorted or grouped by.
881  * eqop is the OID of the equality operator.
882  * sortop is the OID of the ordering operator (a "<" or ">" operator),
883  *              or InvalidOid if not available.
884  * nulls_first means about what you'd expect.  If sortop is InvalidOid
885  *              then nulls_first is meaningless and should be set to false.
886  * hashable is TRUE if eqop is hashable (note this condition also depends
887  *              on the datatype of the input expression).
888  *
889  * In an ORDER BY item, all fields must be valid.  (The eqop isn't essential
890  * here, but it's cheap to get it along with the sortop, and requiring it
891  * to be valid eases comparisons to grouping items.)  Note that this isn't
892  * actually enough information to determine an ordering: if the sortop is
893  * collation-sensitive, a collation OID is needed too.  We don't store the
894  * collation in SortGroupClause because it's not available at the time the
895  * parser builds the SortGroupClause; instead, consult the exposed collation
896  * of the referenced targetlist expression to find out what it is.
897  *
898  * In a grouping item, eqop must be valid.  If the eqop is a btree equality
899  * operator, then sortop should be set to a compatible ordering operator.
900  * We prefer to set eqop/sortop/nulls_first to match any ORDER BY item that
901  * the query presents for the same tlist item.  If there is none, we just
902  * use the default ordering op for the datatype.
903  *
904  * If the tlist item's type has a hash opclass but no btree opclass, then
905  * we will set eqop to the hash equality operator, sortop to InvalidOid,
906  * and nulls_first to false.  A grouping item of this kind can only be
907  * implemented by hashing, and of course it'll never match an ORDER BY item.
908  *
909  * The hashable flag is provided since we generally have the requisite
910  * information readily available when the SortGroupClause is constructed,
911  * and it's relatively expensive to get it again later.  Note there is no
912  * need for a "sortable" flag since OidIsValid(sortop) serves the purpose.
913  *
914  * A query might have both ORDER BY and DISTINCT (or DISTINCT ON) clauses.
915  * In SELECT DISTINCT, the distinctClause list is as long or longer than the
916  * sortClause list, while in SELECT DISTINCT ON it's typically shorter.
917  * The two lists must match up to the end of the shorter one --- the parser
918  * rearranges the distinctClause if necessary to make this true.  (This
919  * restriction ensures that only one sort step is needed to both satisfy the
920  * ORDER BY and set up for the Unique step.  This is semantically necessary
921  * for DISTINCT ON, and presents no real drawback for DISTINCT.)
922  */
923 typedef struct SortGroupClause
924 {
925         NodeTag         type;
926         Index           tleSortGroupRef;        /* reference into targetlist */
927         Oid                     eqop;                   /* the equality operator ('=' op) */
928         Oid                     sortop;                 /* the ordering operator ('<' op), or 0 */
929         bool            nulls_first;    /* do NULLs come before normal values? */
930         bool            hashable;               /* can eqop be implemented by hashing? */
931 } SortGroupClause;
932
933 /*
934  * WindowClause -
935  *              transformed representation of WINDOW and OVER clauses
936  *
937  * A parsed Query's windowClause list contains these structs.  "name" is set
938  * if the clause originally came from WINDOW, and is NULL if it originally
939  * was an OVER clause (but note that we collapse out duplicate OVERs).
940  * partitionClause and orderClause are lists of SortGroupClause structs.
941  * winref is an ID number referenced by WindowFunc nodes; it must be unique
942  * among the members of a Query's windowClause list.
943  * When refname isn't null, the partitionClause is always copied from there;
944  * the orderClause might or might not be copied (see copiedOrder); the framing
945  * options are never copied, per spec.
946  */
947 typedef struct WindowClause
948 {
949         NodeTag         type;
950         char       *name;                       /* window name (NULL in an OVER clause) */
951         char       *refname;            /* referenced window name, if any */
952         List       *partitionClause;    /* PARTITION BY list */
953         List       *orderClause;        /* ORDER BY list */
954         int                     frameOptions;   /* frame_clause options, see WindowDef */
955         Node       *startOffset;        /* expression for starting bound, if any */
956         Node       *endOffset;          /* expression for ending bound, if any */
957         Index           winref;                 /* ID referenced by window functions */
958         bool            copiedOrder;    /* did we copy orderClause from refname? */
959 } WindowClause;
960
961 /*
962  * RowMarkClause -
963  *         parser output representation of FOR [KEY] UPDATE/SHARE clauses
964  *
965  * Query.rowMarks contains a separate RowMarkClause node for each relation
966  * identified as a FOR [KEY] UPDATE/SHARE target.  If one of these clauses
967  * is applied to a subquery, we generate RowMarkClauses for all normal and
968  * subquery rels in the subquery, but they are marked pushedDown = true to
969  * distinguish them from clauses that were explicitly written at this query
970  * level.  Also, Query.hasForUpdate tells whether there were explicit FOR
971  * UPDATE/SHARE/KEY SHARE clauses in the current query level.
972  */
973 typedef struct RowMarkClause
974 {
975         NodeTag         type;
976         Index           rti;                    /* range table index of target relation */
977         LockClauseStrength strength;
978         bool            noWait;                 /* NOWAIT option */
979         bool            pushedDown;             /* pushed down from higher query level? */
980 } RowMarkClause;
981
982 /*
983  * WithClause -
984  *         representation of WITH clause
985  *
986  * Note: WithClause does not propagate into the Query representation;
987  * but CommonTableExpr does.
988  */
989 typedef struct WithClause
990 {
991         NodeTag         type;
992         List       *ctes;                       /* list of CommonTableExprs */
993         bool            recursive;              /* true = WITH RECURSIVE */
994         int                     location;               /* token location, or -1 if unknown */
995 } WithClause;
996
997 /*
998  * CommonTableExpr -
999  *         representation of WITH list element
1000  *
1001  * We don't currently support the SEARCH or CYCLE clause.
1002  */
1003 typedef struct CommonTableExpr
1004 {
1005         NodeTag         type;
1006         char       *ctename;            /* query name (never qualified) */
1007         List       *aliascolnames;      /* optional list of column names */
1008         /* SelectStmt/InsertStmt/etc before parse analysis, Query afterwards: */
1009         Node       *ctequery;           /* the CTE's subquery */
1010         int                     location;               /* token location, or -1 if unknown */
1011         /* These fields are set during parse analysis: */
1012         bool            cterecursive;   /* is this CTE actually recursive? */
1013         int                     cterefcount;    /* number of RTEs referencing this CTE
1014                                                                  * (excluding internal self-references) */
1015         List       *ctecolnames;        /* list of output column names */
1016         List       *ctecoltypes;        /* OID list of output column type OIDs */
1017         List       *ctecoltypmods;      /* integer list of output column typmods */
1018         List       *ctecolcollations;           /* OID list of column collation OIDs */
1019 } CommonTableExpr;
1020
1021 /* Convenience macro to get the output tlist of a CTE's query */
1022 #define GetCTETargetList(cte) \
1023         (AssertMacro(IsA((cte)->ctequery, Query)), \
1024          ((Query *) (cte)->ctequery)->commandType == CMD_SELECT ? \
1025          ((Query *) (cte)->ctequery)->targetList : \
1026          ((Query *) (cte)->ctequery)->returningList)
1027
1028
1029 /*****************************************************************************
1030  *              Optimizable Statements
1031  *****************************************************************************/
1032
1033 /* ----------------------
1034  *              Insert Statement
1035  *
1036  * The source expression is represented by SelectStmt for both the
1037  * SELECT and VALUES cases.  If selectStmt is NULL, then the query
1038  * is INSERT ... DEFAULT VALUES.
1039  * ----------------------
1040  */
1041 typedef struct InsertStmt
1042 {
1043         NodeTag         type;
1044         RangeVar   *relation;           /* relation to insert into */
1045         List       *cols;                       /* optional: names of the target columns */
1046         Node       *selectStmt;         /* the source SELECT/VALUES, or NULL */
1047         List       *returningList;      /* list of expressions to return */
1048         WithClause *withClause;         /* WITH clause */
1049 } InsertStmt;
1050
1051 /* ----------------------
1052  *              Delete Statement
1053  * ----------------------
1054  */
1055 typedef struct DeleteStmt
1056 {
1057         NodeTag         type;
1058         RangeVar   *relation;           /* relation to delete from */
1059         List       *usingClause;        /* optional using clause for more tables */
1060         Node       *whereClause;        /* qualifications */
1061         List       *returningList;      /* list of expressions to return */
1062         WithClause *withClause;         /* WITH clause */
1063 } DeleteStmt;
1064
1065 /* ----------------------
1066  *              Update Statement
1067  * ----------------------
1068  */
1069 typedef struct UpdateStmt
1070 {
1071         NodeTag         type;
1072         RangeVar   *relation;           /* relation to update */
1073         List       *targetList;         /* the target list (of ResTarget) */
1074         Node       *whereClause;        /* qualifications */
1075         List       *fromClause;         /* optional from clause for more tables */
1076         List       *returningList;      /* list of expressions to return */
1077         WithClause *withClause;         /* WITH clause */
1078 } UpdateStmt;
1079
1080 /* ----------------------
1081  *              Select Statement
1082  *
1083  * A "simple" SELECT is represented in the output of gram.y by a single
1084  * SelectStmt node; so is a VALUES construct.  A query containing set
1085  * operators (UNION, INTERSECT, EXCEPT) is represented by a tree of SelectStmt
1086  * nodes, in which the leaf nodes are component SELECTs and the internal nodes
1087  * represent UNION, INTERSECT, or EXCEPT operators.  Using the same node
1088  * type for both leaf and internal nodes allows gram.y to stick ORDER BY,
1089  * LIMIT, etc, clause values into a SELECT statement without worrying
1090  * whether it is a simple or compound SELECT.
1091  * ----------------------
1092  */
1093 typedef enum SetOperation
1094 {
1095         SETOP_NONE = 0,
1096         SETOP_UNION,
1097         SETOP_INTERSECT,
1098         SETOP_EXCEPT
1099 } SetOperation;
1100
1101 typedef struct SelectStmt
1102 {
1103         NodeTag         type;
1104
1105         /*
1106          * These fields are used only in "leaf" SelectStmts.
1107          */
1108         List       *distinctClause; /* NULL, list of DISTINCT ON exprs, or
1109                                                                  * lcons(NIL,NIL) for all (SELECT DISTINCT) */
1110         IntoClause *intoClause;         /* target for SELECT INTO */
1111         List       *targetList;         /* the target list (of ResTarget) */
1112         List       *fromClause;         /* the FROM clause */
1113         Node       *whereClause;        /* WHERE qualification */
1114         List       *groupClause;        /* GROUP BY clauses */
1115         Node       *havingClause;       /* HAVING conditional-expression */
1116         List       *windowClause;       /* WINDOW window_name AS (...), ... */
1117
1118         /*
1119          * In a "leaf" node representing a VALUES list, the above fields are all
1120          * null, and instead this field is set.  Note that the elements of the
1121          * sublists are just expressions, without ResTarget decoration. Also note
1122          * that a list element can be DEFAULT (represented as a SetToDefault
1123          * node), regardless of the context of the VALUES list. It's up to parse
1124          * analysis to reject that where not valid.
1125          */
1126         List       *valuesLists;        /* untransformed list of expression lists */
1127
1128         /*
1129          * These fields are used in both "leaf" SelectStmts and upper-level
1130          * SelectStmts.
1131          */
1132         List       *sortClause;         /* sort clause (a list of SortBy's) */
1133         Node       *limitOffset;        /* # of result tuples to skip */
1134         Node       *limitCount;         /* # of result tuples to return */
1135         List       *lockingClause;      /* FOR UPDATE (list of LockingClause's) */
1136         WithClause *withClause;         /* WITH clause */
1137
1138         /*
1139          * These fields are used only in upper-level SelectStmts.
1140          */
1141         SetOperation op;                        /* type of set op */
1142         bool            all;                    /* ALL specified? */
1143         struct SelectStmt *larg;        /* left child */
1144         struct SelectStmt *rarg;        /* right child */
1145         /* Eventually add fields for CORRESPONDING spec here */
1146 } SelectStmt;
1147
1148
1149 /* ----------------------
1150  *              Set Operation node for post-analysis query trees
1151  *
1152  * After parse analysis, a SELECT with set operations is represented by a
1153  * top-level Query node containing the leaf SELECTs as subqueries in its
1154  * range table.  Its setOperations field shows the tree of set operations,
1155  * with leaf SelectStmt nodes replaced by RangeTblRef nodes, and internal
1156  * nodes replaced by SetOperationStmt nodes.  Information about the output
1157  * column types is added, too.  (Note that the child nodes do not necessarily
1158  * produce these types directly, but we've checked that their output types
1159  * can be coerced to the output column type.)  Also, if it's not UNION ALL,
1160  * information about the types' sort/group semantics is provided in the form
1161  * of a SortGroupClause list (same representation as, eg, DISTINCT).
1162  * The resolved common column collations are provided too; but note that if
1163  * it's not UNION ALL, it's okay for a column to not have a common collation,
1164  * so a member of the colCollations list could be InvalidOid even though the
1165  * column has a collatable type.
1166  * ----------------------
1167  */
1168 typedef struct SetOperationStmt
1169 {
1170         NodeTag         type;
1171         SetOperation op;                        /* type of set op */
1172         bool            all;                    /* ALL specified? */
1173         Node       *larg;                       /* left child */
1174         Node       *rarg;                       /* right child */
1175         /* Eventually add fields for CORRESPONDING spec here */
1176
1177         /* Fields derived during parse analysis: */
1178         List       *colTypes;           /* OID list of output column type OIDs */
1179         List       *colTypmods;         /* integer list of output column typmods */
1180         List       *colCollations;      /* OID list of output column collation OIDs */
1181         List       *groupClauses;       /* a list of SortGroupClause's */
1182         /* groupClauses is NIL if UNION ALL, but must be set otherwise */
1183 } SetOperationStmt;
1184
1185
1186 /*****************************************************************************
1187  *              Other Statements (no optimizations required)
1188  *
1189  *              These are not touched by parser/analyze.c except to put them into
1190  *              the utilityStmt field of a Query.  This is eventually passed to
1191  *              ProcessUtility (by-passing rewriting and planning).  Some of the
1192  *              statements do need attention from parse analysis, and this is
1193  *              done by routines in parser/parse_utilcmd.c after ProcessUtility
1194  *              receives the command for execution.
1195  *****************************************************************************/
1196
1197 /*
1198  * When a command can act on several kinds of objects with only one
1199  * parse structure required, use these constants to designate the
1200  * object type.  Note that commands typically don't support all the types.
1201  */
1202
1203 typedef enum ObjectType
1204 {
1205         OBJECT_AGGREGATE,
1206         OBJECT_ATTRIBUTE,                       /* type's attribute, when distinct from column */
1207         OBJECT_CAST,
1208         OBJECT_COLUMN,
1209         OBJECT_CONSTRAINT,
1210         OBJECT_COLLATION,
1211         OBJECT_CONVERSION,
1212         OBJECT_DATABASE,
1213         OBJECT_DOMAIN,
1214         OBJECT_EVENT_TRIGGER,
1215         OBJECT_EXTENSION,
1216         OBJECT_FDW,
1217         OBJECT_FOREIGN_SERVER,
1218         OBJECT_FOREIGN_TABLE,
1219         OBJECT_FUNCTION,
1220         OBJECT_INDEX,
1221         OBJECT_LANGUAGE,
1222         OBJECT_LARGEOBJECT,
1223         OBJECT_MATVIEW,
1224         OBJECT_OPCLASS,
1225         OBJECT_OPERATOR,
1226         OBJECT_OPFAMILY,
1227         OBJECT_ROLE,
1228         OBJECT_RULE,
1229         OBJECT_SCHEMA,
1230         OBJECT_SEQUENCE,
1231         OBJECT_TABLE,
1232         OBJECT_TABLESPACE,
1233         OBJECT_TRIGGER,
1234         OBJECT_TSCONFIGURATION,
1235         OBJECT_TSDICTIONARY,
1236         OBJECT_TSPARSER,
1237         OBJECT_TSTEMPLATE,
1238         OBJECT_TYPE,
1239         OBJECT_VIEW
1240 } ObjectType;
1241
1242 /* ----------------------
1243  *              Create Schema Statement
1244  *
1245  * NOTE: the schemaElts list contains raw parsetrees for component statements
1246  * of the schema, such as CREATE TABLE, GRANT, etc.  These are analyzed and
1247  * executed after the schema itself is created.
1248  * ----------------------
1249  */
1250 typedef struct CreateSchemaStmt
1251 {
1252         NodeTag         type;
1253         char       *schemaname;         /* the name of the schema to create */
1254         char       *authid;                     /* the owner of the created schema */
1255         List       *schemaElts;         /* schema components (list of parsenodes) */
1256         bool            if_not_exists;  /* just do nothing if schema already exists? */
1257 } CreateSchemaStmt;
1258
1259 typedef enum DropBehavior
1260 {
1261         DROP_RESTRICT,                          /* drop fails if any dependent objects */
1262         DROP_CASCADE                            /* remove dependent objects too */
1263 } DropBehavior;
1264
1265 /* ----------------------
1266  *      Alter Table
1267  * ----------------------
1268  */
1269 typedef struct AlterTableStmt
1270 {
1271         NodeTag         type;
1272         RangeVar   *relation;           /* table to work on */
1273         List       *cmds;                       /* list of subcommands */
1274         ObjectType      relkind;                /* type of object */
1275         bool            missing_ok;             /* skip error if table missing */
1276 } AlterTableStmt;
1277
1278 typedef enum AlterTableType
1279 {
1280         AT_AddColumn,                           /* add column */
1281         AT_AddColumnRecurse,            /* internal to commands/tablecmds.c */
1282         AT_AddColumnToView,                     /* implicitly via CREATE OR REPLACE VIEW */
1283         AT_ColumnDefault,                       /* alter column default */
1284         AT_DropNotNull,                         /* alter column drop not null */
1285         AT_SetNotNull,                          /* alter column set not null */
1286         AT_SetStatistics,                       /* alter column set statistics */
1287         AT_SetOptions,                          /* alter column set ( options ) */
1288         AT_ResetOptions,                        /* alter column reset ( options ) */
1289         AT_SetStorage,                          /* alter column set storage */
1290         AT_DropColumn,                          /* drop column */
1291         AT_DropColumnRecurse,           /* internal to commands/tablecmds.c */
1292         AT_AddIndex,                            /* add index */
1293         AT_ReAddIndex,                          /* internal to commands/tablecmds.c */
1294         AT_AddConstraint,                       /* add constraint */
1295         AT_AddConstraintRecurse,        /* internal to commands/tablecmds.c */
1296         AT_ReAddConstraint,                     /* internal to commands/tablecmds.c */
1297         AT_AlterConstraint,                     /* alter constraint */
1298         AT_ValidateConstraint,          /* validate constraint */
1299         AT_ValidateConstraintRecurse,           /* internal to commands/tablecmds.c */
1300         AT_ProcessedConstraint,         /* pre-processed add constraint (local in
1301                                                                  * parser/parse_utilcmd.c) */
1302         AT_AddIndexConstraint,          /* add constraint using existing index */
1303         AT_DropConstraint,                      /* drop constraint */
1304         AT_DropConstraintRecurse,       /* internal to commands/tablecmds.c */
1305         AT_AlterColumnType,                     /* alter column type */
1306         AT_AlterColumnGenericOptions,           /* alter column OPTIONS (...) */
1307         AT_ChangeOwner,                         /* change owner */
1308         AT_ClusterOn,                           /* CLUSTER ON */
1309         AT_DropCluster,                         /* SET WITHOUT CLUSTER */
1310         AT_SetLogged,                           /* SET LOGGED */
1311         AT_SetUnLogged,                         /* SET UNLOGGED */
1312         AT_AddOids,                                     /* SET WITH OIDS */
1313         AT_AddOidsRecurse,                      /* internal to commands/tablecmds.c */
1314         AT_DropOids,                            /* SET WITHOUT OIDS */
1315         AT_SetTableSpace,                       /* SET TABLESPACE */
1316         AT_SetRelOptions,                       /* SET (...) -- AM specific parameters */
1317         AT_ResetRelOptions,                     /* RESET (...) -- AM specific parameters */
1318         AT_ReplaceRelOptions,           /* replace reloption list in its entirety */
1319         AT_EnableTrig,                          /* ENABLE TRIGGER name */
1320         AT_EnableAlwaysTrig,            /* ENABLE ALWAYS TRIGGER name */
1321         AT_EnableReplicaTrig,           /* ENABLE REPLICA TRIGGER name */
1322         AT_DisableTrig,                         /* DISABLE TRIGGER name */
1323         AT_EnableTrigAll,                       /* ENABLE TRIGGER ALL */
1324         AT_DisableTrigAll,                      /* DISABLE TRIGGER ALL */
1325         AT_EnableTrigUser,                      /* ENABLE TRIGGER USER */
1326         AT_DisableTrigUser,                     /* DISABLE TRIGGER USER */
1327         AT_EnableRule,                          /* ENABLE RULE name */
1328         AT_EnableAlwaysRule,            /* ENABLE ALWAYS RULE name */
1329         AT_EnableReplicaRule,           /* ENABLE REPLICA RULE name */
1330         AT_DisableRule,                         /* DISABLE RULE name */
1331         AT_AddInherit,                          /* INHERIT parent */
1332         AT_DropInherit,                         /* NO INHERIT parent */
1333         AT_AddOf,                                       /* OF <type_name> */
1334         AT_DropOf,                                      /* NOT OF */
1335         AT_ReplicaIdentity,                     /* REPLICA IDENTITY */
1336         AT_GenericOptions                       /* OPTIONS (...) */
1337 } AlterTableType;
1338
1339 typedef struct ReplicaIdentityStmt
1340 {
1341         NodeTag         type;
1342         char            identity_type;
1343         char       *name;
1344 } ReplicaIdentityStmt;
1345
1346 typedef struct AlterTableCmd    /* one subcommand of an ALTER TABLE */
1347 {
1348         NodeTag         type;
1349         AlterTableType subtype;         /* Type of table alteration to apply */
1350         char       *name;                       /* column, constraint, or trigger to act on,
1351                                                                  * or new owner or tablespace */
1352         Node       *def;                        /* definition of new column, index,
1353                                                                  * constraint, or parent table */
1354         DropBehavior behavior;          /* RESTRICT or CASCADE for DROP cases */
1355         bool            missing_ok;             /* skip error if missing? */
1356 } AlterTableCmd;
1357
1358
1359 /* ----------------------
1360  *      Alter Domain
1361  *
1362  * The fields are used in different ways by the different variants of
1363  * this command.
1364  * ----------------------
1365  */
1366 typedef struct AlterDomainStmt
1367 {
1368         NodeTag         type;
1369         char            subtype;                /*------------
1370                                                                  *      T = alter column default
1371                                                                  *      N = alter column drop not null
1372                                                                  *      O = alter column set not null
1373                                                                  *      C = add constraint
1374                                                                  *      X = drop constraint
1375                                                                  *------------
1376                                                                  */
1377         List       *typeName;           /* domain to work on */
1378         char       *name;                       /* column or constraint name to act on */
1379         Node       *def;                        /* definition of default or constraint */
1380         DropBehavior behavior;          /* RESTRICT or CASCADE for DROP cases */
1381         bool            missing_ok;             /* skip error if missing? */
1382 } AlterDomainStmt;
1383
1384
1385 /* ----------------------
1386  *              Grant|Revoke Statement
1387  * ----------------------
1388  */
1389 typedef enum GrantTargetType
1390 {
1391         ACL_TARGET_OBJECT,                      /* grant on specific named object(s) */
1392         ACL_TARGET_ALL_IN_SCHEMA,       /* grant on all objects in given schema(s) */
1393         ACL_TARGET_DEFAULTS                     /* ALTER DEFAULT PRIVILEGES */
1394 } GrantTargetType;
1395
1396 typedef enum GrantObjectType
1397 {
1398         ACL_OBJECT_COLUMN,                      /* column */
1399         ACL_OBJECT_RELATION,            /* table, view */
1400         ACL_OBJECT_SEQUENCE,            /* sequence */
1401         ACL_OBJECT_DATABASE,            /* database */
1402         ACL_OBJECT_DOMAIN,                      /* domain */
1403         ACL_OBJECT_FDW,                         /* foreign-data wrapper */
1404         ACL_OBJECT_FOREIGN_SERVER,      /* foreign server */
1405         ACL_OBJECT_FUNCTION,            /* function */
1406         ACL_OBJECT_LANGUAGE,            /* procedural language */
1407         ACL_OBJECT_LARGEOBJECT,         /* largeobject */
1408         ACL_OBJECT_NAMESPACE,           /* namespace */
1409         ACL_OBJECT_TABLESPACE,          /* tablespace */
1410         ACL_OBJECT_TYPE                         /* type */
1411 } GrantObjectType;
1412
1413 typedef struct GrantStmt
1414 {
1415         NodeTag         type;
1416         bool            is_grant;               /* true = GRANT, false = REVOKE */
1417         GrantTargetType targtype;       /* type of the grant target */
1418         GrantObjectType objtype;        /* kind of object being operated on */
1419         List       *objects;            /* list of RangeVar nodes, FuncWithArgs nodes,
1420                                                                  * or plain names (as Value strings) */
1421         List       *privileges;         /* list of AccessPriv nodes */
1422         /* privileges == NIL denotes ALL PRIVILEGES */
1423         List       *grantees;           /* list of PrivGrantee nodes */
1424         bool            grant_option;   /* grant or revoke grant option */
1425         DropBehavior behavior;          /* drop behavior (for REVOKE) */
1426 } GrantStmt;
1427
1428 typedef struct PrivGrantee
1429 {
1430         NodeTag         type;
1431         char       *rolname;            /* if NULL then PUBLIC */
1432 } PrivGrantee;
1433
1434 /*
1435  * Note: FuncWithArgs carries only the types of the input parameters of the
1436  * function.  So it is sufficient to identify an existing function, but it
1437  * is not enough info to define a function nor to call it.
1438  */
1439 typedef struct FuncWithArgs
1440 {
1441         NodeTag         type;
1442         List       *funcname;           /* qualified name of function */
1443         List       *funcargs;           /* list of Typename nodes */
1444 } FuncWithArgs;
1445
1446 /*
1447  * An access privilege, with optional list of column names
1448  * priv_name == NULL denotes ALL PRIVILEGES (only used with a column list)
1449  * cols == NIL denotes "all columns"
1450  * Note that simple "ALL PRIVILEGES" is represented as a NIL list, not
1451  * an AccessPriv with both fields null.
1452  */
1453 typedef struct AccessPriv
1454 {
1455         NodeTag         type;
1456         char       *priv_name;          /* string name of privilege */
1457         List       *cols;                       /* list of Value strings */
1458 } AccessPriv;
1459
1460 /* ----------------------
1461  *              Grant/Revoke Role Statement
1462  *
1463  * Note: because of the parsing ambiguity with the GRANT <privileges>
1464  * statement, granted_roles is a list of AccessPriv; the execution code
1465  * should complain if any column lists appear.  grantee_roles is a list
1466  * of role names, as Value strings.
1467  * ----------------------
1468  */
1469 typedef struct GrantRoleStmt
1470 {
1471         NodeTag         type;
1472         List       *granted_roles;      /* list of roles to be granted/revoked */
1473         List       *grantee_roles;      /* list of member roles to add/delete */
1474         bool            is_grant;               /* true = GRANT, false = REVOKE */
1475         bool            admin_opt;              /* with admin option */
1476         char       *grantor;            /* set grantor to other than current role */
1477         DropBehavior behavior;          /* drop behavior (for REVOKE) */
1478 } GrantRoleStmt;
1479
1480 /* ----------------------
1481  *      Alter Default Privileges Statement
1482  * ----------------------
1483  */
1484 typedef struct AlterDefaultPrivilegesStmt
1485 {
1486         NodeTag         type;
1487         List       *options;            /* list of DefElem */
1488         GrantStmt  *action;                     /* GRANT/REVOKE action (with objects=NIL) */
1489 } AlterDefaultPrivilegesStmt;
1490
1491 /* ----------------------
1492  *              Copy Statement
1493  *
1494  * We support "COPY relation FROM file", "COPY relation TO file", and
1495  * "COPY (query) TO file".  In any given CopyStmt, exactly one of "relation"
1496  * and "query" must be non-NULL.
1497  * ----------------------
1498  */
1499 typedef struct CopyStmt
1500 {
1501         NodeTag         type;
1502         RangeVar   *relation;           /* the relation to copy */
1503         Node       *query;                      /* the SELECT query to copy */
1504         List       *attlist;            /* List of column names (as Strings), or NIL
1505                                                                  * for all columns */
1506         bool            is_from;                /* TO or FROM */
1507         bool            is_program;             /* is 'filename' a program to popen? */
1508         char       *filename;           /* filename, or NULL for STDIN/STDOUT */
1509         List       *options;            /* List of DefElem nodes */
1510 } CopyStmt;
1511
1512 /* ----------------------
1513  * SET Statement (includes RESET)
1514  *
1515  * "SET var TO DEFAULT" and "RESET var" are semantically equivalent, but we
1516  * preserve the distinction in VariableSetKind for CreateCommandTag().
1517  * ----------------------
1518  */
1519 typedef enum
1520 {
1521         VAR_SET_VALUE,                          /* SET var = value */
1522         VAR_SET_DEFAULT,                        /* SET var TO DEFAULT */
1523         VAR_SET_CURRENT,                        /* SET var FROM CURRENT */
1524         VAR_SET_MULTI,                          /* special case for SET TRANSACTION ... */
1525         VAR_RESET,                                      /* RESET var */
1526         VAR_RESET_ALL                           /* RESET ALL */
1527 } VariableSetKind;
1528
1529 typedef struct VariableSetStmt
1530 {
1531         NodeTag         type;
1532         VariableSetKind kind;
1533         char       *name;                       /* variable to be set */
1534         List       *args;                       /* List of A_Const nodes */
1535         bool            is_local;               /* SET LOCAL? */
1536 } VariableSetStmt;
1537
1538 /* ----------------------
1539  * Show Statement
1540  * ----------------------
1541  */
1542 typedef struct VariableShowStmt
1543 {
1544         NodeTag         type;
1545         char       *name;
1546 } VariableShowStmt;
1547
1548 /* ----------------------
1549  *              Create Table Statement
1550  *
1551  * NOTE: in the raw gram.y output, ColumnDef and Constraint nodes are
1552  * intermixed in tableElts, and constraints is NIL.  After parse analysis,
1553  * tableElts contains just ColumnDefs, and constraints contains just
1554  * Constraint nodes (in fact, only CONSTR_CHECK nodes, in the present
1555  * implementation).
1556  * ----------------------
1557  */
1558
1559 typedef struct CreateStmt
1560 {
1561         NodeTag         type;
1562         RangeVar   *relation;           /* relation to create */
1563         List       *tableElts;          /* column definitions (list of ColumnDef) */
1564         List       *inhRelations;       /* relations to inherit from (list of
1565                                                                  * inhRelation) */
1566         TypeName   *ofTypename;         /* OF typename */
1567         List       *constraints;        /* constraints (list of Constraint nodes) */
1568         List       *options;            /* options from WITH clause */
1569         OnCommitAction oncommit;        /* what do we do at COMMIT? */
1570         char       *tablespacename; /* table space to use, or NULL */
1571         bool            if_not_exists;  /* just do nothing if it already exists? */
1572 } CreateStmt;
1573
1574 /* ----------
1575  * Definitions for constraints in CreateStmt
1576  *
1577  * Note that column defaults are treated as a type of constraint,
1578  * even though that's a bit odd semantically.
1579  *
1580  * For constraints that use expressions (CONSTR_CHECK, CONSTR_DEFAULT)
1581  * we may have the expression in either "raw" form (an untransformed
1582  * parse tree) or "cooked" form (the nodeToString representation of
1583  * an executable expression tree), depending on how this Constraint
1584  * node was created (by parsing, or by inheritance from an existing
1585  * relation).  We should never have both in the same node!
1586  *
1587  * FKCONSTR_ACTION_xxx values are stored into pg_constraint.confupdtype
1588  * and pg_constraint.confdeltype columns; FKCONSTR_MATCH_xxx values are
1589  * stored into pg_constraint.confmatchtype.  Changing the code values may
1590  * require an initdb!
1591  *
1592  * If skip_validation is true then we skip checking that the existing rows
1593  * in the table satisfy the constraint, and just install the catalog entries
1594  * for the constraint.  A new FK constraint is marked as valid iff
1595  * initially_valid is true.  (Usually skip_validation and initially_valid
1596  * are inverses, but we can set both true if the table is known empty.)
1597  *
1598  * Constraint attributes (DEFERRABLE etc) are initially represented as
1599  * separate Constraint nodes for simplicity of parsing.  parse_utilcmd.c makes
1600  * a pass through the constraints list to insert the info into the appropriate
1601  * Constraint node.
1602  * ----------
1603  */
1604
1605 typedef enum ConstrType                 /* types of constraints */
1606 {
1607         CONSTR_NULL,                            /* not standard SQL, but a lot of people
1608                                                                  * expect it */
1609         CONSTR_NOTNULL,
1610         CONSTR_DEFAULT,
1611         CONSTR_CHECK,
1612         CONSTR_PRIMARY,
1613         CONSTR_UNIQUE,
1614         CONSTR_EXCLUSION,
1615         CONSTR_FOREIGN,
1616         CONSTR_ATTR_DEFERRABLE,         /* attributes for previous constraint node */
1617         CONSTR_ATTR_NOT_DEFERRABLE,
1618         CONSTR_ATTR_DEFERRED,
1619         CONSTR_ATTR_IMMEDIATE
1620 } ConstrType;
1621
1622 /* Foreign key action codes */
1623 #define FKCONSTR_ACTION_NOACTION        'a'
1624 #define FKCONSTR_ACTION_RESTRICT        'r'
1625 #define FKCONSTR_ACTION_CASCADE         'c'
1626 #define FKCONSTR_ACTION_SETNULL         'n'
1627 #define FKCONSTR_ACTION_SETDEFAULT      'd'
1628
1629 /* Foreign key matchtype codes */
1630 #define FKCONSTR_MATCH_FULL                     'f'
1631 #define FKCONSTR_MATCH_PARTIAL          'p'
1632 #define FKCONSTR_MATCH_SIMPLE           's'
1633
1634 typedef struct Constraint
1635 {
1636         NodeTag         type;
1637         ConstrType      contype;                /* see above */
1638
1639         /* Fields used for most/all constraint types: */
1640         char       *conname;            /* Constraint name, or NULL if unnamed */
1641         bool            deferrable;             /* DEFERRABLE? */
1642         bool            initdeferred;   /* INITIALLY DEFERRED? */
1643         int                     location;               /* token location, or -1 if unknown */
1644
1645         /* Fields used for constraints with expressions (CHECK and DEFAULT): */
1646         bool            is_no_inherit;  /* is constraint non-inheritable? */
1647         Node       *raw_expr;           /* expr, as untransformed parse tree */
1648         char       *cooked_expr;        /* expr, as nodeToString representation */
1649
1650         /* Fields used for unique constraints (UNIQUE and PRIMARY KEY): */
1651         List       *keys;                       /* String nodes naming referenced column(s) */
1652
1653         /* Fields used for EXCLUSION constraints: */
1654         List       *exclusions;         /* list of (IndexElem, operator name) pairs */
1655
1656         /* Fields used for index constraints (UNIQUE, PRIMARY KEY, EXCLUSION): */
1657         List       *options;            /* options from WITH clause */
1658         char       *indexname;          /* existing index to use; otherwise NULL */
1659         char       *indexspace;         /* index tablespace; NULL for default */
1660         /* These could be, but currently are not, used for UNIQUE/PKEY: */
1661         char       *access_method;      /* index access method; NULL for default */
1662         Node       *where_clause;       /* partial index predicate */
1663
1664         /* Fields used for FOREIGN KEY constraints: */
1665         RangeVar   *pktable;            /* Primary key table */
1666         List       *fk_attrs;           /* Attributes of foreign key */
1667         List       *pk_attrs;           /* Corresponding attrs in PK table */
1668         char            fk_matchtype;   /* FULL, PARTIAL, SIMPLE */
1669         char            fk_upd_action;  /* ON UPDATE action */
1670         char            fk_del_action;  /* ON DELETE action */
1671         List       *old_conpfeqop;      /* pg_constraint.conpfeqop of my former self */
1672         Oid                     old_pktable_oid;        /* pg_constraint.confrelid of my former self */
1673
1674         /* Fields used for constraints that allow a NOT VALID specification */
1675         bool            skip_validation;        /* skip validation of existing rows? */
1676         bool            initially_valid;        /* mark the new constraint as valid? */
1677 } Constraint;
1678
1679 /* ----------------------
1680  *              Create/Drop Table Space Statements
1681  * ----------------------
1682  */
1683
1684 typedef struct CreateTableSpaceStmt
1685 {
1686         NodeTag         type;
1687         char       *tablespacename;
1688         char       *owner;
1689         char       *location;
1690         List       *options;
1691 } CreateTableSpaceStmt;
1692
1693 typedef struct DropTableSpaceStmt
1694 {
1695         NodeTag         type;
1696         char       *tablespacename;
1697         bool            missing_ok;             /* skip error if missing? */
1698 } DropTableSpaceStmt;
1699
1700 typedef struct AlterTableSpaceOptionsStmt
1701 {
1702         NodeTag         type;
1703         char       *tablespacename;
1704         List       *options;
1705         bool            isReset;
1706 } AlterTableSpaceOptionsStmt;
1707
1708 typedef struct AlterTableMoveAllStmt
1709 {
1710         NodeTag         type;
1711         char       *orig_tablespacename;
1712         ObjectType      objtype;                /* Object type to move */
1713         List       *roles;                      /* List of roles to move objects of */
1714         char       *new_tablespacename;
1715         bool            nowait;
1716 } AlterTableMoveAllStmt;
1717
1718 /* ----------------------
1719  *              Create/Alter Extension Statements
1720  * ----------------------
1721  */
1722
1723 typedef struct CreateExtensionStmt
1724 {
1725         NodeTag         type;
1726         char       *extname;
1727         bool            if_not_exists;  /* just do nothing if it already exists? */
1728         List       *options;            /* List of DefElem nodes */
1729 } CreateExtensionStmt;
1730
1731 /* Only used for ALTER EXTENSION UPDATE; later might need an action field */
1732 typedef struct AlterExtensionStmt
1733 {
1734         NodeTag         type;
1735         char       *extname;
1736         List       *options;            /* List of DefElem nodes */
1737 } AlterExtensionStmt;
1738
1739 typedef struct AlterExtensionContentsStmt
1740 {
1741         NodeTag         type;
1742         char       *extname;            /* Extension's name */
1743         int                     action;                 /* +1 = add object, -1 = drop object */
1744         ObjectType      objtype;                /* Object's type */
1745         List       *objname;            /* Qualified name of the object */
1746         List       *objargs;            /* Arguments if needed (eg, for functions) */
1747 } AlterExtensionContentsStmt;
1748
1749 /* ----------------------
1750  *              Create/Alter FOREIGN DATA WRAPPER Statements
1751  * ----------------------
1752  */
1753
1754 typedef struct CreateFdwStmt
1755 {
1756         NodeTag         type;
1757         char       *fdwname;            /* foreign-data wrapper name */
1758         List       *func_options;       /* HANDLER/VALIDATOR options */
1759         List       *options;            /* generic options to FDW */
1760 } CreateFdwStmt;
1761
1762 typedef struct AlterFdwStmt
1763 {
1764         NodeTag         type;
1765         char       *fdwname;            /* foreign-data wrapper name */
1766         List       *func_options;       /* HANDLER/VALIDATOR options */
1767         List       *options;            /* generic options to FDW */
1768 } AlterFdwStmt;
1769
1770 /* ----------------------
1771  *              Create/Alter FOREIGN SERVER Statements
1772  * ----------------------
1773  */
1774
1775 typedef struct CreateForeignServerStmt
1776 {
1777         NodeTag         type;
1778         char       *servername;         /* server name */
1779         char       *servertype;         /* optional server type */
1780         char       *version;            /* optional server version */
1781         char       *fdwname;            /* FDW name */
1782         List       *options;            /* generic options to server */
1783 } CreateForeignServerStmt;
1784
1785 typedef struct AlterForeignServerStmt
1786 {
1787         NodeTag         type;
1788         char       *servername;         /* server name */
1789         char       *version;            /* optional server version */
1790         List       *options;            /* generic options to server */
1791         bool            has_version;    /* version specified */
1792 } AlterForeignServerStmt;
1793
1794 /* ----------------------
1795  *              Create FOREIGN TABLE Statement
1796  * ----------------------
1797  */
1798
1799 typedef struct CreateForeignTableStmt
1800 {
1801         CreateStmt      base;
1802         char       *servername;
1803         List       *options;
1804 } CreateForeignTableStmt;
1805
1806 /* ----------------------
1807  *              Create/Drop USER MAPPING Statements
1808  * ----------------------
1809  */
1810
1811 typedef struct CreateUserMappingStmt
1812 {
1813         NodeTag         type;
1814         char       *username;           /* username or PUBLIC/CURRENT_USER */
1815         char       *servername;         /* server name */
1816         List       *options;            /* generic options to server */
1817 } CreateUserMappingStmt;
1818
1819 typedef struct AlterUserMappingStmt
1820 {
1821         NodeTag         type;
1822         char       *username;           /* username or PUBLIC/CURRENT_USER */
1823         char       *servername;         /* server name */
1824         List       *options;            /* generic options to server */
1825 } AlterUserMappingStmt;
1826
1827 typedef struct DropUserMappingStmt
1828 {
1829         NodeTag         type;
1830         char       *username;           /* username or PUBLIC/CURRENT_USER */
1831         char       *servername;         /* server name */
1832         bool            missing_ok;             /* ignore missing mappings */
1833 } DropUserMappingStmt;
1834
1835 /* ----------------------
1836  *              Import Foreign Schema Statement
1837  * ----------------------
1838  */
1839
1840 typedef enum ImportForeignSchemaType
1841 {
1842         FDW_IMPORT_SCHEMA_ALL,          /* all relations wanted */
1843         FDW_IMPORT_SCHEMA_LIMIT_TO, /* include only listed tables in import */
1844         FDW_IMPORT_SCHEMA_EXCEPT        /* exclude listed tables from import */
1845 } ImportForeignSchemaType;
1846
1847 typedef struct ImportForeignSchemaStmt
1848 {
1849         NodeTag         type;
1850         char       *server_name;        /* FDW server name */
1851         char       *remote_schema;      /* remote schema name to query */
1852         char       *local_schema;       /* local schema to create objects in */
1853         ImportForeignSchemaType list_type;      /* type of table list */
1854         List       *table_list;         /* List of RangeVar */
1855         List       *options;            /* list of options to pass to FDW */
1856 } ImportForeignSchemaStmt;
1857
1858 /* ----------------------
1859  *              Create TRIGGER Statement
1860  * ----------------------
1861  */
1862 typedef struct CreateTrigStmt
1863 {
1864         NodeTag         type;
1865         char       *trigname;           /* TRIGGER's name */
1866         RangeVar   *relation;           /* relation trigger is on */
1867         List       *funcname;           /* qual. name of function to call */
1868         List       *args;                       /* list of (T_String) Values or NIL */
1869         bool            row;                    /* ROW/STATEMENT */
1870         /* timing uses the TRIGGER_TYPE bits defined in catalog/pg_trigger.h */
1871         int16           timing;                 /* BEFORE, AFTER, or INSTEAD */
1872         /* events uses the TRIGGER_TYPE bits defined in catalog/pg_trigger.h */
1873         int16           events;                 /* "OR" of INSERT/UPDATE/DELETE/TRUNCATE */
1874         List       *columns;            /* column names, or NIL for all columns */
1875         Node       *whenClause;         /* qual expression, or NULL if none */
1876         bool            isconstraint;   /* This is a constraint trigger */
1877         /* The remaining fields are only used for constraint triggers */
1878         bool            deferrable;             /* [NOT] DEFERRABLE */
1879         bool            initdeferred;   /* INITIALLY {DEFERRED|IMMEDIATE} */
1880         RangeVar   *constrrel;          /* opposite relation, if RI trigger */
1881 } CreateTrigStmt;
1882
1883 /* ----------------------
1884  *              Create EVENT TRIGGER Statement
1885  * ----------------------
1886  */
1887 typedef struct CreateEventTrigStmt
1888 {
1889         NodeTag         type;
1890         char       *trigname;           /* TRIGGER's name */
1891         char       *eventname;          /* event's identifier */
1892         List       *whenclause;         /* list of DefElems indicating filtering */
1893         List       *funcname;           /* qual. name of function to call */
1894 } CreateEventTrigStmt;
1895
1896 /* ----------------------
1897  *              Alter EVENT TRIGGER Statement
1898  * ----------------------
1899  */
1900 typedef struct AlterEventTrigStmt
1901 {
1902         NodeTag         type;
1903         char       *trigname;           /* TRIGGER's name */
1904         char            tgenabled;              /* trigger's firing configuration WRT
1905                                                                  * session_replication_role */
1906 } AlterEventTrigStmt;
1907
1908 /* ----------------------
1909  *              Create/Drop PROCEDURAL LANGUAGE Statements
1910  *              Create PROCEDURAL LANGUAGE Statements
1911  * ----------------------
1912  */
1913 typedef struct CreatePLangStmt
1914 {
1915         NodeTag         type;
1916         bool            replace;                /* T => replace if already exists */
1917         char       *plname;                     /* PL name */
1918         List       *plhandler;          /* PL call handler function (qual. name) */
1919         List       *plinline;           /* optional inline function (qual. name) */
1920         List       *plvalidator;        /* optional validator function (qual. name) */
1921         bool            pltrusted;              /* PL is trusted */
1922 } CreatePLangStmt;
1923
1924 /* ----------------------
1925  *      Create/Alter/Drop Role Statements
1926  *
1927  * Note: these node types are also used for the backwards-compatible
1928  * Create/Alter/Drop User/Group statements.  In the ALTER and DROP cases
1929  * there's really no need to distinguish what the original spelling was,
1930  * but for CREATE we mark the type because the defaults vary.
1931  * ----------------------
1932  */
1933 typedef enum RoleStmtType
1934 {
1935         ROLESTMT_ROLE,
1936         ROLESTMT_USER,
1937         ROLESTMT_GROUP
1938 } RoleStmtType;
1939
1940 typedef struct CreateRoleStmt
1941 {
1942         NodeTag         type;
1943         RoleStmtType stmt_type;         /* ROLE/USER/GROUP */
1944         char       *role;                       /* role name */
1945         List       *options;            /* List of DefElem nodes */
1946 } CreateRoleStmt;
1947
1948 typedef struct AlterRoleStmt
1949 {
1950         NodeTag         type;
1951         char       *role;                       /* role name */
1952         List       *options;            /* List of DefElem nodes */
1953         int                     action;                 /* +1 = add members, -1 = drop members */
1954 } AlterRoleStmt;
1955
1956 typedef struct AlterRoleSetStmt
1957 {
1958         NodeTag         type;
1959         char       *role;                       /* role name */
1960         char       *database;           /* database name, or NULL */
1961         VariableSetStmt *setstmt;       /* SET or RESET subcommand */
1962 } AlterRoleSetStmt;
1963
1964 typedef struct DropRoleStmt
1965 {
1966         NodeTag         type;
1967         List       *roles;                      /* List of roles to remove */
1968         bool            missing_ok;             /* skip error if a role is missing? */
1969 } DropRoleStmt;
1970
1971 /* ----------------------
1972  *              {Create|Alter} SEQUENCE Statement
1973  * ----------------------
1974  */
1975
1976 typedef struct CreateSeqStmt
1977 {
1978         NodeTag         type;
1979         RangeVar   *sequence;           /* the sequence to create */
1980         List       *options;
1981         Oid                     ownerId;                /* ID of owner, or InvalidOid for default */
1982         bool            if_not_exists;  /* just do nothing if it already exists? */
1983 } CreateSeqStmt;
1984
1985 typedef struct AlterSeqStmt
1986 {
1987         NodeTag         type;
1988         RangeVar   *sequence;           /* the sequence to alter */
1989         List       *options;
1990         bool            missing_ok;             /* skip error if a role is missing? */
1991 } AlterSeqStmt;
1992
1993 /* ----------------------
1994  *              Create {Aggregate|Operator|Type} Statement
1995  * ----------------------
1996  */
1997 typedef struct DefineStmt
1998 {
1999         NodeTag         type;
2000         ObjectType      kind;                   /* aggregate, operator, type */
2001         bool            oldstyle;               /* hack to signal old CREATE AGG syntax */
2002         List       *defnames;           /* qualified name (list of Value strings) */
2003         List       *args;                       /* a list of TypeName (if needed) */
2004         List       *definition;         /* a list of DefElem */
2005 } DefineStmt;
2006
2007 /* ----------------------
2008  *              Create Domain Statement
2009  * ----------------------
2010  */
2011 typedef struct CreateDomainStmt
2012 {
2013         NodeTag         type;
2014         List       *domainname;         /* qualified name (list of Value strings) */
2015         TypeName   *typeName;           /* the base type */
2016         CollateClause *collClause;      /* untransformed COLLATE spec, if any */
2017         List       *constraints;        /* constraints (list of Constraint nodes) */
2018 } CreateDomainStmt;
2019
2020 /* ----------------------
2021  *              Create Operator Class Statement
2022  * ----------------------
2023  */
2024 typedef struct CreateOpClassStmt
2025 {
2026         NodeTag         type;
2027         List       *opclassname;        /* qualified name (list of Value strings) */
2028         List       *opfamilyname;       /* qualified name (ditto); NIL if omitted */
2029         char       *amname;                     /* name of index AM opclass is for */
2030         TypeName   *datatype;           /* datatype of indexed column */
2031         List       *items;                      /* List of CreateOpClassItem nodes */
2032         bool            isDefault;              /* Should be marked as default for type? */
2033 } CreateOpClassStmt;
2034
2035 #define OPCLASS_ITEM_OPERATOR           1
2036 #define OPCLASS_ITEM_FUNCTION           2
2037 #define OPCLASS_ITEM_STORAGETYPE        3
2038
2039 typedef struct CreateOpClassItem
2040 {
2041         NodeTag         type;
2042         int                     itemtype;               /* see codes above */
2043         /* fields used for an operator or function item: */
2044         List       *name;                       /* operator or function name */
2045         List       *args;                       /* argument types */
2046         int                     number;                 /* strategy num or support proc num */
2047         List       *order_family;       /* only used for ordering operators */
2048         List       *class_args;         /* only used for functions */
2049         /* fields used for a storagetype item: */
2050         TypeName   *storedtype;         /* datatype stored in index */
2051 } CreateOpClassItem;
2052
2053 /* ----------------------
2054  *              Create Operator Family Statement
2055  * ----------------------
2056  */
2057 typedef struct CreateOpFamilyStmt
2058 {
2059         NodeTag         type;
2060         List       *opfamilyname;       /* qualified name (list of Value strings) */
2061         char       *amname;                     /* name of index AM opfamily is for */
2062 } CreateOpFamilyStmt;
2063
2064 /* ----------------------
2065  *              Alter Operator Family Statement
2066  * ----------------------
2067  */
2068 typedef struct AlterOpFamilyStmt
2069 {
2070         NodeTag         type;
2071         List       *opfamilyname;       /* qualified name (list of Value strings) */
2072         char       *amname;                     /* name of index AM opfamily is for */
2073         bool            isDrop;                 /* ADD or DROP the items? */
2074         List       *items;                      /* List of CreateOpClassItem nodes */
2075 } AlterOpFamilyStmt;
2076
2077 /* ----------------------
2078  *              Drop Table|Sequence|View|Index|Type|Domain|Conversion|Schema Statement
2079  * ----------------------
2080  */
2081
2082 typedef struct DropStmt
2083 {
2084         NodeTag         type;
2085         List       *objects;            /* list of sublists of names (as Values) */
2086         List       *arguments;          /* list of sublists of arguments (as Values) */
2087         ObjectType      removeType;             /* object type */
2088         DropBehavior behavior;          /* RESTRICT or CASCADE behavior */
2089         bool            missing_ok;             /* skip error if object is missing? */
2090         bool            concurrent;             /* drop index concurrently? */
2091 } DropStmt;
2092
2093 /* ----------------------
2094  *                              Truncate Table Statement
2095  * ----------------------
2096  */
2097 typedef struct TruncateStmt
2098 {
2099         NodeTag         type;
2100         List       *relations;          /* relations (RangeVars) to be truncated */
2101         bool            restart_seqs;   /* restart owned sequences? */
2102         DropBehavior behavior;          /* RESTRICT or CASCADE behavior */
2103 } TruncateStmt;
2104
2105 /* ----------------------
2106  *                              Comment On Statement
2107  * ----------------------
2108  */
2109 typedef struct CommentStmt
2110 {
2111         NodeTag         type;
2112         ObjectType      objtype;                /* Object's type */
2113         List       *objname;            /* Qualified name of the object */
2114         List       *objargs;            /* Arguments if needed (eg, for functions) */
2115         char       *comment;            /* Comment to insert, or NULL to remove */
2116 } CommentStmt;
2117
2118 /* ----------------------
2119  *                              SECURITY LABEL Statement
2120  * ----------------------
2121  */
2122 typedef struct SecLabelStmt
2123 {
2124         NodeTag         type;
2125         ObjectType      objtype;                /* Object's type */
2126         List       *objname;            /* Qualified name of the object */
2127         List       *objargs;            /* Arguments if needed (eg, for functions) */
2128         char       *provider;           /* Label provider (or NULL) */
2129         char       *label;                      /* New security label to be assigned */
2130 } SecLabelStmt;
2131
2132 /* ----------------------
2133  *              Declare Cursor Statement
2134  *
2135  * Note: the "query" field of DeclareCursorStmt is only used in the raw grammar
2136  * output.  After parse analysis it's set to null, and the Query points to the
2137  * DeclareCursorStmt, not vice versa.
2138  * ----------------------
2139  */
2140 #define CURSOR_OPT_BINARY               0x0001  /* BINARY */
2141 #define CURSOR_OPT_SCROLL               0x0002  /* SCROLL explicitly given */
2142 #define CURSOR_OPT_NO_SCROLL    0x0004  /* NO SCROLL explicitly given */
2143 #define CURSOR_OPT_INSENSITIVE  0x0008  /* INSENSITIVE */
2144 #define CURSOR_OPT_HOLD                 0x0010  /* WITH HOLD */
2145 /* these planner-control flags do not correspond to any SQL grammar: */
2146 #define CURSOR_OPT_FAST_PLAN    0x0020  /* prefer fast-start plan */
2147 #define CURSOR_OPT_GENERIC_PLAN 0x0040  /* force use of generic plan */
2148 #define CURSOR_OPT_CUSTOM_PLAN  0x0080  /* force use of custom plan */
2149
2150 typedef struct DeclareCursorStmt
2151 {
2152         NodeTag         type;
2153         char       *portalname;         /* name of the portal (cursor) */
2154         int                     options;                /* bitmask of options (see above) */
2155         Node       *query;                      /* the raw SELECT query */
2156 } DeclareCursorStmt;
2157
2158 /* ----------------------
2159  *              Close Portal Statement
2160  * ----------------------
2161  */
2162 typedef struct ClosePortalStmt
2163 {
2164         NodeTag         type;
2165         char       *portalname;         /* name of the portal (cursor) */
2166         /* NULL means CLOSE ALL */
2167 } ClosePortalStmt;
2168
2169 /* ----------------------
2170  *              Fetch Statement (also Move)
2171  * ----------------------
2172  */
2173 typedef enum FetchDirection
2174 {
2175         /* for these, howMany is how many rows to fetch; FETCH_ALL means ALL */
2176         FETCH_FORWARD,
2177         FETCH_BACKWARD,
2178         /* for these, howMany indicates a position; only one row is fetched */
2179         FETCH_ABSOLUTE,
2180         FETCH_RELATIVE
2181 } FetchDirection;
2182
2183 #define FETCH_ALL       LONG_MAX
2184
2185 typedef struct FetchStmt
2186 {
2187         NodeTag         type;
2188         FetchDirection direction;       /* see above */
2189         long            howMany;                /* number of rows, or position argument */
2190         char       *portalname;         /* name of portal (cursor) */
2191         bool            ismove;                 /* TRUE if MOVE */
2192 } FetchStmt;
2193
2194 /* ----------------------
2195  *              Create Index Statement
2196  *
2197  * This represents creation of an index and/or an associated constraint.
2198  * If isconstraint is true, we should create a pg_constraint entry along
2199  * with the index.  But if indexOid isn't InvalidOid, we are not creating an
2200  * index, just a UNIQUE/PKEY constraint using an existing index.  isconstraint
2201  * must always be true in this case, and the fields describing the index
2202  * properties are empty.
2203  * ----------------------
2204  */
2205 typedef struct IndexStmt
2206 {
2207         NodeTag         type;
2208         char       *idxname;            /* name of new index, or NULL for default */
2209         RangeVar   *relation;           /* relation to build index on */
2210         char       *accessMethod;       /* name of access method (eg. btree) */
2211         char       *tableSpace;         /* tablespace, or NULL for default */
2212         List       *indexParams;        /* columns to index: a list of IndexElem */
2213         List       *options;            /* WITH clause options: a list of DefElem */
2214         Node       *whereClause;        /* qualification (partial-index predicate) */
2215         List       *excludeOpNames; /* exclusion operator names, or NIL if none */
2216         char       *idxcomment;         /* comment to apply to index, or NULL */
2217         Oid                     indexOid;               /* OID of an existing index, if any */
2218         Oid                     oldNode;                /* relfilenode of existing storage, if any */
2219         bool            unique;                 /* is index unique? */
2220         bool            primary;                /* is index a primary key? */
2221         bool            isconstraint;   /* is it for a pkey/unique constraint? */
2222         bool            deferrable;             /* is the constraint DEFERRABLE? */
2223         bool            initdeferred;   /* is the constraint INITIALLY DEFERRED? */
2224         bool            concurrent;             /* should this be a concurrent index build? */
2225 } IndexStmt;
2226
2227 /* ----------------------
2228  *              Create Function Statement
2229  * ----------------------
2230  */
2231 typedef struct CreateFunctionStmt
2232 {
2233         NodeTag         type;
2234         bool            replace;                /* T => replace if already exists */
2235         List       *funcname;           /* qualified name of function to create */
2236         List       *parameters;         /* a list of FunctionParameter */
2237         TypeName   *returnType;         /* the return type */
2238         List       *options;            /* a list of DefElem */
2239         List       *withClause;         /* a list of DefElem */
2240 } CreateFunctionStmt;
2241
2242 typedef enum FunctionParameterMode
2243 {
2244         /* the assigned enum values appear in pg_proc, don't change 'em! */
2245         FUNC_PARAM_IN = 'i',            /* input only */
2246         FUNC_PARAM_OUT = 'o',           /* output only */
2247         FUNC_PARAM_INOUT = 'b',         /* both */
2248         FUNC_PARAM_VARIADIC = 'v',      /* variadic (always input) */
2249         FUNC_PARAM_TABLE = 't'          /* table function output column */
2250 } FunctionParameterMode;
2251
2252 typedef struct FunctionParameter
2253 {
2254         NodeTag         type;
2255         char       *name;                       /* parameter name, or NULL if not given */
2256         TypeName   *argType;            /* TypeName for parameter type */
2257         FunctionParameterMode mode; /* IN/OUT/etc */
2258         Node       *defexpr;            /* raw default expr, or NULL if not given */
2259 } FunctionParameter;
2260
2261 typedef struct AlterFunctionStmt
2262 {
2263         NodeTag         type;
2264         FuncWithArgs *func;                     /* name and args of function */
2265         List       *actions;            /* list of DefElem */
2266 } AlterFunctionStmt;
2267
2268 /* ----------------------
2269  *              DO Statement
2270  *
2271  * DoStmt is the raw parser output, InlineCodeBlock is the execution-time API
2272  * ----------------------
2273  */
2274 typedef struct DoStmt
2275 {
2276         NodeTag         type;
2277         List       *args;                       /* List of DefElem nodes */
2278 } DoStmt;
2279
2280 typedef struct InlineCodeBlock
2281 {
2282         NodeTag         type;
2283         char       *source_text;        /* source text of anonymous code block */
2284         Oid                     langOid;                /* OID of selected language */
2285         bool            langIsTrusted;  /* trusted property of the language */
2286 } InlineCodeBlock;
2287
2288 /* ----------------------
2289  *              Alter Object Rename Statement
2290  * ----------------------
2291  */
2292 typedef struct RenameStmt
2293 {
2294         NodeTag         type;
2295         ObjectType      renameType;             /* OBJECT_TABLE, OBJECT_COLUMN, etc */
2296         ObjectType      relationType;   /* if column name, associated relation type */
2297         RangeVar   *relation;           /* in case it's a table */
2298         List       *object;                     /* in case it's some other object */
2299         List       *objarg;                     /* argument types, if applicable */
2300         char       *subname;            /* name of contained object (column, rule,
2301                                                                  * trigger, etc) */
2302         char       *newname;            /* the new name */
2303         DropBehavior behavior;          /* RESTRICT or CASCADE behavior */
2304         bool            missing_ok;             /* skip error if missing? */
2305 } RenameStmt;
2306
2307 /* ----------------------
2308  *              ALTER object SET SCHEMA Statement
2309  * ----------------------
2310  */
2311 typedef struct AlterObjectSchemaStmt
2312 {
2313         NodeTag         type;
2314         ObjectType objectType;          /* OBJECT_TABLE, OBJECT_TYPE, etc */
2315         RangeVar   *relation;           /* in case it's a table */
2316         List       *object;                     /* in case it's some other object */
2317         List       *objarg;                     /* argument types, if applicable */
2318         char       *newschema;          /* the new schema */
2319         bool            missing_ok;             /* skip error if missing? */
2320 } AlterObjectSchemaStmt;
2321
2322 /* ----------------------
2323  *              Alter Object Owner Statement
2324  * ----------------------
2325  */
2326 typedef struct AlterOwnerStmt
2327 {
2328         NodeTag         type;
2329         ObjectType objectType;          /* OBJECT_TABLE, OBJECT_TYPE, etc */
2330         RangeVar   *relation;           /* in case it's a table */
2331         List       *object;                     /* in case it's some other object */
2332         List       *objarg;                     /* argument types, if applicable */
2333         char       *newowner;           /* the new owner */
2334 } AlterOwnerStmt;
2335
2336
2337 /* ----------------------
2338  *              Create Rule Statement
2339  * ----------------------
2340  */
2341 typedef struct RuleStmt
2342 {
2343         NodeTag         type;
2344         RangeVar   *relation;           /* relation the rule is for */
2345         char       *rulename;           /* name of the rule */
2346         Node       *whereClause;        /* qualifications */
2347         CmdType         event;                  /* SELECT, INSERT, etc */
2348         bool            instead;                /* is a 'do instead'? */
2349         List       *actions;            /* the action statements */
2350         bool            replace;                /* OR REPLACE */
2351 } RuleStmt;
2352
2353 /* ----------------------
2354  *              Notify Statement
2355  * ----------------------
2356  */
2357 typedef struct NotifyStmt
2358 {
2359         NodeTag         type;
2360         char       *conditionname;      /* condition name to notify */
2361         char       *payload;            /* the payload string, or NULL if none */
2362 } NotifyStmt;
2363
2364 /* ----------------------
2365  *              Listen Statement
2366  * ----------------------
2367  */
2368 typedef struct ListenStmt
2369 {
2370         NodeTag         type;
2371         char       *conditionname;      /* condition name to listen on */
2372 } ListenStmt;
2373
2374 /* ----------------------
2375  *              Unlisten Statement
2376  * ----------------------
2377  */
2378 typedef struct UnlistenStmt
2379 {
2380         NodeTag         type;
2381         char       *conditionname;      /* name to unlisten on, or NULL for all */
2382 } UnlistenStmt;
2383
2384 /* ----------------------
2385  *              {Begin|Commit|Rollback} Transaction Statement
2386  * ----------------------
2387  */
2388 typedef enum TransactionStmtKind
2389 {
2390         TRANS_STMT_BEGIN,
2391         TRANS_STMT_START,                       /* semantically identical to BEGIN */
2392         TRANS_STMT_COMMIT,
2393         TRANS_STMT_ROLLBACK,
2394         TRANS_STMT_SAVEPOINT,
2395         TRANS_STMT_RELEASE,
2396         TRANS_STMT_ROLLBACK_TO,
2397         TRANS_STMT_PREPARE,
2398         TRANS_STMT_COMMIT_PREPARED,
2399         TRANS_STMT_ROLLBACK_PREPARED
2400 } TransactionStmtKind;
2401
2402 typedef struct TransactionStmt
2403 {
2404         NodeTag         type;
2405         TransactionStmtKind kind;       /* see above */
2406         List       *options;            /* for BEGIN/START and savepoint commands */
2407         char       *gid;                        /* for two-phase-commit related commands */
2408 } TransactionStmt;
2409
2410 /* ----------------------
2411  *              Create Type Statement, composite types
2412  * ----------------------
2413  */
2414 typedef struct CompositeTypeStmt
2415 {
2416         NodeTag         type;
2417         RangeVar   *typevar;            /* the composite type to be created */
2418         List       *coldeflist;         /* list of ColumnDef nodes */
2419 } CompositeTypeStmt;
2420
2421 /* ----------------------
2422  *              Create Type Statement, enum types
2423  * ----------------------
2424  */
2425 typedef struct CreateEnumStmt
2426 {
2427         NodeTag         type;
2428         List       *typeName;           /* qualified name (list of Value strings) */
2429         List       *vals;                       /* enum values (list of Value strings) */
2430 } CreateEnumStmt;
2431
2432 /* ----------------------
2433  *              Create Type Statement, range types
2434  * ----------------------
2435  */
2436 typedef struct CreateRangeStmt
2437 {
2438         NodeTag         type;
2439         List       *typeName;           /* qualified name (list of Value strings) */
2440         List       *params;                     /* range parameters (list of DefElem) */
2441 } CreateRangeStmt;
2442
2443 /* ----------------------
2444  *              Alter Type Statement, enum types
2445  * ----------------------
2446  */
2447 typedef struct AlterEnumStmt
2448 {
2449         NodeTag         type;
2450         List       *typeName;           /* qualified name (list of Value strings) */
2451         char       *newVal;                     /* new enum value's name */
2452         char       *newValNeighbor; /* neighboring enum value, if specified */
2453         bool            newValIsAfter;  /* place new enum value after neighbor? */
2454         bool            skipIfExists;   /* no error if label already exists */
2455 } AlterEnumStmt;
2456
2457 /* ----------------------
2458  *              Create View Statement
2459  * ----------------------
2460  */
2461 typedef enum ViewCheckOption
2462 {
2463         NO_CHECK_OPTION,
2464         LOCAL_CHECK_OPTION,
2465         CASCADED_CHECK_OPTION
2466 } ViewCheckOption;
2467
2468 typedef struct ViewStmt
2469 {
2470         NodeTag         type;
2471         RangeVar   *view;                       /* the view to be created */
2472         List       *aliases;            /* target column names */
2473         Node       *query;                      /* the SELECT query */
2474         bool            replace;                /* replace an existing view? */
2475         List       *options;            /* options from WITH clause */
2476         ViewCheckOption withCheckOption;        /* WITH CHECK OPTION */
2477 } ViewStmt;
2478
2479 /* ----------------------
2480  *              Load Statement
2481  * ----------------------
2482  */
2483 typedef struct LoadStmt
2484 {
2485         NodeTag         type;
2486         char       *filename;           /* file to load */
2487 } LoadStmt;
2488
2489 /* ----------------------
2490  *              Createdb Statement
2491  * ----------------------
2492  */
2493 typedef struct CreatedbStmt
2494 {
2495         NodeTag         type;
2496         char       *dbname;                     /* name of database to create */
2497         List       *options;            /* List of DefElem nodes */
2498 } CreatedbStmt;
2499
2500 /* ----------------------
2501  *      Alter Database
2502  * ----------------------
2503  */
2504 typedef struct AlterDatabaseStmt
2505 {
2506         NodeTag         type;
2507         char       *dbname;                     /* name of database to alter */
2508         List       *options;            /* List of DefElem nodes */
2509 } AlterDatabaseStmt;
2510
2511 typedef struct AlterDatabaseSetStmt
2512 {
2513         NodeTag         type;
2514         char       *dbname;                     /* database name */
2515         VariableSetStmt *setstmt;       /* SET or RESET subcommand */
2516 } AlterDatabaseSetStmt;
2517
2518 /* ----------------------
2519  *              Dropdb Statement
2520  * ----------------------
2521  */
2522 typedef struct DropdbStmt
2523 {
2524         NodeTag         type;
2525         char       *dbname;                     /* database to drop */
2526         bool            missing_ok;             /* skip error if db is missing? */
2527 } DropdbStmt;
2528
2529 /* ----------------------
2530  *              Alter System Statement
2531  * ----------------------
2532  */
2533 typedef struct AlterSystemStmt
2534 {
2535         NodeTag         type;
2536         VariableSetStmt *setstmt;       /* SET subcommand */
2537 } AlterSystemStmt;
2538
2539 /* ----------------------
2540  *              Cluster Statement (support pbrown's cluster index implementation)
2541  * ----------------------
2542  */
2543 typedef struct ClusterStmt
2544 {
2545         NodeTag         type;
2546         RangeVar   *relation;           /* relation being indexed, or NULL if all */
2547         char       *indexname;          /* original index defined */
2548         bool            verbose;                /* print progress info */
2549 } ClusterStmt;
2550
2551 /* ----------------------
2552  *              Vacuum and Analyze Statements
2553  *
2554  * Even though these are nominally two statements, it's convenient to use
2555  * just one node type for both.  Note that at least one of VACOPT_VACUUM
2556  * and VACOPT_ANALYZE must be set in options.  VACOPT_FREEZE is an internal
2557  * convenience for the grammar and is not examined at runtime --- the
2558  * freeze_min_age and freeze_table_age fields are what matter.
2559  * ----------------------
2560  */
2561 typedef enum VacuumOption
2562 {
2563         VACOPT_VACUUM = 1 << 0,         /* do VACUUM */
2564         VACOPT_ANALYZE = 1 << 1,        /* do ANALYZE */
2565         VACOPT_VERBOSE = 1 << 2,        /* print progress info */
2566         VACOPT_FREEZE = 1 << 3,         /* FREEZE option */
2567         VACOPT_FULL = 1 << 4,           /* FULL (non-concurrent) vacuum */
2568         VACOPT_NOWAIT = 1 << 5          /* don't wait to get lock (autovacuum only) */
2569 } VacuumOption;
2570
2571 typedef struct VacuumStmt
2572 {
2573         NodeTag         type;
2574         int                     options;                /* OR of VacuumOption flags */
2575         int                     freeze_min_age; /* min freeze age, or -1 to use default */
2576         int                     freeze_table_age;               /* age at which to scan whole table */
2577         int                     multixact_freeze_min_age;               /* min multixact freeze age,
2578                                                                                                  * or -1 to use default */
2579         int                     multixact_freeze_table_age;             /* multixact age at which to
2580                                                                                                  * scan whole table */
2581         RangeVar   *relation;           /* single table to process, or NULL */
2582         List       *va_cols;            /* list of column names, or NIL for all */
2583 } VacuumStmt;
2584
2585 /* ----------------------
2586  *              Explain Statement
2587  *
2588  * The "query" field is either a raw parse tree (SelectStmt, InsertStmt, etc)
2589  * or a Query node if parse analysis has been done.  Note that rewriting and
2590  * planning of the query are always postponed until execution of EXPLAIN.
2591  * ----------------------
2592  */
2593 typedef struct ExplainStmt
2594 {
2595         NodeTag         type;
2596         Node       *query;                      /* the query (see comments above) */
2597         List       *options;            /* list of DefElem nodes */
2598 } ExplainStmt;
2599
2600 /* ----------------------
2601  *              CREATE TABLE AS Statement (a/k/a SELECT INTO)
2602  *
2603  * A query written as CREATE TABLE AS will produce this node type natively.
2604  * A query written as SELECT ... INTO will be transformed to this form during
2605  * parse analysis.
2606  * A query written as CREATE MATERIALIZED view will produce this node type,
2607  * during parse analysis, since it needs all the same data.
2608  *
2609  * The "query" field is handled similarly to EXPLAIN, though note that it
2610  * can be a SELECT or an EXECUTE, but not other DML statements.
2611  * ----------------------
2612  */
2613 typedef struct CreateTableAsStmt
2614 {
2615         NodeTag         type;
2616         Node       *query;                      /* the query (see comments above) */
2617         IntoClause *into;                       /* destination table */
2618         ObjectType      relkind;                /* OBJECT_TABLE or OBJECT_MATVIEW */
2619         bool            is_select_into; /* it was written as SELECT INTO */
2620 } CreateTableAsStmt;
2621
2622 /* ----------------------
2623  *              REFRESH MATERIALIZED VIEW Statement
2624  * ----------------------
2625  */
2626 typedef struct RefreshMatViewStmt
2627 {
2628         NodeTag         type;
2629         bool            concurrent;             /* allow concurrent access? */
2630         bool            skipData;               /* true for WITH NO DATA */
2631         RangeVar   *relation;           /* relation to insert into */
2632 } RefreshMatViewStmt;
2633
2634 /* ----------------------
2635  * Checkpoint Statement
2636  * ----------------------
2637  */
2638 typedef struct CheckPointStmt
2639 {
2640         NodeTag         type;
2641 } CheckPointStmt;
2642
2643 /* ----------------------
2644  * Discard Statement
2645  * ----------------------
2646  */
2647
2648 typedef enum DiscardMode
2649 {
2650         DISCARD_ALL,
2651         DISCARD_PLANS,
2652         DISCARD_SEQUENCES,
2653         DISCARD_TEMP
2654 } DiscardMode;
2655
2656 typedef struct DiscardStmt
2657 {
2658         NodeTag         type;
2659         DiscardMode target;
2660 } DiscardStmt;
2661
2662 /* ----------------------
2663  *              LOCK Statement
2664  * ----------------------
2665  */
2666 typedef struct LockStmt
2667 {
2668         NodeTag         type;
2669         List       *relations;          /* relations to lock */
2670         int                     mode;                   /* lock mode */
2671         bool            nowait;                 /* no wait mode */
2672 } LockStmt;
2673
2674 /* ----------------------
2675  *              SET CONSTRAINTS Statement
2676  * ----------------------
2677  */
2678 typedef struct ConstraintsSetStmt
2679 {
2680         NodeTag         type;
2681         List       *constraints;        /* List of names as RangeVars */
2682         bool            deferred;
2683 } ConstraintsSetStmt;
2684
2685 /* ----------------------
2686  *              REINDEX Statement
2687  * ----------------------
2688  */
2689 typedef struct ReindexStmt
2690 {
2691         NodeTag         type;
2692         ObjectType      kind;                   /* OBJECT_INDEX, OBJECT_TABLE, etc. */
2693         RangeVar   *relation;           /* Table or index to reindex */
2694         const char *name;                       /* name of database to reindex */
2695         bool            do_system;              /* include system tables in database case */
2696         bool            do_user;                /* include user tables in database case */
2697 } ReindexStmt;
2698
2699 /* ----------------------
2700  *              CREATE CONVERSION Statement
2701  * ----------------------
2702  */
2703 typedef struct CreateConversionStmt
2704 {
2705         NodeTag         type;
2706         List       *conversion_name;    /* Name of the conversion */
2707         char       *for_encoding_name;          /* source encoding name */
2708         char       *to_encoding_name;           /* destination encoding name */
2709         List       *func_name;          /* qualified conversion function name */
2710         bool            def;                    /* is this a default conversion? */
2711 } CreateConversionStmt;
2712
2713 /* ----------------------
2714  *      CREATE CAST Statement
2715  * ----------------------
2716  */
2717 typedef struct CreateCastStmt
2718 {
2719         NodeTag         type;
2720         TypeName   *sourcetype;
2721         TypeName   *targettype;
2722         FuncWithArgs *func;
2723         CoercionContext context;
2724         bool            inout;
2725 } CreateCastStmt;
2726
2727 /* ----------------------
2728  *              PREPARE Statement
2729  * ----------------------
2730  */
2731 typedef struct PrepareStmt
2732 {
2733         NodeTag         type;
2734         char       *name;                       /* Name of plan, arbitrary */
2735         List       *argtypes;           /* Types of parameters (List of TypeName) */
2736         Node       *query;                      /* The query itself (as a raw parsetree) */
2737 } PrepareStmt;
2738
2739
2740 /* ----------------------
2741  *              EXECUTE Statement
2742  * ----------------------
2743  */
2744
2745 typedef struct ExecuteStmt
2746 {
2747         NodeTag         type;
2748         char       *name;                       /* The name of the plan to execute */
2749         List       *params;                     /* Values to assign to parameters */
2750 } ExecuteStmt;
2751
2752
2753 /* ----------------------
2754  *              DEALLOCATE Statement
2755  * ----------------------
2756  */
2757 typedef struct DeallocateStmt
2758 {
2759         NodeTag         type;
2760         char       *name;                       /* The name of the plan to remove */
2761         /* NULL means DEALLOCATE ALL */
2762 } DeallocateStmt;
2763
2764 /*
2765  *              DROP OWNED statement
2766  */
2767 typedef struct DropOwnedStmt
2768 {
2769         NodeTag         type;
2770         List       *roles;
2771         DropBehavior behavior;
2772 } DropOwnedStmt;
2773
2774 /*
2775  *              REASSIGN OWNED statement
2776  */
2777 typedef struct ReassignOwnedStmt
2778 {
2779         NodeTag         type;
2780         List       *roles;
2781         char       *newrole;
2782 } ReassignOwnedStmt;
2783
2784 /*
2785  * TS Dictionary stmts: DefineStmt, RenameStmt and DropStmt are default
2786  */
2787 typedef struct AlterTSDictionaryStmt
2788 {
2789         NodeTag         type;
2790         List       *dictname;           /* qualified name (list of Value strings) */
2791         List       *options;            /* List of DefElem nodes */
2792 } AlterTSDictionaryStmt;
2793
2794 /*
2795  * TS Configuration stmts: DefineStmt, RenameStmt and DropStmt are default
2796  */
2797 typedef struct AlterTSConfigurationStmt
2798 {
2799         NodeTag         type;
2800         List       *cfgname;            /* qualified name (list of Value strings) */
2801
2802         /*
2803          * dicts will be non-NIL if ADD/ALTER MAPPING was specified. If dicts is
2804          * NIL, but tokentype isn't, DROP MAPPING was specified.
2805          */
2806         List       *tokentype;          /* list of Value strings */
2807         List       *dicts;                      /* list of list of Value strings */
2808         bool            override;               /* if true - remove old variant */
2809         bool            replace;                /* if true - replace dictionary by another */
2810         bool            missing_ok;             /* for DROP - skip error if missing? */
2811 } AlterTSConfigurationStmt;
2812
2813 #endif   /* PARSENODES_H */