1 /*-------------------------------------------------------------------------
4 * definitions for query plan nodes
7 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 *-------------------------------------------------------------------------
17 #include "access/sdir.h"
18 #include "nodes/bitmapset.h"
19 #include "nodes/primnodes.h"
20 #include "storage/itemptr.h"
23 /* ----------------------------------------------------------------
25 * ----------------------------------------------------------------
31 * The output of the planner is a Plan tree headed by a PlannedStmt node.
32 * PlannedStmt holds the "one time" information needed by the executor.
35 typedef struct PlannedStmt
39 CmdType commandType
; /* select|insert|update|delete */
41 bool canSetTag
; /* do I set the command result tag? */
43 bool transientPlan
; /* redo plan when TransactionXmin changes? */
45 struct Plan
*planTree
; /* tree of Plan nodes */
47 List
*rtable
; /* list of RangeTblEntry nodes */
49 /* rtable indexes of target relations for INSERT/UPDATE/DELETE */
50 List
*resultRelations
; /* integer list of RT indexes, or NIL */
52 Node
*utilityStmt
; /* non-null if this is DECLARE CURSOR */
54 IntoClause
*intoClause
; /* target for SELECT INTO / CREATE TABLE AS */
56 List
*subplans
; /* Plan trees for SubPlan expressions */
58 Bitmapset
*rewindPlanIDs
; /* indices of subplans that require REWIND */
61 * If the query has a returningList then the planner will store a list of
62 * processed targetlists (one per result relation) here. We must have a
63 * separate RETURNING targetlist for each result rel because column
64 * numbers may vary within an inheritance tree. In the targetlists, Vars
65 * referencing the result relation will have their original varno and
66 * varattno, while Vars referencing other rels will be converted to have
67 * varno OUTER and varattno referencing a resjunk entry in the top plan
70 List
*returningLists
; /* list of lists of TargetEntry, or NIL */
72 List
*rowMarks
; /* a list of RowMarkClause's */
74 List
*relationOids
; /* OIDs of relations the plan depends on */
76 List
*invalItems
; /* other dependencies, as PlanInvalItems */
78 int nParamExec
; /* number of PARAM_EXEC Params used */
81 /* macro for fetching the Plan associated with a SubPlan node */
82 #define exec_subplan_get_plan(plannedstmt, subplan) \
83 ((Plan *) list_nth((plannedstmt)->subplans, (subplan)->plan_id - 1))
89 * All plan nodes "derive" from the Plan structure by having the
90 * Plan structure as the first field. This ensures that everything works
91 * when nodes are cast to Plan's. (node pointers are frequently cast to Plan*
92 * when passed around generically in the executor)
94 * We never actually instantiate any Plan nodes; this is just the common
95 * abstract superclass for all Plan-type nodes.
103 * estimated execution costs for plan (see costsize.c for more info)
105 Cost startup_cost
; /* cost expended before fetching any tuples */
106 Cost total_cost
; /* total cost (assuming all tuples fetched) */
109 * planner's estimate of result size of this plan step
111 double plan_rows
; /* number of rows plan is expected to emit */
112 int plan_width
; /* average row width in bytes */
115 * Common structural data for all Plan types.
117 List
*targetlist
; /* target list to be computed at this node */
118 List
*qual
; /* implicitly-ANDed qual conditions */
119 struct Plan
*lefttree
; /* input plan tree(s) */
120 struct Plan
*righttree
;
121 List
*initPlan
; /* Init Plan nodes (un-correlated expr
125 * Information for management of parameter-change-driven rescanning
127 * extParam includes the paramIDs of all external PARAM_EXEC params
128 * affecting this plan node or its children. setParam params from the
129 * node's initPlans are not included, but their extParams are.
131 * allParam includes all the extParam paramIDs, plus the IDs of local
132 * params that affect the node (i.e., the setParams of its initplans).
133 * These are _all_ the PARAM_EXEC params that affect this node.
140 * these are are defined to avoid confusion problems with "left"
141 * and "right" and "inner" and "outer". The convention is that
142 * the "left" plan is the "outer" plan and the "right" plan is
143 * the inner plan, but these make the code more readable.
146 #define innerPlan(node) (((Plan *)(node))->righttree)
147 #define outerPlan(node) (((Plan *)(node))->lefttree)
152 * If no outer plan, evaluate a variable-free targetlist.
153 * If outer plan, return tuples from outer plan (after a level of
154 * projection as shown by targetlist).
156 * If resconstantqual isn't NULL, it represents a one-time qualification
157 * test (i.e., one that doesn't depend on any variables from the outer plan,
158 * so needs to be evaluated only once).
161 typedef struct Result
164 Node
*resconstantqual
;
169 * Generate the concatenation of the results of sub-plans.
171 * Append nodes are sometimes used to switch between several result relations
172 * (when the target of an UPDATE or DELETE is an inheritance set). Such a
173 * node will have isTarget true. The Append executor is then responsible
174 * for updating the executor state to point at the correct target relation
175 * whenever it switches subplans.
178 typedef struct Append
187 * Generate the intersection of the results of sub-plans.
189 * The subplans must be of types that yield tuple bitmaps. The targetlist
190 * and qual fields of the plan are unused and are always NIL.
193 typedef struct BitmapAnd
201 * Generate the union of the results of sub-plans.
203 * The subplans must be of types that yield tuple bitmaps. The targetlist
204 * and qual fields of the plan are unused and are always NIL.
207 typedef struct BitmapOr
221 Index scanrelid
; /* relid is index into the range table */
225 * sequential scan node
228 typedef Scan SeqScan
;
233 * indexqualorig is an implicitly-ANDed list of index qual expressions, each
234 * in the same form it appeared in the query WHERE condition. Each should
235 * be of the form (indexkey OP comparisonval) or (comparisonval OP indexkey).
236 * The indexkey is a Var or expression referencing column(s) of the index's
237 * base table. The comparisonval might be any expression, but it won't use
238 * any columns of the base table.
240 * indexqual has the same form, but the expressions have been commuted if
241 * necessary to put the indexkeys on the left, and the indexkeys are replaced
242 * by Var nodes identifying the index columns (varattno is the index column
243 * position, not the base table's column, even though varno is for the base
244 * table). This is a bit hokey ... would be cleaner to use a special-purpose
245 * node type that could not be mistaken for a regular Var. But it will do
249 typedef struct IndexScan
252 Oid indexid
; /* OID of index to scan */
253 List
*indexqual
; /* list of index quals (OpExprs) */
254 List
*indexqualorig
; /* the same in original form */
255 ScanDirection indexorderdir
; /* forward or backward or don't care */
259 * bitmap index scan node
261 * BitmapIndexScan delivers a bitmap of potential tuple locations;
262 * it does not access the heap itself. The bitmap is used by an
263 * ancestor BitmapHeapScan node, possibly after passing through
264 * intermediate BitmapAnd and/or BitmapOr nodes to combine it with
265 * the results of other BitmapIndexScans.
267 * The fields have the same meanings as for IndexScan, except we don't
268 * store a direction flag because direction is uninteresting.
270 * In a BitmapIndexScan plan node, the targetlist and qual fields are
271 * not used and are always NIL. The indexqualorig field is unused at
272 * run time too, but is saved for the benefit of EXPLAIN.
275 typedef struct BitmapIndexScan
278 Oid indexid
; /* OID of index to scan */
279 List
*indexqual
; /* list of index quals (OpExprs) */
280 List
*indexqualorig
; /* the same in original form */
284 * bitmap sequential scan node
286 * This needs a copy of the qual conditions being used by the input index
287 * scans because there are various cases where we need to recheck the quals;
288 * for example, when the bitmap is lossy about the specific rows on a page
289 * that meet the index condition.
292 typedef struct BitmapHeapScan
295 List
*bitmapqualorig
; /* index quals, in standard expr form */
301 * tidquals is an implicitly OR'ed list of qual expressions of the form
302 * "CTID = pseudoconstant" or "CTID = ANY(pseudoconstant_array)".
305 typedef struct TidScan
308 List
*tidquals
; /* qual(s) involving CTID = something */
314 * SubqueryScan is for scanning the output of a sub-query in the range table.
315 * We often need an extra plan node above the sub-query's plan to perform
316 * expression evaluations (which we can't push into the sub-query without
317 * risking changing its semantics). Although we are not scanning a physical
318 * relation, we make this a descendant of Scan anyway for code-sharing
321 * Note: we store the sub-plan in the type-specific subplan field, not in
322 * the generic lefttree field as you might expect. This is because we do
323 * not want plan-tree-traversal routines to recurse into the subplan without
324 * knowing that they are changing Query contexts.
326 * Note: subrtable is used just to carry the subquery rangetable from
327 * createplan.c to setrefs.c; it should always be NIL by the time the
328 * executor sees the plan.
331 typedef struct SubqueryScan
335 List
*subrtable
; /* temporary workspace for planner */
342 typedef struct FunctionScan
345 Node
*funcexpr
; /* expression tree for func call */
346 List
*funccolnames
; /* output column names (string Value nodes) */
347 List
*funccoltypes
; /* OID list of column type OIDs */
348 List
*funccoltypmods
; /* integer list of column typmods */
355 typedef struct ValuesScan
358 List
*values_lists
; /* list of expression lists */
370 * jointype: rule for joining tuples from left and right subtrees
371 * joinqual: qual conditions that came from JOIN/ON or JOIN/USING
372 * (plan.qual contains conditions that came from WHERE)
374 * When jointype is INNER, joinqual and plan.qual are semantically
375 * interchangeable. For OUTER jointypes, the two are *not* interchangeable;
376 * only joinqual is used to determine whether a match has been found for
377 * the purpose of deciding whether to generate null-extended tuples.
378 * (But plan.qual is still applied before actually returning a tuple.)
379 * For an outer join, only joinquals are allowed to be used as the merge
380 * or hash condition of a merge or hash join.
387 List
*joinqual
; /* JOIN quals (in addition to plan.qual) */
391 * nest loop join node
394 typedef struct NestLoop
402 * The expected ordering of each mergeable column is described by a btree
403 * opfamily OID, a direction (BTLessStrategyNumber or BTGreaterStrategyNumber)
404 * and a nulls-first flag. Note that the two sides of each mergeclause may
405 * be of different datatypes, but they are ordered the same way according to
406 * the common opfamily. The operator in each mergeclause must be an equality
407 * operator of the indicated opfamily.
410 typedef struct MergeJoin
413 List
*mergeclauses
; /* mergeclauses as expression trees */
414 /* these are arrays, but have the same length as the mergeclauses list: */
415 Oid
*mergeFamilies
; /* per-clause OIDs of btree opfamilies */
416 int *mergeStrategies
; /* per-clause ordering (ASC or DESC) */
417 bool *mergeNullsFirst
; /* per-clause nulls ordering */
421 * hash join (probe) node
424 typedef struct HashJoin
431 * materialization node
434 typedef struct Material
446 int numCols
; /* number of sort-key columns */
447 AttrNumber
*sortColIdx
; /* their indexes in the target list */
448 Oid
*sortOperators
; /* OIDs of operators to sort them by */
449 bool *nullsFirst
; /* NULLS FIRST/LAST directions */
454 * Used for queries with GROUP BY (but no aggregates) specified.
455 * The input must be presorted according to the grouping columns.
461 int numCols
; /* number of grouping columns */
462 AttrNumber
*grpColIdx
; /* their indexes in the target list */
463 Oid
*grpOperators
; /* equality operators to compare with */
469 * An Agg node implements plain or grouped aggregation. For grouped
470 * aggregation, we can work with presorted input or unsorted input;
471 * the latter strategy uses an internal hashtable.
473 * Notice the lack of any direct info about the aggregate functions to be
474 * computed. They are found by scanning the node's tlist and quals during
475 * executor startup. (It is possible that there are no aggregate functions;
476 * this could happen if they get optimized away by constant-folding, or if
477 * we are using the Agg node to implement hash-based grouping.)
480 typedef enum AggStrategy
482 AGG_PLAIN
, /* simple agg across all input rows */
483 AGG_SORTED
, /* grouped agg, input must be sorted */
484 AGG_HASHED
/* grouped agg, use internal hashtable */
490 AggStrategy aggstrategy
;
491 int numCols
; /* number of grouping columns */
492 AttrNumber
*grpColIdx
; /* their indexes in the target list */
493 Oid
*grpOperators
; /* equality operators to compare with */
494 long numGroups
; /* estimated number of groups in input */
501 typedef struct Unique
504 int numCols
; /* number of columns to check for uniqueness */
505 AttrNumber
*uniqColIdx
; /* their indexes in the target list */
506 Oid
*uniqOperators
; /* equality operators to compare with */
516 /* all other info is in the parent HashJoin node */
523 typedef enum SetOpCmd
526 SETOPCMD_INTERSECT_ALL
,
531 typedef enum SetOpStrategy
533 SETOP_SORTED
, /* input must be sorted */
534 SETOP_HASHED
/* use internal hashtable */
540 SetOpCmd cmd
; /* what to do */
541 SetOpStrategy strategy
; /* how to do it */
542 int numCols
; /* number of columns to check for
544 AttrNumber
*dupColIdx
; /* their indexes in the target list */
545 Oid
*dupOperators
; /* equality operators to compare with */
546 AttrNumber flagColIdx
; /* where is the flag column, if any */
547 int firstFlag
; /* flag value for first input relation */
548 long numGroups
; /* estimated number of groups in input */
554 * Note: as of Postgres 8.2, the offset and count expressions are expected
555 * to yield int8, rather than int4 as before.
561 Node
*limitOffset
; /* OFFSET parameter, or NULL if none */
562 Node
*limitCount
; /* COUNT parameter, or NULL if none */
567 * Plan invalidation info
569 * We track the objects on which a PlannedStmt depends in two ways:
570 * relations are recorded as a simple list of OIDs, and everything else
571 * is represented as a list of PlanInvalItems. A PlanInvalItem is designed
572 * to be used with the syscache invalidation mechanism, so it identifies a
573 * system catalog entry by cache ID and tuple TID.
575 typedef struct PlanInvalItem
578 int cacheId
; /* a syscache ID, see utils/syscache.h */
579 ItemPointerData tupleId
; /* TID of the object's catalog tuple */
582 #endif /* PLANNODES_H */