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