]> granicus.if.org Git - postgresql/blob - src/include/nodes/plannodes.h
4e655b0e6c1dfffb18bd0c9411736bc18cf0c4ba
[postgresql] / src / include / nodes / plannodes.h
1 /*-------------------------------------------------------------------------
2  *
3  * plannodes.h
4  *        definitions for query plan nodes
5  *
6  *
7  * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * src/include/nodes/plannodes.h
11  *
12  *-------------------------------------------------------------------------
13  */
14 #ifndef PLANNODES_H
15 #define PLANNODES_H
16
17 #include "access/sdir.h"
18 #include "lib/stringinfo.h"
19 #include "nodes/bitmapset.h"
20 #include "nodes/lockoptions.h"
21 #include "nodes/primnodes.h"
22
23
24 /* ----------------------------------------------------------------
25  *                                              node definitions
26  * ----------------------------------------------------------------
27  */
28
29 /* ----------------
30  *              PlannedStmt node
31  *
32  * The output of the planner is a Plan tree headed by a PlannedStmt node.
33  * PlannedStmt holds the "one time" information needed by the executor.
34  * ----------------
35  */
36 typedef struct PlannedStmt
37 {
38         NodeTag         type;
39
40         CmdType         commandType;    /* select|insert|update|delete */
41
42         uint32          queryId;                /* query identifier (copied from Query) */
43
44         bool            hasReturning;   /* is it insert|update|delete RETURNING? */
45
46         bool            hasModifyingCTE;        /* has insert|update|delete in WITH? */
47
48         bool            isUpsert;               /* is it insert ... ON CONFLICT UPDATE? */
49
50         bool            canSetTag;              /* do I set the command result tag? */
51
52         bool            transientPlan;  /* redo plan when TransactionXmin changes? */
53
54         struct Plan *planTree;          /* tree of Plan nodes */
55
56         List       *rtable;                     /* list of RangeTblEntry nodes */
57
58         /* rtable indexes of target relations for INSERT/UPDATE/DELETE */
59         List       *resultRelations;    /* integer list of RT indexes, or NIL */
60
61         Node       *utilityStmt;        /* non-null if this is DECLARE CURSOR */
62
63         List       *subplans;           /* Plan trees for SubPlan expressions */
64
65         Bitmapset  *rewindPlanIDs;      /* indices of subplans that require REWIND */
66
67         List       *rowMarks;           /* a list of PlanRowMark's */
68
69         List       *relationOids;       /* OIDs of relations the plan depends on */
70
71         List       *invalItems;         /* other dependencies, as PlanInvalItems */
72
73         int                     nParamExec;             /* number of PARAM_EXEC Params used */
74
75         bool            hasRowSecurity; /* row security applied? */
76
77 } PlannedStmt;
78
79 /* macro for fetching the Plan associated with a SubPlan node */
80 #define exec_subplan_get_plan(plannedstmt, subplan) \
81         ((Plan *) list_nth((plannedstmt)->subplans, (subplan)->plan_id - 1))
82
83
84 /* ----------------
85  *              Plan node
86  *
87  * All plan nodes "derive" from the Plan structure by having the
88  * Plan structure as the first field.  This ensures that everything works
89  * when nodes are cast to Plan's.  (node pointers are frequently cast to Plan*
90  * when passed around generically in the executor)
91  *
92  * We never actually instantiate any Plan nodes; this is just the common
93  * abstract superclass for all Plan-type nodes.
94  * ----------------
95  */
96 typedef struct Plan
97 {
98         NodeTag         type;
99
100         /*
101          * estimated execution costs for plan (see costsize.c for more info)
102          */
103         Cost            startup_cost;   /* cost expended before fetching any tuples */
104         Cost            total_cost;             /* total cost (assuming all tuples fetched) */
105
106         /*
107          * planner's estimate of result size of this plan step
108          */
109         double          plan_rows;              /* number of rows plan is expected to emit */
110         int                     plan_width;             /* average row width in bytes */
111
112         /*
113          * Common structural data for all Plan types.
114          */
115         List       *targetlist;         /* target list to be computed at this node */
116         List       *qual;                       /* implicitly-ANDed qual conditions */
117         struct Plan *lefttree;          /* input plan tree(s) */
118         struct Plan *righttree;
119         List       *initPlan;           /* Init Plan nodes (un-correlated expr
120                                                                  * subselects) */
121
122         /*
123          * Information for management of parameter-change-driven rescanning
124          *
125          * extParam includes the paramIDs of all external PARAM_EXEC params
126          * affecting this plan node or its children.  setParam params from the
127          * node's initPlans are not included, but their extParams are.
128          *
129          * allParam includes all the extParam paramIDs, plus the IDs of local
130          * params that affect the node (i.e., the setParams of its initplans).
131          * These are _all_ the PARAM_EXEC params that affect this node.
132          */
133         Bitmapset  *extParam;
134         Bitmapset  *allParam;
135 } Plan;
136
137 /* ----------------
138  *      these are defined to avoid confusion problems with "left"
139  *      and "right" and "inner" and "outer".  The convention is that
140  *      the "left" plan is the "outer" plan and the "right" plan is
141  *      the inner plan, but these make the code more readable.
142  * ----------------
143  */
144 #define innerPlan(node)                 (((Plan *)(node))->righttree)
145 #define outerPlan(node)                 (((Plan *)(node))->lefttree)
146
147
148 /* ----------------
149  *       Result node -
150  *              If no outer plan, evaluate a variable-free targetlist.
151  *              If outer plan, return tuples from outer plan (after a level of
152  *              projection as shown by targetlist).
153  *
154  * If resconstantqual isn't NULL, it represents a one-time qualification
155  * test (i.e., one that doesn't depend on any variables from the outer plan,
156  * so needs to be evaluated only once).
157  * ----------------
158  */
159 typedef struct Result
160 {
161         Plan            plan;
162         Node       *resconstantqual;
163 } Result;
164
165 /* ----------------
166  *       ModifyTable node -
167  *              Apply rows produced by subplan(s) to result table(s),
168  *              by inserting, updating, or deleting.
169  *
170  * Note that rowMarks and epqParam are presumed to be valid for all the
171  * subplan(s); they can't contain any info that varies across subplans.
172  * ----------------
173  */
174 typedef struct ModifyTable
175 {
176         Plan            plan;
177         CmdType         operation;              /* INSERT, UPDATE, or DELETE */
178         bool            canSetTag;              /* do we set the command tag/es_processed? */
179         Index           nominalRelation;        /* Parent RT index for use of EXPLAIN */
180         List       *resultRelations;    /* integer list of RT indexes */
181         int                     resultRelIndex; /* index of first resultRel in plan's list */
182         List       *plans;                      /* plan(s) producing source data */
183         List       *withCheckOptionLists;       /* per-target-table WCO lists */
184         List       *returningLists; /* per-target-table RETURNING tlists */
185         List       *fdwPrivLists;       /* per-target-table FDW private data lists */
186         List       *rowMarks;           /* PlanRowMarks (non-locking only) */
187         int                     epqParam;               /* ID of Param for EvalPlanQual re-eval */
188         OnConflictAction onConflictAction; /* ON CONFLICT action */
189         List       *arbiterIndexes;     /* List of ON CONFLICT arbiter index OIDs  */
190         List       *onConflictSet;      /* SET for INSERT ON CONFLICT DO UPDATE */
191         Node       *onConflictWhere;/* WHERE for ON CONFLICT UPDATE */
192         Index           exclRelRTI;             /* RTI of the EXCLUDED pseudo relation */
193         List       *exclRelTlist;       /* tlist of the EXCLUDED pseudo relation */
194 } ModifyTable;
195
196 /* ----------------
197  *       Append node -
198  *              Generate the concatenation of the results of sub-plans.
199  * ----------------
200  */
201 typedef struct Append
202 {
203         Plan            plan;
204         List       *appendplans;
205 } Append;
206
207 /* ----------------
208  *       MergeAppend node -
209  *              Merge the results of pre-sorted sub-plans to preserve the ordering.
210  * ----------------
211  */
212 typedef struct MergeAppend
213 {
214         Plan            plan;
215         List       *mergeplans;
216         /* remaining fields are just like the sort-key info in struct Sort */
217         int                     numCols;                /* number of sort-key columns */
218         AttrNumber *sortColIdx;         /* their indexes in the target list */
219         Oid                *sortOperators;      /* OIDs of operators to sort them by */
220         Oid                *collations;         /* OIDs of collations */
221         bool       *nullsFirst;         /* NULLS FIRST/LAST directions */
222 } MergeAppend;
223
224 /* ----------------
225  *      RecursiveUnion node -
226  *              Generate a recursive union of two subplans.
227  *
228  * The "outer" subplan is always the non-recursive term, and the "inner"
229  * subplan is the recursive term.
230  * ----------------
231  */
232 typedef struct RecursiveUnion
233 {
234         Plan            plan;
235         int                     wtParam;                /* ID of Param representing work table */
236         /* Remaining fields are zero/null in UNION ALL case */
237         int                     numCols;                /* number of columns to check for
238                                                                  * duplicate-ness */
239         AttrNumber *dupColIdx;          /* their indexes in the target list */
240         Oid                *dupOperators;       /* equality operators to compare with */
241         long            numGroups;              /* estimated number of groups in input */
242 } RecursiveUnion;
243
244 /* ----------------
245  *       BitmapAnd node -
246  *              Generate the intersection of the results of sub-plans.
247  *
248  * The subplans must be of types that yield tuple bitmaps.  The targetlist
249  * and qual fields of the plan are unused and are always NIL.
250  * ----------------
251  */
252 typedef struct BitmapAnd
253 {
254         Plan            plan;
255         List       *bitmapplans;
256 } BitmapAnd;
257
258 /* ----------------
259  *       BitmapOr node -
260  *              Generate the union of the results of sub-plans.
261  *
262  * The subplans must be of types that yield tuple bitmaps.  The targetlist
263  * and qual fields of the plan are unused and are always NIL.
264  * ----------------
265  */
266 typedef struct BitmapOr
267 {
268         Plan            plan;
269         List       *bitmapplans;
270 } BitmapOr;
271
272 /*
273  * ==========
274  * Scan nodes
275  * ==========
276  */
277 typedef struct Scan
278 {
279         Plan            plan;
280         Index           scanrelid;              /* relid is index into the range table */
281 } Scan;
282
283 /* ----------------
284  *              sequential scan node
285  * ----------------
286  */
287 typedef Scan SeqScan;
288
289 /* ----------------
290  *              table sample scan node
291  * ----------------
292  */
293 typedef Scan SampleScan;
294
295 /* ----------------
296  *              index scan node
297  *
298  * indexqualorig is an implicitly-ANDed list of index qual expressions, each
299  * in the same form it appeared in the query WHERE condition.  Each should
300  * be of the form (indexkey OP comparisonval) or (comparisonval OP indexkey).
301  * The indexkey is a Var or expression referencing column(s) of the index's
302  * base table.  The comparisonval might be any expression, but it won't use
303  * any columns of the base table.  The expressions are ordered by index
304  * column position (but items referencing the same index column can appear
305  * in any order).  indexqualorig is used at runtime only if we have to recheck
306  * a lossy indexqual.
307  *
308  * indexqual has the same form, but the expressions have been commuted if
309  * necessary to put the indexkeys on the left, and the indexkeys are replaced
310  * by Var nodes identifying the index columns (their varno is INDEX_VAR and
311  * their varattno is the index column number).
312  *
313  * indexorderbyorig is similarly the original form of any ORDER BY expressions
314  * that are being implemented by the index, while indexorderby is modified to
315  * have index column Vars on the left-hand side.  Here, multiple expressions
316  * must appear in exactly the ORDER BY order, and this is not necessarily the
317  * index column order.  Only the expressions are provided, not the auxiliary
318  * sort-order information from the ORDER BY SortGroupClauses; it's assumed
319  * that the sort ordering is fully determinable from the top-level operators.
320  * indexorderbyorig is used at runtime to recheck the ordering, if the index
321  * cannot calculate an accurate ordering.  It is also needed for EXPLAIN.
322  *
323  * indexorderbyops is an array of operators used to sort the ORDER BY
324  * expressions, used together with indexorderbyorig to recheck ordering at run
325  * time.  (Note these fields are used for amcanorderbyop cases, not amcanorder
326  * cases.)
327  *
328  * indexorderdir specifies the scan ordering, for indexscans on amcanorder
329  * indexes (for other indexes it should be "don't care").
330  * ----------------
331  */
332 typedef struct IndexScan
333 {
334         Scan            scan;
335         Oid                     indexid;                /* OID of index to scan */
336         List       *indexqual;          /* list of index quals (usually OpExprs) */
337         List       *indexqualorig;      /* the same in original form */
338         List       *indexorderby;       /* list of index ORDER BY exprs */
339         List       *indexorderbyorig;           /* the same in original form */
340         Oid                *indexorderbyops;    /* operators to sort ORDER BY exprs */
341         ScanDirection indexorderdir;    /* forward or backward or don't care */
342 } IndexScan;
343
344 /* ----------------
345  *              index-only scan node
346  *
347  * IndexOnlyScan is very similar to IndexScan, but it specifies an
348  * index-only scan, in which the data comes from the index not the heap.
349  * Because of this, *all* Vars in the plan node's targetlist, qual, and
350  * index expressions reference index columns and have varno = INDEX_VAR.
351  * Hence we do not need separate indexqualorig and indexorderbyorig lists,
352  * since their contents would be equivalent to indexqual and indexorderby.
353  *
354  * To help EXPLAIN interpret the index Vars for display, we provide
355  * indextlist, which represents the contents of the index as a targetlist
356  * with one TLE per index column.  Vars appearing in this list reference
357  * the base table, and this is the only field in the plan node that may
358  * contain such Vars.
359  * ----------------
360  */
361 typedef struct IndexOnlyScan
362 {
363         Scan            scan;
364         Oid                     indexid;                /* OID of index to scan */
365         List       *indexqual;          /* list of index quals (usually OpExprs) */
366         List       *indexorderby;       /* list of index ORDER BY exprs */
367         List       *indextlist;         /* TargetEntry list describing index's cols */
368         ScanDirection indexorderdir;    /* forward or backward or don't care */
369 } IndexOnlyScan;
370
371 /* ----------------
372  *              bitmap index scan node
373  *
374  * BitmapIndexScan delivers a bitmap of potential tuple locations;
375  * it does not access the heap itself.  The bitmap is used by an
376  * ancestor BitmapHeapScan node, possibly after passing through
377  * intermediate BitmapAnd and/or BitmapOr nodes to combine it with
378  * the results of other BitmapIndexScans.
379  *
380  * The fields have the same meanings as for IndexScan, except we don't
381  * store a direction flag because direction is uninteresting.
382  *
383  * In a BitmapIndexScan plan node, the targetlist and qual fields are
384  * not used and are always NIL.  The indexqualorig field is unused at
385  * run time too, but is saved for the benefit of EXPLAIN.
386  * ----------------
387  */
388 typedef struct BitmapIndexScan
389 {
390         Scan            scan;
391         Oid                     indexid;                /* OID of index to scan */
392         List       *indexqual;          /* list of index quals (OpExprs) */
393         List       *indexqualorig;      /* the same in original form */
394 } BitmapIndexScan;
395
396 /* ----------------
397  *              bitmap sequential scan node
398  *
399  * This needs a copy of the qual conditions being used by the input index
400  * scans because there are various cases where we need to recheck the quals;
401  * for example, when the bitmap is lossy about the specific rows on a page
402  * that meet the index condition.
403  * ----------------
404  */
405 typedef struct BitmapHeapScan
406 {
407         Scan            scan;
408         List       *bitmapqualorig; /* index quals, in standard expr form */
409 } BitmapHeapScan;
410
411 /* ----------------
412  *              tid scan node
413  *
414  * tidquals is an implicitly OR'ed list of qual expressions of the form
415  * "CTID = pseudoconstant" or "CTID = ANY(pseudoconstant_array)".
416  * ----------------
417  */
418 typedef struct TidScan
419 {
420         Scan            scan;
421         List       *tidquals;           /* qual(s) involving CTID = something */
422 } TidScan;
423
424 /* ----------------
425  *              subquery scan node
426  *
427  * SubqueryScan is for scanning the output of a sub-query in the range table.
428  * We often need an extra plan node above the sub-query's plan to perform
429  * expression evaluations (which we can't push into the sub-query without
430  * risking changing its semantics).  Although we are not scanning a physical
431  * relation, we make this a descendant of Scan anyway for code-sharing
432  * purposes.
433  *
434  * Note: we store the sub-plan in the type-specific subplan field, not in
435  * the generic lefttree field as you might expect.  This is because we do
436  * not want plan-tree-traversal routines to recurse into the subplan without
437  * knowing that they are changing Query contexts.
438  * ----------------
439  */
440 typedef struct SubqueryScan
441 {
442         Scan            scan;
443         Plan       *subplan;
444 } SubqueryScan;
445
446 /* ----------------
447  *              FunctionScan node
448  * ----------------
449  */
450 typedef struct FunctionScan
451 {
452         Scan            scan;
453         List       *functions;          /* list of RangeTblFunction nodes */
454         bool            funcordinality; /* WITH ORDINALITY */
455 } FunctionScan;
456
457 /* ----------------
458  *              ValuesScan node
459  * ----------------
460  */
461 typedef struct ValuesScan
462 {
463         Scan            scan;
464         List       *values_lists;       /* list of expression lists */
465 } ValuesScan;
466
467 /* ----------------
468  *              CteScan node
469  * ----------------
470  */
471 typedef struct CteScan
472 {
473         Scan            scan;
474         int                     ctePlanId;              /* ID of init SubPlan for CTE */
475         int                     cteParam;               /* ID of Param representing CTE output */
476 } CteScan;
477
478 /* ----------------
479  *              WorkTableScan node
480  * ----------------
481  */
482 typedef struct WorkTableScan
483 {
484         Scan            scan;
485         int                     wtParam;                /* ID of Param representing work table */
486 } WorkTableScan;
487
488 /* ----------------
489  *              ForeignScan node
490  *
491  * fdw_exprs and fdw_private are both under the control of the foreign-data
492  * wrapper, but fdw_exprs is presumed to contain expression trees and will
493  * be post-processed accordingly by the planner; fdw_private won't be.
494  * Note that everything in both lists must be copiable by copyObject().
495  * One way to store an arbitrary blob of bytes is to represent it as a bytea
496  * Const.  Usually, though, you'll be better off choosing a representation
497  * that can be dumped usefully by nodeToString().
498  *
499  * fdw_scan_tlist is a targetlist describing the contents of the scan tuple
500  * returned by the FDW; it can be NIL if the scan tuple matches the declared
501  * rowtype of the foreign table, which is the normal case for a simple foreign
502  * table scan.  (If the plan node represents a foreign join, fdw_scan_tlist
503  * is required since there is no rowtype available from the system catalogs.)
504  * When fdw_scan_tlist is provided, Vars in the node's tlist and quals must
505  * have varno INDEX_VAR, and their varattnos correspond to resnos in the
506  * fdw_scan_tlist (which are also column numbers in the actual scan tuple).
507  * fdw_scan_tlist is never actually executed; it just holds expression trees
508  * describing what is in the scan tuple's columns.
509  *
510  * When the plan node represents a foreign join, scan.scanrelid is zero and
511  * fs_relids must be consulted to identify the join relation.  (fs_relids
512  * is valid for simple scans as well, but will always match scan.scanrelid.)
513  * ----------------
514  */
515 typedef struct ForeignScan
516 {
517         Scan            scan;
518         Oid                     fs_server;              /* OID of foreign server */
519         List       *fdw_exprs;          /* expressions that FDW may evaluate */
520         List       *fdw_private;        /* private data for FDW */
521         List       *fdw_scan_tlist; /* optional tlist describing scan tuple */
522         Bitmapset  *fs_relids;          /* RTIs generated by this scan */
523         bool            fsSystemCol;    /* true if any "system column" is needed */
524 } ForeignScan;
525
526 /* ----------------
527  *         CustomScan node
528  *
529  * The comments for ForeignScan's fdw_exprs, fdw_private, fdw_scan_tlist,
530  * and fs_relids fields apply equally to CustomScan's custom_exprs,
531  * custom_private, custom_scan_tlist, and custom_relids fields.  The
532  * convention of setting scan.scanrelid to zero for joins applies as well.
533  *
534  * Note that since Plan trees can be copied, custom scan providers *must*
535  * fit all plan data they need into those fields; embedding CustomScan in
536  * a larger struct will not work.
537  * ----------------
538  */
539 struct CustomScan;
540
541 typedef struct CustomScanMethods
542 {
543         const char *CustomName;
544
545         /* Create execution state (CustomScanState) from a CustomScan plan node */
546         Node       *(*CreateCustomScanState) (struct CustomScan *cscan);
547         /* Optional: print custom_xxx fields in some special way */
548         void            (*TextOutCustomScan) (StringInfo str,
549                                                                                           const struct CustomScan *node);
550 } CustomScanMethods;
551
552 typedef struct CustomScan
553 {
554         Scan            scan;
555         uint32          flags;                  /* mask of CUSTOMPATH_* flags, see relation.h */
556         List       *custom_exprs;       /* expressions that custom code may evaluate */
557         List       *custom_private; /* private data for custom code */
558         List       *custom_scan_tlist;          /* optional tlist describing scan
559                                                                                  * tuple */
560         Bitmapset  *custom_relids;      /* RTIs generated by this scan */
561         const CustomScanMethods *methods;
562 } CustomScan;
563
564 /*
565  * ==========
566  * Join nodes
567  * ==========
568  */
569
570 /* ----------------
571  *              Join node
572  *
573  * jointype:    rule for joining tuples from left and right subtrees
574  * joinqual:    qual conditions that came from JOIN/ON or JOIN/USING
575  *                              (plan.qual contains conditions that came from WHERE)
576  *
577  * When jointype is INNER, joinqual and plan.qual are semantically
578  * interchangeable.  For OUTER jointypes, the two are *not* interchangeable;
579  * only joinqual is used to determine whether a match has been found for
580  * the purpose of deciding whether to generate null-extended tuples.
581  * (But plan.qual is still applied before actually returning a tuple.)
582  * For an outer join, only joinquals are allowed to be used as the merge
583  * or hash condition of a merge or hash join.
584  * ----------------
585  */
586 typedef struct Join
587 {
588         Plan            plan;
589         JoinType        jointype;
590         List       *joinqual;           /* JOIN quals (in addition to plan.qual) */
591 } Join;
592
593 /* ----------------
594  *              nest loop join node
595  *
596  * The nestParams list identifies any executor Params that must be passed
597  * into execution of the inner subplan carrying values from the current row
598  * of the outer subplan.  Currently we restrict these values to be simple
599  * Vars, but perhaps someday that'd be worth relaxing.  (Note: during plan
600  * creation, the paramval can actually be a PlaceHolderVar expression; but it
601  * must be a Var with varno OUTER_VAR by the time it gets to the executor.)
602  * ----------------
603  */
604 typedef struct NestLoop
605 {
606         Join            join;
607         List       *nestParams;         /* list of NestLoopParam nodes */
608 } NestLoop;
609
610 typedef struct NestLoopParam
611 {
612         NodeTag         type;
613         int                     paramno;                /* number of the PARAM_EXEC Param to set */
614         Var                *paramval;           /* outer-relation Var to assign to Param */
615 } NestLoopParam;
616
617 /* ----------------
618  *              merge join node
619  *
620  * The expected ordering of each mergeable column is described by a btree
621  * opfamily OID, a collation OID, a direction (BTLessStrategyNumber or
622  * BTGreaterStrategyNumber) and a nulls-first flag.  Note that the two sides
623  * of each mergeclause may be of different datatypes, but they are ordered the
624  * same way according to the common opfamily and collation.  The operator in
625  * each mergeclause must be an equality operator of the indicated opfamily.
626  * ----------------
627  */
628 typedef struct MergeJoin
629 {
630         Join            join;
631         List       *mergeclauses;       /* mergeclauses as expression trees */
632         /* these are arrays, but have the same length as the mergeclauses list: */
633         Oid                *mergeFamilies;      /* per-clause OIDs of btree opfamilies */
634         Oid                *mergeCollations;    /* per-clause OIDs of collations */
635         int                *mergeStrategies;    /* per-clause ordering (ASC or DESC) */
636         bool       *mergeNullsFirst;    /* per-clause nulls ordering */
637 } MergeJoin;
638
639 /* ----------------
640  *              hash join node
641  * ----------------
642  */
643 typedef struct HashJoin
644 {
645         Join            join;
646         List       *hashclauses;
647 } HashJoin;
648
649 /* ----------------
650  *              materialization node
651  * ----------------
652  */
653 typedef struct Material
654 {
655         Plan            plan;
656 } Material;
657
658 /* ----------------
659  *              sort node
660  * ----------------
661  */
662 typedef struct Sort
663 {
664         Plan            plan;
665         int                     numCols;                /* number of sort-key columns */
666         AttrNumber *sortColIdx;         /* their indexes in the target list */
667         Oid                *sortOperators;      /* OIDs of operators to sort them by */
668         Oid                *collations;         /* OIDs of collations */
669         bool       *nullsFirst;         /* NULLS FIRST/LAST directions */
670 } Sort;
671
672 /* ---------------
673  *       group node -
674  *              Used for queries with GROUP BY (but no aggregates) specified.
675  *              The input must be presorted according to the grouping columns.
676  * ---------------
677  */
678 typedef struct Group
679 {
680         Plan            plan;
681         int                     numCols;                /* number of grouping columns */
682         AttrNumber *grpColIdx;          /* their indexes in the target list */
683         Oid                *grpOperators;       /* equality operators to compare with */
684 } Group;
685
686 /* ---------------
687  *              aggregate node
688  *
689  * An Agg node implements plain or grouped aggregation.  For grouped
690  * aggregation, we can work with presorted input or unsorted input;
691  * the latter strategy uses an internal hashtable.
692  *
693  * Notice the lack of any direct info about the aggregate functions to be
694  * computed.  They are found by scanning the node's tlist and quals during
695  * executor startup.  (It is possible that there are no aggregate functions;
696  * this could happen if they get optimized away by constant-folding, or if
697  * we are using the Agg node to implement hash-based grouping.)
698  * ---------------
699  */
700 typedef enum AggStrategy
701 {
702         AGG_PLAIN,                                      /* simple agg across all input rows */
703         AGG_SORTED,                                     /* grouped agg, input must be sorted */
704         AGG_HASHED                                      /* grouped agg, use internal hashtable */
705 } AggStrategy;
706
707 typedef struct Agg
708 {
709         Plan            plan;
710         AggStrategy aggstrategy;
711         int                     numCols;                /* number of grouping columns */
712         AttrNumber *grpColIdx;          /* their indexes in the target list */
713         Oid                *grpOperators;       /* equality operators to compare with */
714         long            numGroups;              /* estimated number of groups in input */
715 } Agg;
716
717 /* ----------------
718  *              window aggregate node
719  * ----------------
720  */
721 typedef struct WindowAgg
722 {
723         Plan            plan;
724         Index           winref;                 /* ID referenced by window functions */
725         int                     partNumCols;    /* number of columns in partition clause */
726         AttrNumber *partColIdx;         /* their indexes in the target list */
727         Oid                *partOperators;      /* equality operators for partition columns */
728         int                     ordNumCols;             /* number of columns in ordering clause */
729         AttrNumber *ordColIdx;          /* their indexes in the target list */
730         Oid                *ordOperators;       /* equality operators for ordering columns */
731         int                     frameOptions;   /* frame_clause options, see WindowDef */
732         Node       *startOffset;        /* expression for starting bound, if any */
733         Node       *endOffset;          /* expression for ending bound, if any */
734 } WindowAgg;
735
736 /* ----------------
737  *              unique node
738  * ----------------
739  */
740 typedef struct Unique
741 {
742         Plan            plan;
743         int                     numCols;                /* number of columns to check for uniqueness */
744         AttrNumber *uniqColIdx;         /* their indexes in the target list */
745         Oid                *uniqOperators;      /* equality operators to compare with */
746 } Unique;
747
748 /* ----------------
749  *              hash build node
750  *
751  * If the executor is supposed to try to apply skew join optimization, then
752  * skewTable/skewColumn/skewInherit identify the outer relation's join key
753  * column, from which the relevant MCV statistics can be fetched.  Also, its
754  * type information is provided to save a lookup.
755  * ----------------
756  */
757 typedef struct Hash
758 {
759         Plan            plan;
760         Oid                     skewTable;              /* outer join key's table OID, or InvalidOid */
761         AttrNumber      skewColumn;             /* outer join key's column #, or zero */
762         bool            skewInherit;    /* is outer join rel an inheritance tree? */
763         Oid                     skewColType;    /* datatype of the outer key column */
764         int32           skewColTypmod;  /* typmod of the outer key column */
765         /* all other info is in the parent HashJoin node */
766 } Hash;
767
768 /* ----------------
769  *              setop node
770  * ----------------
771  */
772 typedef enum SetOpCmd
773 {
774         SETOPCMD_INTERSECT,
775         SETOPCMD_INTERSECT_ALL,
776         SETOPCMD_EXCEPT,
777         SETOPCMD_EXCEPT_ALL
778 } SetOpCmd;
779
780 typedef enum SetOpStrategy
781 {
782         SETOP_SORTED,                           /* input must be sorted */
783         SETOP_HASHED                            /* use internal hashtable */
784 } SetOpStrategy;
785
786 typedef struct SetOp
787 {
788         Plan            plan;
789         SetOpCmd        cmd;                    /* what to do */
790         SetOpStrategy strategy;         /* how to do it */
791         int                     numCols;                /* number of columns to check for
792                                                                  * duplicate-ness */
793         AttrNumber *dupColIdx;          /* their indexes in the target list */
794         Oid                *dupOperators;       /* equality operators to compare with */
795         AttrNumber      flagColIdx;             /* where is the flag column, if any */
796         int                     firstFlag;              /* flag value for first input relation */
797         long            numGroups;              /* estimated number of groups in input */
798 } SetOp;
799
800 /* ----------------
801  *              lock-rows node
802  *
803  * rowMarks identifies the rels to be locked by this node; it should be
804  * a subset of the rowMarks listed in the top-level PlannedStmt.
805  * epqParam is a Param that all scan nodes below this one must depend on.
806  * It is used to force re-evaluation of the plan during EvalPlanQual.
807  * ----------------
808  */
809 typedef struct LockRows
810 {
811         Plan            plan;
812         List       *rowMarks;           /* a list of PlanRowMark's */
813         int                     epqParam;               /* ID of Param for EvalPlanQual re-eval */
814 } LockRows;
815
816 /* ----------------
817  *              limit node
818  *
819  * Note: as of Postgres 8.2, the offset and count expressions are expected
820  * to yield int8, rather than int4 as before.
821  * ----------------
822  */
823 typedef struct Limit
824 {
825         Plan            plan;
826         Node       *limitOffset;        /* OFFSET parameter, or NULL if none */
827         Node       *limitCount;         /* COUNT parameter, or NULL if none */
828 } Limit;
829
830
831 /*
832  * RowMarkType -
833  *        enums for types of row-marking operations
834  *
835  * The first four of these values represent different lock strengths that
836  * we can take on tuples according to SELECT FOR [KEY] UPDATE/SHARE requests.
837  * We support these on regular tables, as well as on foreign tables whose FDWs
838  * report support for late locking.  For other foreign tables, any locking
839  * that might be done for such requests must happen during the initial row
840  * fetch; their FDWs provide no mechanism for going back to lock a row later.
841  * This means that the semantics will be a bit different than for a local
842  * table; in particular we are likely to lock more rows than would be locked
843  * locally, since remote rows will be locked even if they then fail
844  * locally-checked restriction or join quals.  However, the prospect of
845  * doing a separate remote query to lock each selected row is usually pretty
846  * unappealing, so early locking remains a credible design choice for FDWs.
847  *
848  * When doing UPDATE, DELETE, or SELECT FOR UPDATE/SHARE, we have to uniquely
849  * identify all the source rows, not only those from the target relations, so
850  * that we can perform EvalPlanQual rechecking at need.  For plain tables we
851  * can just fetch the TID, much as for a target relation; this case is
852  * represented by ROW_MARK_REFERENCE.  Otherwise (for example for VALUES or
853  * FUNCTION scans) we have to copy the whole row value.  ROW_MARK_COPY is
854  * pretty inefficient, since most of the time we'll never need the data; but
855  * fortunately the overhead is usually not performance-critical in practice.
856  * By default we use ROW_MARK_COPY for foreign tables, but if the FDW has
857  * a concept of rowid it can request to use ROW_MARK_REFERENCE instead.
858  * (Again, this probably doesn't make sense if a physical remote fetch is
859  * needed, but for FDWs that map to local storage it might be credible.)
860  */
861 typedef enum RowMarkType
862 {
863         ROW_MARK_EXCLUSIVE,                     /* obtain exclusive tuple lock */
864         ROW_MARK_NOKEYEXCLUSIVE,        /* obtain no-key exclusive tuple lock */
865         ROW_MARK_SHARE,                         /* obtain shared tuple lock */
866         ROW_MARK_KEYSHARE,                      /* obtain keyshare tuple lock */
867         ROW_MARK_REFERENCE,                     /* just fetch the TID, don't lock it */
868         ROW_MARK_COPY                           /* physically copy the row value */
869 } RowMarkType;
870
871 #define RowMarkRequiresRowShareLock(marktype)  ((marktype) <= ROW_MARK_KEYSHARE)
872
873 /*
874  * PlanRowMark -
875  *         plan-time representation of FOR [KEY] UPDATE/SHARE clauses
876  *
877  * When doing UPDATE, DELETE, or SELECT FOR UPDATE/SHARE, we create a separate
878  * PlanRowMark node for each non-target relation in the query.  Relations that
879  * are not specified as FOR UPDATE/SHARE are marked ROW_MARK_REFERENCE (if
880  * regular tables or supported foreign tables) or ROW_MARK_COPY (if not).
881  *
882  * Initially all PlanRowMarks have rti == prti and isParent == false.
883  * When the planner discovers that a relation is the root of an inheritance
884  * tree, it sets isParent true, and adds an additional PlanRowMark to the
885  * list for each child relation (including the target rel itself in its role
886  * as a child).  The child entries have rti == child rel's RT index and
887  * prti == parent's RT index, and can therefore be recognized as children by
888  * the fact that prti != rti.  The parent's allMarkTypes field gets the OR
889  * of (1<<markType) across all its children (this definition allows children
890  * to use different markTypes).
891  *
892  * The planner also adds resjunk output columns to the plan that carry
893  * information sufficient to identify the locked or fetched rows.  When
894  * markType != ROW_MARK_COPY, these columns are named
895  *              tableoid%u                      OID of table
896  *              ctid%u                          TID of row
897  * The tableoid column is only present for an inheritance hierarchy.
898  * When markType == ROW_MARK_COPY, there is instead a single column named
899  *              wholerow%u                      whole-row value of relation
900  * (An inheritance hierarchy could have all three resjunk output columns,
901  * if some children use a different markType than others.)
902  * In all three cases, %u represents the rowmark ID number (rowmarkId).
903  * This number is unique within a plan tree, except that child relation
904  * entries copy their parent's rowmarkId.  (Assigning unique numbers
905  * means we needn't renumber rowmarkIds when flattening subqueries, which
906  * would require finding and renaming the resjunk columns as well.)
907  * Note this means that all tables in an inheritance hierarchy share the
908  * same resjunk column names.  However, in an inherited UPDATE/DELETE the
909  * columns could have different physical column numbers in each subplan.
910  */
911 typedef struct PlanRowMark
912 {
913         NodeTag         type;
914         Index           rti;                    /* range table index of markable relation */
915         Index           prti;                   /* range table index of parent relation */
916         Index           rowmarkId;              /* unique identifier for resjunk columns */
917         RowMarkType markType;           /* see enum above */
918         int                     allMarkTypes;   /* OR of (1<<markType) for all children */
919         LockClauseStrength strength;    /* LockingClause's strength, or LCS_NONE */
920         LockWaitPolicy waitPolicy;      /* NOWAIT and SKIP LOCKED options */
921         bool            isParent;               /* true if this is a "dummy" parent entry */
922 } PlanRowMark;
923
924
925 /*
926  * Plan invalidation info
927  *
928  * We track the objects on which a PlannedStmt depends in two ways:
929  * relations are recorded as a simple list of OIDs, and everything else
930  * is represented as a list of PlanInvalItems.  A PlanInvalItem is designed
931  * to be used with the syscache invalidation mechanism, so it identifies a
932  * system catalog entry by cache ID and hash value.
933  */
934 typedef struct PlanInvalItem
935 {
936         NodeTag         type;
937         int                     cacheId;                /* a syscache ID, see utils/syscache.h */
938         uint32          hashValue;              /* hash value of object's cache lookup key */
939 } PlanInvalItem;
940
941 #endif   /* PLANNODES_H */