]> granicus.if.org Git - postgresql/blob - src/include/nodes/parsenodes.h
Implement IMPORT FOREIGN SCHEMA.
[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_AddOids,                                     /* SET WITH OIDS */
1311         AT_AddOidsRecurse,                      /* internal to commands/tablecmds.c */
1312         AT_DropOids,                            /* SET WITHOUT OIDS */
1313         AT_SetTableSpace,                       /* SET TABLESPACE */
1314         AT_SetRelOptions,                       /* SET (...) -- AM specific parameters */
1315         AT_ResetRelOptions,                     /* RESET (...) -- AM specific parameters */
1316         AT_ReplaceRelOptions,           /* replace reloption list in its entirety */
1317         AT_EnableTrig,                          /* ENABLE TRIGGER name */
1318         AT_EnableAlwaysTrig,            /* ENABLE ALWAYS TRIGGER name */
1319         AT_EnableReplicaTrig,           /* ENABLE REPLICA TRIGGER name */
1320         AT_DisableTrig,                         /* DISABLE TRIGGER name */
1321         AT_EnableTrigAll,                       /* ENABLE TRIGGER ALL */
1322         AT_DisableTrigAll,                      /* DISABLE TRIGGER ALL */
1323         AT_EnableTrigUser,                      /* ENABLE TRIGGER USER */
1324         AT_DisableTrigUser,                     /* DISABLE TRIGGER USER */
1325         AT_EnableRule,                          /* ENABLE RULE name */
1326         AT_EnableAlwaysRule,            /* ENABLE ALWAYS RULE name */
1327         AT_EnableReplicaRule,           /* ENABLE REPLICA RULE name */
1328         AT_DisableRule,                         /* DISABLE RULE name */
1329         AT_AddInherit,                          /* INHERIT parent */
1330         AT_DropInherit,                         /* NO INHERIT parent */
1331         AT_AddOf,                                       /* OF <type_name> */
1332         AT_DropOf,                                      /* NOT OF */
1333         AT_ReplicaIdentity,                     /* REPLICA IDENTITY */
1334         AT_GenericOptions                       /* OPTIONS (...) */
1335 } AlterTableType;
1336
1337 typedef struct ReplicaIdentityStmt
1338 {
1339         NodeTag         type;
1340         char            identity_type;
1341         char       *name;
1342 } ReplicaIdentityStmt;
1343
1344 typedef struct AlterTableCmd    /* one subcommand of an ALTER TABLE */
1345 {
1346         NodeTag         type;
1347         AlterTableType subtype;         /* Type of table alteration to apply */
1348         char       *name;                       /* column, constraint, or trigger to act on,
1349                                                                  * or new owner or tablespace */
1350         Node       *def;                        /* definition of new column, index,
1351                                                                  * constraint, or parent table */
1352         DropBehavior behavior;          /* RESTRICT or CASCADE for DROP cases */
1353         bool            missing_ok;             /* skip error if missing? */
1354 } AlterTableCmd;
1355
1356
1357 /* ----------------------
1358  *      Alter Domain
1359  *
1360  * The fields are used in different ways by the different variants of
1361  * this command.
1362  * ----------------------
1363  */
1364 typedef struct AlterDomainStmt
1365 {
1366         NodeTag         type;
1367         char            subtype;                /*------------
1368                                                                  *      T = alter column default
1369                                                                  *      N = alter column drop not null
1370                                                                  *      O = alter column set not null
1371                                                                  *      C = add constraint
1372                                                                  *      X = drop constraint
1373                                                                  *------------
1374                                                                  */
1375         List       *typeName;           /* domain to work on */
1376         char       *name;                       /* column or constraint name to act on */
1377         Node       *def;                        /* definition of default or constraint */
1378         DropBehavior behavior;          /* RESTRICT or CASCADE for DROP cases */
1379         bool            missing_ok;             /* skip error if missing? */
1380 } AlterDomainStmt;
1381
1382
1383 /* ----------------------
1384  *              Grant|Revoke Statement
1385  * ----------------------
1386  */
1387 typedef enum GrantTargetType
1388 {
1389         ACL_TARGET_OBJECT,                      /* grant on specific named object(s) */
1390         ACL_TARGET_ALL_IN_SCHEMA,       /* grant on all objects in given schema(s) */
1391         ACL_TARGET_DEFAULTS                     /* ALTER DEFAULT PRIVILEGES */
1392 } GrantTargetType;
1393
1394 typedef enum GrantObjectType
1395 {
1396         ACL_OBJECT_COLUMN,                      /* column */
1397         ACL_OBJECT_RELATION,            /* table, view */
1398         ACL_OBJECT_SEQUENCE,            /* sequence */
1399         ACL_OBJECT_DATABASE,            /* database */
1400         ACL_OBJECT_DOMAIN,                      /* domain */
1401         ACL_OBJECT_FDW,                         /* foreign-data wrapper */
1402         ACL_OBJECT_FOREIGN_SERVER,      /* foreign server */
1403         ACL_OBJECT_FUNCTION,            /* function */
1404         ACL_OBJECT_LANGUAGE,            /* procedural language */
1405         ACL_OBJECT_LARGEOBJECT,         /* largeobject */
1406         ACL_OBJECT_NAMESPACE,           /* namespace */
1407         ACL_OBJECT_TABLESPACE,          /* tablespace */
1408         ACL_OBJECT_TYPE                         /* type */
1409 } GrantObjectType;
1410
1411 typedef struct GrantStmt
1412 {
1413         NodeTag         type;
1414         bool            is_grant;               /* true = GRANT, false = REVOKE */
1415         GrantTargetType targtype;       /* type of the grant target */
1416         GrantObjectType objtype;        /* kind of object being operated on */
1417         List       *objects;            /* list of RangeVar nodes, FuncWithArgs nodes,
1418                                                                  * or plain names (as Value strings) */
1419         List       *privileges;         /* list of AccessPriv nodes */
1420         /* privileges == NIL denotes ALL PRIVILEGES */
1421         List       *grantees;           /* list of PrivGrantee nodes */
1422         bool            grant_option;   /* grant or revoke grant option */
1423         DropBehavior behavior;          /* drop behavior (for REVOKE) */
1424 } GrantStmt;
1425
1426 typedef struct PrivGrantee
1427 {
1428         NodeTag         type;
1429         char       *rolname;            /* if NULL then PUBLIC */
1430 } PrivGrantee;
1431
1432 /*
1433  * Note: FuncWithArgs carries only the types of the input parameters of the
1434  * function.  So it is sufficient to identify an existing function, but it
1435  * is not enough info to define a function nor to call it.
1436  */
1437 typedef struct FuncWithArgs
1438 {
1439         NodeTag         type;
1440         List       *funcname;           /* qualified name of function */
1441         List       *funcargs;           /* list of Typename nodes */
1442 } FuncWithArgs;
1443
1444 /*
1445  * An access privilege, with optional list of column names
1446  * priv_name == NULL denotes ALL PRIVILEGES (only used with a column list)
1447  * cols == NIL denotes "all columns"
1448  * Note that simple "ALL PRIVILEGES" is represented as a NIL list, not
1449  * an AccessPriv with both fields null.
1450  */
1451 typedef struct AccessPriv
1452 {
1453         NodeTag         type;
1454         char       *priv_name;          /* string name of privilege */
1455         List       *cols;                       /* list of Value strings */
1456 } AccessPriv;
1457
1458 /* ----------------------
1459  *              Grant/Revoke Role Statement
1460  *
1461  * Note: because of the parsing ambiguity with the GRANT <privileges>
1462  * statement, granted_roles is a list of AccessPriv; the execution code
1463  * should complain if any column lists appear.  grantee_roles is a list
1464  * of role names, as Value strings.
1465  * ----------------------
1466  */
1467 typedef struct GrantRoleStmt
1468 {
1469         NodeTag         type;
1470         List       *granted_roles;      /* list of roles to be granted/revoked */
1471         List       *grantee_roles;      /* list of member roles to add/delete */
1472         bool            is_grant;               /* true = GRANT, false = REVOKE */
1473         bool            admin_opt;              /* with admin option */
1474         char       *grantor;            /* set grantor to other than current role */
1475         DropBehavior behavior;          /* drop behavior (for REVOKE) */
1476 } GrantRoleStmt;
1477
1478 /* ----------------------
1479  *      Alter Default Privileges Statement
1480  * ----------------------
1481  */
1482 typedef struct AlterDefaultPrivilegesStmt
1483 {
1484         NodeTag         type;
1485         List       *options;            /* list of DefElem */
1486         GrantStmt  *action;                     /* GRANT/REVOKE action (with objects=NIL) */
1487 } AlterDefaultPrivilegesStmt;
1488
1489 /* ----------------------
1490  *              Copy Statement
1491  *
1492  * We support "COPY relation FROM file", "COPY relation TO file", and
1493  * "COPY (query) TO file".  In any given CopyStmt, exactly one of "relation"
1494  * and "query" must be non-NULL.
1495  * ----------------------
1496  */
1497 typedef struct CopyStmt
1498 {
1499         NodeTag         type;
1500         RangeVar   *relation;           /* the relation to copy */
1501         Node       *query;                      /* the SELECT query to copy */
1502         List       *attlist;            /* List of column names (as Strings), or NIL
1503                                                                  * for all columns */
1504         bool            is_from;                /* TO or FROM */
1505         bool            is_program;             /* is 'filename' a program to popen? */
1506         char       *filename;           /* filename, or NULL for STDIN/STDOUT */
1507         List       *options;            /* List of DefElem nodes */
1508 } CopyStmt;
1509
1510 /* ----------------------
1511  * SET Statement (includes RESET)
1512  *
1513  * "SET var TO DEFAULT" and "RESET var" are semantically equivalent, but we
1514  * preserve the distinction in VariableSetKind for CreateCommandTag().
1515  * ----------------------
1516  */
1517 typedef enum
1518 {
1519         VAR_SET_VALUE,                          /* SET var = value */
1520         VAR_SET_DEFAULT,                        /* SET var TO DEFAULT */
1521         VAR_SET_CURRENT,                        /* SET var FROM CURRENT */
1522         VAR_SET_MULTI,                          /* special case for SET TRANSACTION ... */
1523         VAR_RESET,                                      /* RESET var */
1524         VAR_RESET_ALL                           /* RESET ALL */
1525 } VariableSetKind;
1526
1527 typedef struct VariableSetStmt
1528 {
1529         NodeTag         type;
1530         VariableSetKind kind;
1531         char       *name;                       /* variable to be set */
1532         List       *args;                       /* List of A_Const nodes */
1533         bool            is_local;               /* SET LOCAL? */
1534 } VariableSetStmt;
1535
1536 /* ----------------------
1537  * Show Statement
1538  * ----------------------
1539  */
1540 typedef struct VariableShowStmt
1541 {
1542         NodeTag         type;
1543         char       *name;
1544 } VariableShowStmt;
1545
1546 /* ----------------------
1547  *              Create Table Statement
1548  *
1549  * NOTE: in the raw gram.y output, ColumnDef and Constraint nodes are
1550  * intermixed in tableElts, and constraints is NIL.  After parse analysis,
1551  * tableElts contains just ColumnDefs, and constraints contains just
1552  * Constraint nodes (in fact, only CONSTR_CHECK nodes, in the present
1553  * implementation).
1554  * ----------------------
1555  */
1556
1557 typedef struct CreateStmt
1558 {
1559         NodeTag         type;
1560         RangeVar   *relation;           /* relation to create */
1561         List       *tableElts;          /* column definitions (list of ColumnDef) */
1562         List       *inhRelations;       /* relations to inherit from (list of
1563                                                                  * inhRelation) */
1564         TypeName   *ofTypename;         /* OF typename */
1565         List       *constraints;        /* constraints (list of Constraint nodes) */
1566         List       *options;            /* options from WITH clause */
1567         OnCommitAction oncommit;        /* what do we do at COMMIT? */
1568         char       *tablespacename; /* table space to use, or NULL */
1569         bool            if_not_exists;  /* just do nothing if it already exists? */
1570 } CreateStmt;
1571
1572 /* ----------
1573  * Definitions for constraints in CreateStmt
1574  *
1575  * Note that column defaults are treated as a type of constraint,
1576  * even though that's a bit odd semantically.
1577  *
1578  * For constraints that use expressions (CONSTR_CHECK, CONSTR_DEFAULT)
1579  * we may have the expression in either "raw" form (an untransformed
1580  * parse tree) or "cooked" form (the nodeToString representation of
1581  * an executable expression tree), depending on how this Constraint
1582  * node was created (by parsing, or by inheritance from an existing
1583  * relation).  We should never have both in the same node!
1584  *
1585  * FKCONSTR_ACTION_xxx values are stored into pg_constraint.confupdtype
1586  * and pg_constraint.confdeltype columns; FKCONSTR_MATCH_xxx values are
1587  * stored into pg_constraint.confmatchtype.  Changing the code values may
1588  * require an initdb!
1589  *
1590  * If skip_validation is true then we skip checking that the existing rows
1591  * in the table satisfy the constraint, and just install the catalog entries
1592  * for the constraint.  A new FK constraint is marked as valid iff
1593  * initially_valid is true.  (Usually skip_validation and initially_valid
1594  * are inverses, but we can set both true if the table is known empty.)
1595  *
1596  * Constraint attributes (DEFERRABLE etc) are initially represented as
1597  * separate Constraint nodes for simplicity of parsing.  parse_utilcmd.c makes
1598  * a pass through the constraints list to insert the info into the appropriate
1599  * Constraint node.
1600  * ----------
1601  */
1602
1603 typedef enum ConstrType                 /* types of constraints */
1604 {
1605         CONSTR_NULL,                            /* not standard SQL, but a lot of people
1606                                                                  * expect it */
1607         CONSTR_NOTNULL,
1608         CONSTR_DEFAULT,
1609         CONSTR_CHECK,
1610         CONSTR_PRIMARY,
1611         CONSTR_UNIQUE,
1612         CONSTR_EXCLUSION,
1613         CONSTR_FOREIGN,
1614         CONSTR_ATTR_DEFERRABLE,         /* attributes for previous constraint node */
1615         CONSTR_ATTR_NOT_DEFERRABLE,
1616         CONSTR_ATTR_DEFERRED,
1617         CONSTR_ATTR_IMMEDIATE
1618 } ConstrType;
1619
1620 /* Foreign key action codes */
1621 #define FKCONSTR_ACTION_NOACTION        'a'
1622 #define FKCONSTR_ACTION_RESTRICT        'r'
1623 #define FKCONSTR_ACTION_CASCADE         'c'
1624 #define FKCONSTR_ACTION_SETNULL         'n'
1625 #define FKCONSTR_ACTION_SETDEFAULT      'd'
1626
1627 /* Foreign key matchtype codes */
1628 #define FKCONSTR_MATCH_FULL                     'f'
1629 #define FKCONSTR_MATCH_PARTIAL          'p'
1630 #define FKCONSTR_MATCH_SIMPLE           's'
1631
1632 typedef struct Constraint
1633 {
1634         NodeTag         type;
1635         ConstrType      contype;                /* see above */
1636
1637         /* Fields used for most/all constraint types: */
1638         char       *conname;            /* Constraint name, or NULL if unnamed */
1639         bool            deferrable;             /* DEFERRABLE? */
1640         bool            initdeferred;   /* INITIALLY DEFERRED? */
1641         int                     location;               /* token location, or -1 if unknown */
1642
1643         /* Fields used for constraints with expressions (CHECK and DEFAULT): */
1644         bool            is_no_inherit;  /* is constraint non-inheritable? */
1645         Node       *raw_expr;           /* expr, as untransformed parse tree */
1646         char       *cooked_expr;        /* expr, as nodeToString representation */
1647
1648         /* Fields used for unique constraints (UNIQUE and PRIMARY KEY): */
1649         List       *keys;                       /* String nodes naming referenced column(s) */
1650
1651         /* Fields used for EXCLUSION constraints: */
1652         List       *exclusions;         /* list of (IndexElem, operator name) pairs */
1653
1654         /* Fields used for index constraints (UNIQUE, PRIMARY KEY, EXCLUSION): */
1655         List       *options;            /* options from WITH clause */
1656         char       *indexname;          /* existing index to use; otherwise NULL */
1657         char       *indexspace;         /* index tablespace; NULL for default */
1658         /* These could be, but currently are not, used for UNIQUE/PKEY: */
1659         char       *access_method;      /* index access method; NULL for default */
1660         Node       *where_clause;       /* partial index predicate */
1661
1662         /* Fields used for FOREIGN KEY constraints: */
1663         RangeVar   *pktable;            /* Primary key table */
1664         List       *fk_attrs;           /* Attributes of foreign key */
1665         List       *pk_attrs;           /* Corresponding attrs in PK table */
1666         char            fk_matchtype;   /* FULL, PARTIAL, SIMPLE */
1667         char            fk_upd_action;  /* ON UPDATE action */
1668         char            fk_del_action;  /* ON DELETE action */
1669         List       *old_conpfeqop;      /* pg_constraint.conpfeqop of my former self */
1670         Oid                     old_pktable_oid;        /* pg_constraint.confrelid of my former self */
1671
1672         /* Fields used for constraints that allow a NOT VALID specification */
1673         bool            skip_validation;        /* skip validation of existing rows? */
1674         bool            initially_valid;        /* mark the new constraint as valid? */
1675 } Constraint;
1676
1677 /* ----------------------
1678  *              Create/Drop Table Space Statements
1679  * ----------------------
1680  */
1681
1682 typedef struct CreateTableSpaceStmt
1683 {
1684         NodeTag         type;
1685         char       *tablespacename;
1686         char       *owner;
1687         char       *location;
1688         List       *options;
1689 } CreateTableSpaceStmt;
1690
1691 typedef struct DropTableSpaceStmt
1692 {
1693         NodeTag         type;
1694         char       *tablespacename;
1695         bool            missing_ok;             /* skip error if missing? */
1696 } DropTableSpaceStmt;
1697
1698 typedef struct AlterTableSpaceOptionsStmt
1699 {
1700         NodeTag         type;
1701         char       *tablespacename;
1702         List       *options;
1703         bool            isReset;
1704 } AlterTableSpaceOptionsStmt;
1705
1706 typedef struct AlterTableSpaceMoveStmt
1707 {
1708         NodeTag         type;
1709         char       *orig_tablespacename;
1710         ObjectType      objtype;                /* set to -1 if move_all is true */
1711         bool            move_all;               /* move all, or just objtype objects? */
1712         List       *roles;                      /* List of roles to move objects of */
1713         char       *new_tablespacename;
1714         bool            nowait;
1715 } AlterTableSpaceMoveStmt;
1716
1717 /* ----------------------
1718  *              Create/Alter Extension Statements
1719  * ----------------------
1720  */
1721
1722 typedef struct CreateExtensionStmt
1723 {
1724         NodeTag         type;
1725         char       *extname;
1726         bool            if_not_exists;  /* just do nothing if it already exists? */
1727         List       *options;            /* List of DefElem nodes */
1728 } CreateExtensionStmt;
1729
1730 /* Only used for ALTER EXTENSION UPDATE; later might need an action field */
1731 typedef struct AlterExtensionStmt
1732 {
1733         NodeTag         type;
1734         char       *extname;
1735         List       *options;            /* List of DefElem nodes */
1736 } AlterExtensionStmt;
1737
1738 typedef struct AlterExtensionContentsStmt
1739 {
1740         NodeTag         type;
1741         char       *extname;            /* Extension's name */
1742         int                     action;                 /* +1 = add object, -1 = drop object */
1743         ObjectType      objtype;                /* Object's type */
1744         List       *objname;            /* Qualified name of the object */
1745         List       *objargs;            /* Arguments if needed (eg, for functions) */
1746 } AlterExtensionContentsStmt;
1747
1748 /* ----------------------
1749  *              Create/Alter FOREIGN DATA WRAPPER Statements
1750  * ----------------------
1751  */
1752
1753 typedef struct CreateFdwStmt
1754 {
1755         NodeTag         type;
1756         char       *fdwname;            /* foreign-data wrapper name */
1757         List       *func_options;       /* HANDLER/VALIDATOR options */
1758         List       *options;            /* generic options to FDW */
1759 } CreateFdwStmt;
1760
1761 typedef struct AlterFdwStmt
1762 {
1763         NodeTag         type;
1764         char       *fdwname;            /* foreign-data wrapper name */
1765         List       *func_options;       /* HANDLER/VALIDATOR options */
1766         List       *options;            /* generic options to FDW */
1767 } AlterFdwStmt;
1768
1769 /* ----------------------
1770  *              Create/Alter FOREIGN SERVER Statements
1771  * ----------------------
1772  */
1773
1774 typedef struct CreateForeignServerStmt
1775 {
1776         NodeTag         type;
1777         char       *servername;         /* server name */
1778         char       *servertype;         /* optional server type */
1779         char       *version;            /* optional server version */
1780         char       *fdwname;            /* FDW name */
1781         List       *options;            /* generic options to server */
1782 } CreateForeignServerStmt;
1783
1784 typedef struct AlterForeignServerStmt
1785 {
1786         NodeTag         type;
1787         char       *servername;         /* server name */
1788         char       *version;            /* optional server version */
1789         List       *options;            /* generic options to server */
1790         bool            has_version;    /* version specified */
1791 } AlterForeignServerStmt;
1792
1793 /* ----------------------
1794  *              Create FOREIGN TABLE Statement
1795  * ----------------------
1796  */
1797
1798 typedef struct CreateForeignTableStmt
1799 {
1800         CreateStmt      base;
1801         char       *servername;
1802         List       *options;
1803 } CreateForeignTableStmt;
1804
1805 /* ----------------------
1806  *              Create/Drop USER MAPPING Statements
1807  * ----------------------
1808  */
1809
1810 typedef struct CreateUserMappingStmt
1811 {
1812         NodeTag         type;
1813         char       *username;           /* username or PUBLIC/CURRENT_USER */
1814         char       *servername;         /* server name */
1815         List       *options;            /* generic options to server */
1816 } CreateUserMappingStmt;
1817
1818 typedef struct AlterUserMappingStmt
1819 {
1820         NodeTag         type;
1821         char       *username;           /* username or PUBLIC/CURRENT_USER */
1822         char       *servername;         /* server name */
1823         List       *options;            /* generic options to server */
1824 } AlterUserMappingStmt;
1825
1826 typedef struct DropUserMappingStmt
1827 {
1828         NodeTag         type;
1829         char       *username;           /* username or PUBLIC/CURRENT_USER */
1830         char       *servername;         /* server name */
1831         bool            missing_ok;             /* ignore missing mappings */
1832 } DropUserMappingStmt;
1833
1834 /* ----------------------
1835  *              Import Foreign Schema Statement
1836  * ----------------------
1837  */
1838
1839 typedef enum ImportForeignSchemaType
1840 {
1841         FDW_IMPORT_SCHEMA_ALL,          /* all relations wanted */
1842         FDW_IMPORT_SCHEMA_LIMIT_TO, /* include only listed tables in import */
1843         FDW_IMPORT_SCHEMA_EXCEPT        /* exclude listed tables from import */
1844 } ImportForeignSchemaType;
1845
1846 typedef struct ImportForeignSchemaStmt
1847 {
1848         NodeTag         type;
1849         char       *server_name;        /* FDW server name */
1850         char       *remote_schema;      /* remote schema name to query */
1851         char       *local_schema;       /* local schema to create objects in */
1852         ImportForeignSchemaType list_type;      /* type of table list */
1853         List       *table_list;         /* List of RangeVar */
1854         List       *options;            /* list of options to pass to FDW */
1855 } ImportForeignSchemaStmt;
1856
1857 /* ----------------------
1858  *              Create TRIGGER Statement
1859  * ----------------------
1860  */
1861 typedef struct CreateTrigStmt
1862 {
1863         NodeTag         type;
1864         char       *trigname;           /* TRIGGER's name */
1865         RangeVar   *relation;           /* relation trigger is on */
1866         List       *funcname;           /* qual. name of function to call */
1867         List       *args;                       /* list of (T_String) Values or NIL */
1868         bool            row;                    /* ROW/STATEMENT */
1869         /* timing uses the TRIGGER_TYPE bits defined in catalog/pg_trigger.h */
1870         int16           timing;                 /* BEFORE, AFTER, or INSTEAD */
1871         /* events uses the TRIGGER_TYPE bits defined in catalog/pg_trigger.h */
1872         int16           events;                 /* "OR" of INSERT/UPDATE/DELETE/TRUNCATE */
1873         List       *columns;            /* column names, or NIL for all columns */
1874         Node       *whenClause;         /* qual expression, or NULL if none */
1875         bool            isconstraint;   /* This is a constraint trigger */
1876         /* The remaining fields are only used for constraint triggers */
1877         bool            deferrable;             /* [NOT] DEFERRABLE */
1878         bool            initdeferred;   /* INITIALLY {DEFERRED|IMMEDIATE} */
1879         RangeVar   *constrrel;          /* opposite relation, if RI trigger */
1880 } CreateTrigStmt;
1881
1882 /* ----------------------
1883  *              Create EVENT TRIGGER Statement
1884  * ----------------------
1885  */
1886 typedef struct CreateEventTrigStmt
1887 {
1888         NodeTag         type;
1889         char       *trigname;           /* TRIGGER's name */
1890         char       *eventname;          /* event's identifier */
1891         List       *whenclause;         /* list of DefElems indicating filtering */
1892         List       *funcname;           /* qual. name of function to call */
1893 } CreateEventTrigStmt;
1894
1895 /* ----------------------
1896  *              Alter EVENT TRIGGER Statement
1897  * ----------------------
1898  */
1899 typedef struct AlterEventTrigStmt
1900 {
1901         NodeTag         type;
1902         char       *trigname;           /* TRIGGER's name */
1903         char            tgenabled;              /* trigger's firing configuration WRT
1904                                                                  * session_replication_role */
1905 } AlterEventTrigStmt;
1906
1907 /* ----------------------
1908  *              Create/Drop PROCEDURAL LANGUAGE Statements
1909  *              Create PROCEDURAL LANGUAGE Statements
1910  * ----------------------
1911  */
1912 typedef struct CreatePLangStmt
1913 {
1914         NodeTag         type;
1915         bool            replace;                /* T => replace if already exists */
1916         char       *plname;                     /* PL name */
1917         List       *plhandler;          /* PL call handler function (qual. name) */
1918         List       *plinline;           /* optional inline function (qual. name) */
1919         List       *plvalidator;        /* optional validator function (qual. name) */
1920         bool            pltrusted;              /* PL is trusted */
1921 } CreatePLangStmt;
1922
1923 /* ----------------------
1924  *      Create/Alter/Drop Role Statements
1925  *
1926  * Note: these node types are also used for the backwards-compatible
1927  * Create/Alter/Drop User/Group statements.  In the ALTER and DROP cases
1928  * there's really no need to distinguish what the original spelling was,
1929  * but for CREATE we mark the type because the defaults vary.
1930  * ----------------------
1931  */
1932 typedef enum RoleStmtType
1933 {
1934         ROLESTMT_ROLE,
1935         ROLESTMT_USER,
1936         ROLESTMT_GROUP
1937 } RoleStmtType;
1938
1939 typedef struct CreateRoleStmt
1940 {
1941         NodeTag         type;
1942         RoleStmtType stmt_type;         /* ROLE/USER/GROUP */
1943         char       *role;                       /* role name */
1944         List       *options;            /* List of DefElem nodes */
1945 } CreateRoleStmt;
1946
1947 typedef struct AlterRoleStmt
1948 {
1949         NodeTag         type;
1950         char       *role;                       /* role name */
1951         List       *options;            /* List of DefElem nodes */
1952         int                     action;                 /* +1 = add members, -1 = drop members */
1953 } AlterRoleStmt;
1954
1955 typedef struct AlterRoleSetStmt
1956 {
1957         NodeTag         type;
1958         char       *role;                       /* role name */
1959         char       *database;           /* database name, or NULL */
1960         VariableSetStmt *setstmt;       /* SET or RESET subcommand */
1961 } AlterRoleSetStmt;
1962
1963 typedef struct DropRoleStmt
1964 {
1965         NodeTag         type;
1966         List       *roles;                      /* List of roles to remove */
1967         bool            missing_ok;             /* skip error if a role is missing? */
1968 } DropRoleStmt;
1969
1970 /* ----------------------
1971  *              {Create|Alter} SEQUENCE Statement
1972  * ----------------------
1973  */
1974
1975 typedef struct CreateSeqStmt
1976 {
1977         NodeTag         type;
1978         RangeVar   *sequence;           /* the sequence to create */
1979         List       *options;
1980         Oid                     ownerId;                /* ID of owner, or InvalidOid for default */
1981 } CreateSeqStmt;
1982
1983 typedef struct AlterSeqStmt
1984 {
1985         NodeTag         type;
1986         RangeVar   *sequence;           /* the sequence to alter */
1987         List       *options;
1988         bool            missing_ok;             /* skip error if a role is missing? */
1989 } AlterSeqStmt;
1990
1991 /* ----------------------
1992  *              Create {Aggregate|Operator|Type} Statement
1993  * ----------------------
1994  */
1995 typedef struct DefineStmt
1996 {
1997         NodeTag         type;
1998         ObjectType      kind;                   /* aggregate, operator, type */
1999         bool            oldstyle;               /* hack to signal old CREATE AGG syntax */
2000         List       *defnames;           /* qualified name (list of Value strings) */
2001         List       *args;                       /* a list of TypeName (if needed) */
2002         List       *definition;         /* a list of DefElem */
2003 } DefineStmt;
2004
2005 /* ----------------------
2006  *              Create Domain Statement
2007  * ----------------------
2008  */
2009 typedef struct CreateDomainStmt
2010 {
2011         NodeTag         type;
2012         List       *domainname;         /* qualified name (list of Value strings) */
2013         TypeName   *typeName;           /* the base type */
2014         CollateClause *collClause;      /* untransformed COLLATE spec, if any */
2015         List       *constraints;        /* constraints (list of Constraint nodes) */
2016 } CreateDomainStmt;
2017
2018 /* ----------------------
2019  *              Create Operator Class Statement
2020  * ----------------------
2021  */
2022 typedef struct CreateOpClassStmt
2023 {
2024         NodeTag         type;
2025         List       *opclassname;        /* qualified name (list of Value strings) */
2026         List       *opfamilyname;       /* qualified name (ditto); NIL if omitted */
2027         char       *amname;                     /* name of index AM opclass is for */
2028         TypeName   *datatype;           /* datatype of indexed column */
2029         List       *items;                      /* List of CreateOpClassItem nodes */
2030         bool            isDefault;              /* Should be marked as default for type? */
2031 } CreateOpClassStmt;
2032
2033 #define OPCLASS_ITEM_OPERATOR           1
2034 #define OPCLASS_ITEM_FUNCTION           2
2035 #define OPCLASS_ITEM_STORAGETYPE        3
2036
2037 typedef struct CreateOpClassItem
2038 {
2039         NodeTag         type;
2040         int                     itemtype;               /* see codes above */
2041         /* fields used for an operator or function item: */
2042         List       *name;                       /* operator or function name */
2043         List       *args;                       /* argument types */
2044         int                     number;                 /* strategy num or support proc num */
2045         List       *order_family;       /* only used for ordering operators */
2046         List       *class_args;         /* only used for functions */
2047         /* fields used for a storagetype item: */
2048         TypeName   *storedtype;         /* datatype stored in index */
2049 } CreateOpClassItem;
2050
2051 /* ----------------------
2052  *              Create Operator Family Statement
2053  * ----------------------
2054  */
2055 typedef struct CreateOpFamilyStmt
2056 {
2057         NodeTag         type;
2058         List       *opfamilyname;       /* qualified name (list of Value strings) */
2059         char       *amname;                     /* name of index AM opfamily is for */
2060 } CreateOpFamilyStmt;
2061
2062 /* ----------------------
2063  *              Alter Operator Family Statement
2064  * ----------------------
2065  */
2066 typedef struct AlterOpFamilyStmt
2067 {
2068         NodeTag         type;
2069         List       *opfamilyname;       /* qualified name (list of Value strings) */
2070         char       *amname;                     /* name of index AM opfamily is for */
2071         bool            isDrop;                 /* ADD or DROP the items? */
2072         List       *items;                      /* List of CreateOpClassItem nodes */
2073 } AlterOpFamilyStmt;
2074
2075 /* ----------------------
2076  *              Drop Table|Sequence|View|Index|Type|Domain|Conversion|Schema Statement
2077  * ----------------------
2078  */
2079
2080 typedef struct DropStmt
2081 {
2082         NodeTag         type;
2083         List       *objects;            /* list of sublists of names (as Values) */
2084         List       *arguments;          /* list of sublists of arguments (as Values) */
2085         ObjectType      removeType;             /* object type */
2086         DropBehavior behavior;          /* RESTRICT or CASCADE behavior */
2087         bool            missing_ok;             /* skip error if object is missing? */
2088         bool            concurrent;             /* drop index concurrently? */
2089 } DropStmt;
2090
2091 /* ----------------------
2092  *                              Truncate Table Statement
2093  * ----------------------
2094  */
2095 typedef struct TruncateStmt
2096 {
2097         NodeTag         type;
2098         List       *relations;          /* relations (RangeVars) to be truncated */
2099         bool            restart_seqs;   /* restart owned sequences? */
2100         DropBehavior behavior;          /* RESTRICT or CASCADE behavior */
2101 } TruncateStmt;
2102
2103 /* ----------------------
2104  *                              Comment On Statement
2105  * ----------------------
2106  */
2107 typedef struct CommentStmt
2108 {
2109         NodeTag         type;
2110         ObjectType      objtype;                /* Object's type */
2111         List       *objname;            /* Qualified name of the object */
2112         List       *objargs;            /* Arguments if needed (eg, for functions) */
2113         char       *comment;            /* Comment to insert, or NULL to remove */
2114 } CommentStmt;
2115
2116 /* ----------------------
2117  *                              SECURITY LABEL Statement
2118  * ----------------------
2119  */
2120 typedef struct SecLabelStmt
2121 {
2122         NodeTag         type;
2123         ObjectType      objtype;                /* Object's type */
2124         List       *objname;            /* Qualified name of the object */
2125         List       *objargs;            /* Arguments if needed (eg, for functions) */
2126         char       *provider;           /* Label provider (or NULL) */
2127         char       *label;                      /* New security label to be assigned */
2128 } SecLabelStmt;
2129
2130 /* ----------------------
2131  *              Declare Cursor Statement
2132  *
2133  * Note: the "query" field of DeclareCursorStmt is only used in the raw grammar
2134  * output.  After parse analysis it's set to null, and the Query points to the
2135  * DeclareCursorStmt, not vice versa.
2136  * ----------------------
2137  */
2138 #define CURSOR_OPT_BINARY               0x0001  /* BINARY */
2139 #define CURSOR_OPT_SCROLL               0x0002  /* SCROLL explicitly given */
2140 #define CURSOR_OPT_NO_SCROLL    0x0004  /* NO SCROLL explicitly given */
2141 #define CURSOR_OPT_INSENSITIVE  0x0008  /* INSENSITIVE */
2142 #define CURSOR_OPT_HOLD                 0x0010  /* WITH HOLD */
2143 /* these planner-control flags do not correspond to any SQL grammar: */
2144 #define CURSOR_OPT_FAST_PLAN    0x0020  /* prefer fast-start plan */
2145 #define CURSOR_OPT_GENERIC_PLAN 0x0040  /* force use of generic plan */
2146 #define CURSOR_OPT_CUSTOM_PLAN  0x0080  /* force use of custom plan */
2147
2148 typedef struct DeclareCursorStmt
2149 {
2150         NodeTag         type;
2151         char       *portalname;         /* name of the portal (cursor) */
2152         int                     options;                /* bitmask of options (see above) */
2153         Node       *query;                      /* the raw SELECT query */
2154 } DeclareCursorStmt;
2155
2156 /* ----------------------
2157  *              Close Portal Statement
2158  * ----------------------
2159  */
2160 typedef struct ClosePortalStmt
2161 {
2162         NodeTag         type;
2163         char       *portalname;         /* name of the portal (cursor) */
2164         /* NULL means CLOSE ALL */
2165 } ClosePortalStmt;
2166
2167 /* ----------------------
2168  *              Fetch Statement (also Move)
2169  * ----------------------
2170  */
2171 typedef enum FetchDirection
2172 {
2173         /* for these, howMany is how many rows to fetch; FETCH_ALL means ALL */
2174         FETCH_FORWARD,
2175         FETCH_BACKWARD,
2176         /* for these, howMany indicates a position; only one row is fetched */
2177         FETCH_ABSOLUTE,
2178         FETCH_RELATIVE
2179 } FetchDirection;
2180
2181 #define FETCH_ALL       LONG_MAX
2182
2183 typedef struct FetchStmt
2184 {
2185         NodeTag         type;
2186         FetchDirection direction;       /* see above */
2187         long            howMany;                /* number of rows, or position argument */
2188         char       *portalname;         /* name of portal (cursor) */
2189         bool            ismove;                 /* TRUE if MOVE */
2190 } FetchStmt;
2191
2192 /* ----------------------
2193  *              Create Index Statement
2194  *
2195  * This represents creation of an index and/or an associated constraint.
2196  * If isconstraint is true, we should create a pg_constraint entry along
2197  * with the index.  But if indexOid isn't InvalidOid, we are not creating an
2198  * index, just a UNIQUE/PKEY constraint using an existing index.  isconstraint
2199  * must always be true in this case, and the fields describing the index
2200  * properties are empty.
2201  * ----------------------
2202  */
2203 typedef struct IndexStmt
2204 {
2205         NodeTag         type;
2206         char       *idxname;            /* name of new index, or NULL for default */
2207         RangeVar   *relation;           /* relation to build index on */
2208         char       *accessMethod;       /* name of access method (eg. btree) */
2209         char       *tableSpace;         /* tablespace, or NULL for default */
2210         List       *indexParams;        /* columns to index: a list of IndexElem */
2211         List       *options;            /* WITH clause options: a list of DefElem */
2212         Node       *whereClause;        /* qualification (partial-index predicate) */
2213         List       *excludeOpNames; /* exclusion operator names, or NIL if none */
2214         char       *idxcomment;         /* comment to apply to index, or NULL */
2215         Oid                     indexOid;               /* OID of an existing index, if any */
2216         Oid                     oldNode;                /* relfilenode of existing storage, if any */
2217         bool            unique;                 /* is index unique? */
2218         bool            primary;                /* is index a primary key? */
2219         bool            isconstraint;   /* is it for a pkey/unique constraint? */
2220         bool            deferrable;             /* is the constraint DEFERRABLE? */
2221         bool            initdeferred;   /* is the constraint INITIALLY DEFERRED? */
2222         bool            concurrent;             /* should this be a concurrent index build? */
2223 } IndexStmt;
2224
2225 /* ----------------------
2226  *              Create Function Statement
2227  * ----------------------
2228  */
2229 typedef struct CreateFunctionStmt
2230 {
2231         NodeTag         type;
2232         bool            replace;                /* T => replace if already exists */
2233         List       *funcname;           /* qualified name of function to create */
2234         List       *parameters;         /* a list of FunctionParameter */
2235         TypeName   *returnType;         /* the return type */
2236         List       *options;            /* a list of DefElem */
2237         List       *withClause;         /* a list of DefElem */
2238 } CreateFunctionStmt;
2239
2240 typedef enum FunctionParameterMode
2241 {
2242         /* the assigned enum values appear in pg_proc, don't change 'em! */
2243         FUNC_PARAM_IN = 'i',            /* input only */
2244         FUNC_PARAM_OUT = 'o',           /* output only */
2245         FUNC_PARAM_INOUT = 'b',         /* both */
2246         FUNC_PARAM_VARIADIC = 'v',      /* variadic (always input) */
2247         FUNC_PARAM_TABLE = 't'          /* table function output column */
2248 } FunctionParameterMode;
2249
2250 typedef struct FunctionParameter
2251 {
2252         NodeTag         type;
2253         char       *name;                       /* parameter name, or NULL if not given */
2254         TypeName   *argType;            /* TypeName for parameter type */
2255         FunctionParameterMode mode; /* IN/OUT/etc */
2256         Node       *defexpr;            /* raw default expr, or NULL if not given */
2257 } FunctionParameter;
2258
2259 typedef struct AlterFunctionStmt
2260 {
2261         NodeTag         type;
2262         FuncWithArgs *func;                     /* name and args of function */
2263         List       *actions;            /* list of DefElem */
2264 } AlterFunctionStmt;
2265
2266 /* ----------------------
2267  *              DO Statement
2268  *
2269  * DoStmt is the raw parser output, InlineCodeBlock is the execution-time API
2270  * ----------------------
2271  */
2272 typedef struct DoStmt
2273 {
2274         NodeTag         type;
2275         List       *args;                       /* List of DefElem nodes */
2276 } DoStmt;
2277
2278 typedef struct InlineCodeBlock
2279 {
2280         NodeTag         type;
2281         char       *source_text;        /* source text of anonymous code block */
2282         Oid                     langOid;                /* OID of selected language */
2283         bool            langIsTrusted;  /* trusted property of the language */
2284 } InlineCodeBlock;
2285
2286 /* ----------------------
2287  *              Alter Object Rename Statement
2288  * ----------------------
2289  */
2290 typedef struct RenameStmt
2291 {
2292         NodeTag         type;
2293         ObjectType      renameType;             /* OBJECT_TABLE, OBJECT_COLUMN, etc */
2294         ObjectType      relationType;   /* if column name, associated relation type */
2295         RangeVar   *relation;           /* in case it's a table */
2296         List       *object;                     /* in case it's some other object */
2297         List       *objarg;                     /* argument types, if applicable */
2298         char       *subname;            /* name of contained object (column, rule,
2299                                                                  * trigger, etc) */
2300         char       *newname;            /* the new name */
2301         DropBehavior behavior;          /* RESTRICT or CASCADE behavior */
2302         bool            missing_ok;             /* skip error if missing? */
2303 } RenameStmt;
2304
2305 /* ----------------------
2306  *              ALTER object SET SCHEMA Statement
2307  * ----------------------
2308  */
2309 typedef struct AlterObjectSchemaStmt
2310 {
2311         NodeTag         type;
2312         ObjectType objectType;          /* OBJECT_TABLE, OBJECT_TYPE, etc */
2313         RangeVar   *relation;           /* in case it's a table */
2314         List       *object;                     /* in case it's some other object */
2315         List       *objarg;                     /* argument types, if applicable */
2316         char       *newschema;          /* the new schema */
2317         bool            missing_ok;             /* skip error if missing? */
2318 } AlterObjectSchemaStmt;
2319
2320 /* ----------------------
2321  *              Alter Object Owner Statement
2322  * ----------------------
2323  */
2324 typedef struct AlterOwnerStmt
2325 {
2326         NodeTag         type;
2327         ObjectType objectType;          /* OBJECT_TABLE, OBJECT_TYPE, etc */
2328         RangeVar   *relation;           /* in case it's a table */
2329         List       *object;                     /* in case it's some other object */
2330         List       *objarg;                     /* argument types, if applicable */
2331         char       *newowner;           /* the new owner */
2332 } AlterOwnerStmt;
2333
2334
2335 /* ----------------------
2336  *              Create Rule Statement
2337  * ----------------------
2338  */
2339 typedef struct RuleStmt
2340 {
2341         NodeTag         type;
2342         RangeVar   *relation;           /* relation the rule is for */
2343         char       *rulename;           /* name of the rule */
2344         Node       *whereClause;        /* qualifications */
2345         CmdType         event;                  /* SELECT, INSERT, etc */
2346         bool            instead;                /* is a 'do instead'? */
2347         List       *actions;            /* the action statements */
2348         bool            replace;                /* OR REPLACE */
2349 } RuleStmt;
2350
2351 /* ----------------------
2352  *              Notify Statement
2353  * ----------------------
2354  */
2355 typedef struct NotifyStmt
2356 {
2357         NodeTag         type;
2358         char       *conditionname;      /* condition name to notify */
2359         char       *payload;            /* the payload string, or NULL if none */
2360 } NotifyStmt;
2361
2362 /* ----------------------
2363  *              Listen Statement
2364  * ----------------------
2365  */
2366 typedef struct ListenStmt
2367 {
2368         NodeTag         type;
2369         char       *conditionname;      /* condition name to listen on */
2370 } ListenStmt;
2371
2372 /* ----------------------
2373  *              Unlisten Statement
2374  * ----------------------
2375  */
2376 typedef struct UnlistenStmt
2377 {
2378         NodeTag         type;
2379         char       *conditionname;      /* name to unlisten on, or NULL for all */
2380 } UnlistenStmt;
2381
2382 /* ----------------------
2383  *              {Begin|Commit|Rollback} Transaction Statement
2384  * ----------------------
2385  */
2386 typedef enum TransactionStmtKind
2387 {
2388         TRANS_STMT_BEGIN,
2389         TRANS_STMT_START,                       /* semantically identical to BEGIN */
2390         TRANS_STMT_COMMIT,
2391         TRANS_STMT_ROLLBACK,
2392         TRANS_STMT_SAVEPOINT,
2393         TRANS_STMT_RELEASE,
2394         TRANS_STMT_ROLLBACK_TO,
2395         TRANS_STMT_PREPARE,
2396         TRANS_STMT_COMMIT_PREPARED,
2397         TRANS_STMT_ROLLBACK_PREPARED
2398 } TransactionStmtKind;
2399
2400 typedef struct TransactionStmt
2401 {
2402         NodeTag         type;
2403         TransactionStmtKind kind;       /* see above */
2404         List       *options;            /* for BEGIN/START and savepoint commands */
2405         char       *gid;                        /* for two-phase-commit related commands */
2406 } TransactionStmt;
2407
2408 /* ----------------------
2409  *              Create Type Statement, composite types
2410  * ----------------------
2411  */
2412 typedef struct CompositeTypeStmt
2413 {
2414         NodeTag         type;
2415         RangeVar   *typevar;            /* the composite type to be created */
2416         List       *coldeflist;         /* list of ColumnDef nodes */
2417 } CompositeTypeStmt;
2418
2419 /* ----------------------
2420  *              Create Type Statement, enum types
2421  * ----------------------
2422  */
2423 typedef struct CreateEnumStmt
2424 {
2425         NodeTag         type;
2426         List       *typeName;           /* qualified name (list of Value strings) */
2427         List       *vals;                       /* enum values (list of Value strings) */
2428 } CreateEnumStmt;
2429
2430 /* ----------------------
2431  *              Create Type Statement, range types
2432  * ----------------------
2433  */
2434 typedef struct CreateRangeStmt
2435 {
2436         NodeTag         type;
2437         List       *typeName;           /* qualified name (list of Value strings) */
2438         List       *params;                     /* range parameters (list of DefElem) */
2439 } CreateRangeStmt;
2440
2441 /* ----------------------
2442  *              Alter Type Statement, enum types
2443  * ----------------------
2444  */
2445 typedef struct AlterEnumStmt
2446 {
2447         NodeTag         type;
2448         List       *typeName;           /* qualified name (list of Value strings) */
2449         char       *newVal;                     /* new enum value's name */
2450         char       *newValNeighbor; /* neighboring enum value, if specified */
2451         bool            newValIsAfter;  /* place new enum value after neighbor? */
2452         bool            skipIfExists;   /* no error if label already exists */
2453 } AlterEnumStmt;
2454
2455 /* ----------------------
2456  *              Create View Statement
2457  * ----------------------
2458  */
2459 typedef enum ViewCheckOption
2460 {
2461         NO_CHECK_OPTION,
2462         LOCAL_CHECK_OPTION,
2463         CASCADED_CHECK_OPTION
2464 } ViewCheckOption;
2465
2466 typedef struct ViewStmt
2467 {
2468         NodeTag         type;
2469         RangeVar   *view;                       /* the view to be created */
2470         List       *aliases;            /* target column names */
2471         Node       *query;                      /* the SELECT query */
2472         bool            replace;                /* replace an existing view? */
2473         List       *options;            /* options from WITH clause */
2474         ViewCheckOption withCheckOption;        /* WITH CHECK OPTION */
2475 } ViewStmt;
2476
2477 /* ----------------------
2478  *              Load Statement
2479  * ----------------------
2480  */
2481 typedef struct LoadStmt
2482 {
2483         NodeTag         type;
2484         char       *filename;           /* file to load */
2485 } LoadStmt;
2486
2487 /* ----------------------
2488  *              Createdb Statement
2489  * ----------------------
2490  */
2491 typedef struct CreatedbStmt
2492 {
2493         NodeTag         type;
2494         char       *dbname;                     /* name of database to create */
2495         List       *options;            /* List of DefElem nodes */
2496 } CreatedbStmt;
2497
2498 /* ----------------------
2499  *      Alter Database
2500  * ----------------------
2501  */
2502 typedef struct AlterDatabaseStmt
2503 {
2504         NodeTag         type;
2505         char       *dbname;                     /* name of database to alter */
2506         List       *options;            /* List of DefElem nodes */
2507 } AlterDatabaseStmt;
2508
2509 typedef struct AlterDatabaseSetStmt
2510 {
2511         NodeTag         type;
2512         char       *dbname;                     /* database name */
2513         VariableSetStmt *setstmt;       /* SET or RESET subcommand */
2514 } AlterDatabaseSetStmt;
2515
2516 /* ----------------------
2517  *              Dropdb Statement
2518  * ----------------------
2519  */
2520 typedef struct DropdbStmt
2521 {
2522         NodeTag         type;
2523         char       *dbname;                     /* database to drop */
2524         bool            missing_ok;             /* skip error if db is missing? */
2525 } DropdbStmt;
2526
2527 /* ----------------------
2528  *              Alter System Statement
2529  * ----------------------
2530  */
2531 typedef struct AlterSystemStmt
2532 {
2533         NodeTag         type;
2534         VariableSetStmt *setstmt;       /* SET subcommand */
2535 } AlterSystemStmt;
2536
2537 /* ----------------------
2538  *              Cluster Statement (support pbrown's cluster index implementation)
2539  * ----------------------
2540  */
2541 typedef struct ClusterStmt
2542 {
2543         NodeTag         type;
2544         RangeVar   *relation;           /* relation being indexed, or NULL if all */
2545         char       *indexname;          /* original index defined */
2546         bool            verbose;                /* print progress info */
2547 } ClusterStmt;
2548
2549 /* ----------------------
2550  *              Vacuum and Analyze Statements
2551  *
2552  * Even though these are nominally two statements, it's convenient to use
2553  * just one node type for both.  Note that at least one of VACOPT_VACUUM
2554  * and VACOPT_ANALYZE must be set in options.  VACOPT_FREEZE is an internal
2555  * convenience for the grammar and is not examined at runtime --- the
2556  * freeze_min_age and freeze_table_age fields are what matter.
2557  * ----------------------
2558  */
2559 typedef enum VacuumOption
2560 {
2561         VACOPT_VACUUM = 1 << 0,         /* do VACUUM */
2562         VACOPT_ANALYZE = 1 << 1,        /* do ANALYZE */
2563         VACOPT_VERBOSE = 1 << 2,        /* print progress info */
2564         VACOPT_FREEZE = 1 << 3,         /* FREEZE option */
2565         VACOPT_FULL = 1 << 4,           /* FULL (non-concurrent) vacuum */
2566         VACOPT_NOWAIT = 1 << 5          /* don't wait to get lock (autovacuum only) */
2567 } VacuumOption;
2568
2569 typedef struct VacuumStmt
2570 {
2571         NodeTag         type;
2572         int                     options;                /* OR of VacuumOption flags */
2573         int                     freeze_min_age; /* min freeze age, or -1 to use default */
2574         int                     freeze_table_age;               /* age at which to scan whole table */
2575         int                     multixact_freeze_min_age;               /* min multixact freeze age,
2576                                                                                                  * or -1 to use default */
2577         int                     multixact_freeze_table_age;             /* multixact age at which to
2578                                                                                                  * scan whole table */
2579         RangeVar   *relation;           /* single table to process, or NULL */
2580         List       *va_cols;            /* list of column names, or NIL for all */
2581 } VacuumStmt;
2582
2583 /* ----------------------
2584  *              Explain Statement
2585  *
2586  * The "query" field is either a raw parse tree (SelectStmt, InsertStmt, etc)
2587  * or a Query node if parse analysis has been done.  Note that rewriting and
2588  * planning of the query are always postponed until execution of EXPLAIN.
2589  * ----------------------
2590  */
2591 typedef struct ExplainStmt
2592 {
2593         NodeTag         type;
2594         Node       *query;                      /* the query (see comments above) */
2595         List       *options;            /* list of DefElem nodes */
2596 } ExplainStmt;
2597
2598 /* ----------------------
2599  *              CREATE TABLE AS Statement (a/k/a SELECT INTO)
2600  *
2601  * A query written as CREATE TABLE AS will produce this node type natively.
2602  * A query written as SELECT ... INTO will be transformed to this form during
2603  * parse analysis.
2604  * A query written as CREATE MATERIALIZED view will produce this node type,
2605  * during parse analysis, since it needs all the same data.
2606  *
2607  * The "query" field is handled similarly to EXPLAIN, though note that it
2608  * can be a SELECT or an EXECUTE, but not other DML statements.
2609  * ----------------------
2610  */
2611 typedef struct CreateTableAsStmt
2612 {
2613         NodeTag         type;
2614         Node       *query;                      /* the query (see comments above) */
2615         IntoClause *into;                       /* destination table */
2616         ObjectType      relkind;                /* OBJECT_TABLE or OBJECT_MATVIEW */
2617         bool            is_select_into; /* it was written as SELECT INTO */
2618 } CreateTableAsStmt;
2619
2620 /* ----------------------
2621  *              REFRESH MATERIALIZED VIEW Statement
2622  * ----------------------
2623  */
2624 typedef struct RefreshMatViewStmt
2625 {
2626         NodeTag         type;
2627         bool            concurrent;             /* allow concurrent access? */
2628         bool            skipData;               /* true for WITH NO DATA */
2629         RangeVar   *relation;           /* relation to insert into */
2630 } RefreshMatViewStmt;
2631
2632 /* ----------------------
2633  * Checkpoint Statement
2634  * ----------------------
2635  */
2636 typedef struct CheckPointStmt
2637 {
2638         NodeTag         type;
2639 } CheckPointStmt;
2640
2641 /* ----------------------
2642  * Discard Statement
2643  * ----------------------
2644  */
2645
2646 typedef enum DiscardMode
2647 {
2648         DISCARD_ALL,
2649         DISCARD_PLANS,
2650         DISCARD_SEQUENCES,
2651         DISCARD_TEMP
2652 } DiscardMode;
2653
2654 typedef struct DiscardStmt
2655 {
2656         NodeTag         type;
2657         DiscardMode target;
2658 } DiscardStmt;
2659
2660 /* ----------------------
2661  *              LOCK Statement
2662  * ----------------------
2663  */
2664 typedef struct LockStmt
2665 {
2666         NodeTag         type;
2667         List       *relations;          /* relations to lock */
2668         int                     mode;                   /* lock mode */
2669         bool            nowait;                 /* no wait mode */
2670 } LockStmt;
2671
2672 /* ----------------------
2673  *              SET CONSTRAINTS Statement
2674  * ----------------------
2675  */
2676 typedef struct ConstraintsSetStmt
2677 {
2678         NodeTag         type;
2679         List       *constraints;        /* List of names as RangeVars */
2680         bool            deferred;
2681 } ConstraintsSetStmt;
2682
2683 /* ----------------------
2684  *              REINDEX Statement
2685  * ----------------------
2686  */
2687 typedef struct ReindexStmt
2688 {
2689         NodeTag         type;
2690         ObjectType      kind;                   /* OBJECT_INDEX, OBJECT_TABLE, etc. */
2691         RangeVar   *relation;           /* Table or index to reindex */
2692         const char *name;                       /* name of database to reindex */
2693         bool            do_system;              /* include system tables in database case */
2694         bool            do_user;                /* include user tables in database case */
2695 } ReindexStmt;
2696
2697 /* ----------------------
2698  *              CREATE CONVERSION Statement
2699  * ----------------------
2700  */
2701 typedef struct CreateConversionStmt
2702 {
2703         NodeTag         type;
2704         List       *conversion_name;    /* Name of the conversion */
2705         char       *for_encoding_name;          /* source encoding name */
2706         char       *to_encoding_name;           /* destination encoding name */
2707         List       *func_name;          /* qualified conversion function name */
2708         bool            def;                    /* is this a default conversion? */
2709 } CreateConversionStmt;
2710
2711 /* ----------------------
2712  *      CREATE CAST Statement
2713  * ----------------------
2714  */
2715 typedef struct CreateCastStmt
2716 {
2717         NodeTag         type;
2718         TypeName   *sourcetype;
2719         TypeName   *targettype;
2720         FuncWithArgs *func;
2721         CoercionContext context;
2722         bool            inout;
2723 } CreateCastStmt;
2724
2725 /* ----------------------
2726  *              PREPARE Statement
2727  * ----------------------
2728  */
2729 typedef struct PrepareStmt
2730 {
2731         NodeTag         type;
2732         char       *name;                       /* Name of plan, arbitrary */
2733         List       *argtypes;           /* Types of parameters (List of TypeName) */
2734         Node       *query;                      /* The query itself (as a raw parsetree) */
2735 } PrepareStmt;
2736
2737
2738 /* ----------------------
2739  *              EXECUTE Statement
2740  * ----------------------
2741  */
2742
2743 typedef struct ExecuteStmt
2744 {
2745         NodeTag         type;
2746         char       *name;                       /* The name of the plan to execute */
2747         List       *params;                     /* Values to assign to parameters */
2748 } ExecuteStmt;
2749
2750
2751 /* ----------------------
2752  *              DEALLOCATE Statement
2753  * ----------------------
2754  */
2755 typedef struct DeallocateStmt
2756 {
2757         NodeTag         type;
2758         char       *name;                       /* The name of the plan to remove */
2759         /* NULL means DEALLOCATE ALL */
2760 } DeallocateStmt;
2761
2762 /*
2763  *              DROP OWNED statement
2764  */
2765 typedef struct DropOwnedStmt
2766 {
2767         NodeTag         type;
2768         List       *roles;
2769         DropBehavior behavior;
2770 } DropOwnedStmt;
2771
2772 /*
2773  *              REASSIGN OWNED statement
2774  */
2775 typedef struct ReassignOwnedStmt
2776 {
2777         NodeTag         type;
2778         List       *roles;
2779         char       *newrole;
2780 } ReassignOwnedStmt;
2781
2782 /*
2783  * TS Dictionary stmts: DefineStmt, RenameStmt and DropStmt are default
2784  */
2785 typedef struct AlterTSDictionaryStmt
2786 {
2787         NodeTag         type;
2788         List       *dictname;           /* qualified name (list of Value strings) */
2789         List       *options;            /* List of DefElem nodes */
2790 } AlterTSDictionaryStmt;
2791
2792 /*
2793  * TS Configuration stmts: DefineStmt, RenameStmt and DropStmt are default
2794  */
2795 typedef struct AlterTSConfigurationStmt
2796 {
2797         NodeTag         type;
2798         List       *cfgname;            /* qualified name (list of Value strings) */
2799
2800         /*
2801          * dicts will be non-NIL if ADD/ALTER MAPPING was specified. If dicts is
2802          * NIL, but tokentype isn't, DROP MAPPING was specified.
2803          */
2804         List       *tokentype;          /* list of Value strings */
2805         List       *dicts;                      /* list of list of Value strings */
2806         bool            override;               /* if true - remove old variant */
2807         bool            replace;                /* if true - replace dictionary by another */
2808         bool            missing_ok;             /* for DROP - skip error if missing? */
2809 } AlterTSConfigurationStmt;
2810
2811 #endif   /* PARSENODES_H */