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