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