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