Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * partprune.c
4 : : * Support for partition pruning during query planning and execution
5 : : *
6 : : * This module implements partition pruning using the information contained in
7 : : * a table's partition descriptor, query clauses, and run-time parameters.
8 : : *
9 : : * During planning, clauses that can be matched to the table's partition key
10 : : * are turned into a set of "pruning steps", which are then executed to
11 : : * identify a set of partitions (as indexes in the RelOptInfo->part_rels
12 : : * array) that satisfy the constraints in the step. Partitions not in the set
13 : : * are said to have been pruned.
14 : : *
15 : : * A base pruning step may involve expressions whose values are only known
16 : : * during execution, such as Params, in which case pruning cannot occur
17 : : * entirely during planning. In that case, such steps are included alongside
18 : : * the plan, so that they can be used by the executor for further pruning.
19 : : *
20 : : * There are two kinds of pruning steps. A "base" pruning step represents
21 : : * tests on partition key column(s), typically comparisons to expressions.
22 : : * A "combine" pruning step represents a Boolean connector (AND/OR), and
23 : : * combines the outputs of some previous steps using the appropriate
24 : : * combination method.
25 : : *
26 : : * See gen_partprune_steps_internal() for more details on step generation.
27 : : *
28 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
29 : : * Portions Copyright (c) 1994, Regents of the University of California
30 : : *
31 : : * IDENTIFICATION
32 : : * src/backend/partitioning/partprune.c
33 : : *
34 : : *-------------------------------------------------------------------------
35 : : */
36 : : #include "postgres.h"
37 : :
38 : : #include "access/hash.h"
39 : : #include "access/nbtree.h"
40 : : #include "catalog/pg_operator.h"
41 : : #include "catalog/pg_opfamily.h"
42 : : #include "catalog/pg_proc.h"
43 : : #include "catalog/pg_type.h"
44 : : #include "executor/executor.h"
45 : : #include "miscadmin.h"
46 : : #include "nodes/makefuncs.h"
47 : : #include "nodes/nodeFuncs.h"
48 : : #include "optimizer/appendinfo.h"
49 : : #include "optimizer/cost.h"
50 : : #include "optimizer/optimizer.h"
51 : : #include "optimizer/pathnode.h"
52 : : #include "optimizer/placeholder.h"
53 : : #include "parser/parsetree.h"
54 : : #include "partitioning/partbounds.h"
55 : : #include "partitioning/partprune.h"
56 : : #include "utils/array.h"
57 : : #include "utils/lsyscache.h"
58 : :
59 : :
60 : : /*
61 : : * Information about a clause matched with a partition key.
62 : : */
63 : : typedef struct PartClauseInfo
64 : : {
65 : : int keyno; /* Partition key number (0 to partnatts - 1) */
66 : : Oid opno; /* operator used to compare partkey to expr */
67 : : bool op_is_ne; /* is clause's original operator <> ? */
68 : : Expr *expr; /* expr the partition key is compared to */
69 : : Oid cmpfn; /* Oid of function to compare 'expr' to the
70 : : * partition key */
71 : : int op_strategy; /* btree strategy identifying the operator */
72 : : } PartClauseInfo;
73 : :
74 : : /*
75 : : * PartClauseMatchStatus
76 : : * Describes the result of match_clause_to_partition_key()
77 : : */
78 : : typedef enum PartClauseMatchStatus
79 : : {
80 : : PARTCLAUSE_NOMATCH,
81 : : PARTCLAUSE_MATCH_CLAUSE,
82 : : PARTCLAUSE_MATCH_NULLNESS,
83 : : PARTCLAUSE_MATCH_STEPS,
84 : : PARTCLAUSE_MATCH_CONTRADICT,
85 : : PARTCLAUSE_UNSUPPORTED,
86 : : } PartClauseMatchStatus;
87 : :
88 : : /*
89 : : * PartClauseTarget
90 : : * Identifies which qual clauses we can use for generating pruning steps
91 : : */
92 : : typedef enum PartClauseTarget
93 : : {
94 : : PARTTARGET_PLANNER, /* want to prune during planning */
95 : : PARTTARGET_INITIAL, /* want to prune during executor startup */
96 : : PARTTARGET_EXEC, /* want to prune during each plan node scan */
97 : : } PartClauseTarget;
98 : :
99 : : /*
100 : : * GeneratePruningStepsContext
101 : : * Information about the current state of generation of "pruning steps"
102 : : * for a given set of clauses
103 : : *
104 : : * gen_partprune_steps() initializes and returns an instance of this struct.
105 : : *
106 : : * Note that has_mutable_op, has_mutable_arg, and has_exec_param are set if
107 : : * we found any potentially-useful-for-pruning clause having those properties,
108 : : * whether or not we actually used the clause in the steps list. This
109 : : * definition allows us to skip the PARTTARGET_EXEC pass in some cases.
110 : : */
111 : : typedef struct GeneratePruningStepsContext
112 : : {
113 : : /* Copies of input arguments for gen_partprune_steps: */
114 : : RelOptInfo *rel; /* the partitioned relation */
115 : : PartClauseTarget target; /* use-case we're generating steps for */
116 : : /* Result data: */
117 : : List *steps; /* list of PartitionPruneSteps */
118 : : bool has_mutable_op; /* clauses include any stable operators */
119 : : bool has_mutable_arg; /* clauses include any mutable comparison
120 : : * values, *other than* exec params */
121 : : bool has_exec_param; /* clauses include any PARAM_EXEC params */
122 : : bool contradictory; /* clauses were proven self-contradictory */
123 : : /* Working state: */
124 : : int next_step_id;
125 : : } GeneratePruningStepsContext;
126 : :
127 : : /* The result of performing one PartitionPruneStep */
128 : : typedef struct PruneStepResult
129 : : {
130 : : /*
131 : : * The offsets of bounds (in a table's boundinfo) whose partition is
132 : : * selected by the pruning step.
133 : : */
134 : : Bitmapset *bound_offsets;
135 : :
136 : : bool scan_default; /* Scan the default partition? */
137 : : bool scan_null; /* Scan the partition for NULL values? */
138 : : } PruneStepResult;
139 : :
140 : :
141 : : static List *add_part_relids(List *allpartrelids, Bitmapset *partrelids);
142 : : static List *make_partitionedrel_pruneinfo(PlannerInfo *root,
143 : : RelOptInfo *parentrel,
144 : : List *prunequal,
145 : : Bitmapset *partrelids,
146 : : int *relid_subplan_map,
147 : : Bitmapset **matchedsubplans);
148 : : static void gen_partprune_steps(RelOptInfo *rel, List *clauses,
149 : : PartClauseTarget target,
150 : : GeneratePruningStepsContext *context);
151 : : static List *gen_partprune_steps_internal(GeneratePruningStepsContext *context,
152 : : List *clauses);
153 : : static PartitionPruneStep *gen_prune_step_op(GeneratePruningStepsContext *context,
154 : : StrategyNumber opstrategy, bool op_is_ne,
155 : : List *exprs, List *cmpfns, Bitmapset *nullkeys);
156 : : static PartitionPruneStep *gen_prune_step_combine(GeneratePruningStepsContext *context,
157 : : List *source_stepids,
158 : : PartitionPruneCombineOp combineOp);
159 : : static List *gen_prune_steps_from_opexps(GeneratePruningStepsContext *context,
160 : : List **keyclauses, Bitmapset *nullkeys);
161 : : static PartClauseMatchStatus match_clause_to_partition_key(GeneratePruningStepsContext *context,
162 : : Expr *clause, const Expr *partkey, int partkeyidx,
163 : : bool *clause_is_not_null,
164 : : PartClauseInfo **pc, List **clause_steps);
165 : : static List *get_steps_using_prefix(GeneratePruningStepsContext *context,
166 : : StrategyNumber step_opstrategy,
167 : : bool step_op_is_ne,
168 : : Expr *step_lastexpr,
169 : : Oid step_lastcmpfn,
170 : : Bitmapset *step_nullkeys,
171 : : List *prefix);
172 : : static List *get_steps_using_prefix_recurse(GeneratePruningStepsContext *context,
173 : : StrategyNumber step_opstrategy,
174 : : bool step_op_is_ne,
175 : : Expr *step_lastexpr,
176 : : Oid step_lastcmpfn,
177 : : Bitmapset *step_nullkeys,
178 : : List *prefix,
179 : : ListCell *start,
180 : : List *step_exprs,
181 : : List *step_cmpfns);
182 : : static PruneStepResult *get_matching_hash_bounds(PartitionPruneContext *context,
183 : : StrategyNumber opstrategy, const Datum *values, int nvalues,
184 : : FmgrInfo *partsupfunc, Bitmapset *nullkeys);
185 : : static PruneStepResult *get_matching_list_bounds(PartitionPruneContext *context,
186 : : StrategyNumber opstrategy, Datum value, int nvalues,
187 : : FmgrInfo *partsupfunc, Bitmapset *nullkeys);
188 : : static PruneStepResult *get_matching_range_bounds(PartitionPruneContext *context,
189 : : StrategyNumber opstrategy, const Datum *values, int nvalues,
190 : : FmgrInfo *partsupfunc, Bitmapset *nullkeys);
191 : : static Bitmapset *pull_exec_paramids(Expr *expr);
192 : : static bool pull_exec_paramids_walker(Node *node, Bitmapset **context);
193 : : static Bitmapset *get_partkey_exec_paramids(List *steps);
194 : : static PruneStepResult *perform_pruning_base_step(PartitionPruneContext *context,
195 : : PartitionPruneStepOp *opstep);
196 : : static PruneStepResult *perform_pruning_combine_step(PartitionPruneContext *context,
197 : : PartitionPruneStepCombine *cstep,
198 : : PruneStepResult **step_results);
199 : : static PartClauseMatchStatus match_boolean_partition_clause(Oid partopfamily,
200 : : Expr *clause,
201 : : const Expr *partkey,
202 : : Expr **outconst,
203 : : bool *notclause);
204 : : static void partkey_datum_from_expr(PartitionPruneContext *context,
205 : : Expr *expr, int stateidx,
206 : : Datum *value, bool *isnull);
207 : :
208 : :
209 : : /*
210 : : * make_partition_pruneinfo
211 : : * Checks if the given set of quals can be used to build pruning steps
212 : : * that the executor can use to prune away unneeded partitions. If
213 : : * suitable quals are found then a PartitionPruneInfo is built and tagged
214 : : * onto the PlannerInfo's partPruneInfos list.
215 : : *
216 : : * The return value is the 0-based index of the item added to the
217 : : * partPruneInfos list or -1 if nothing was added.
218 : : *
219 : : * 'parentrel' is the RelOptInfo for an appendrel, and 'subpaths' is the list
220 : : * of scan paths for its child rels.
221 : : * 'prunequal' is a list of potential pruning quals (i.e., restriction
222 : : * clauses that are applicable to the appendrel).
223 : : */
224 : : int
225 : 7198 : make_partition_pruneinfo(PlannerInfo *root, RelOptInfo *parentrel,
226 : : List *subpaths,
227 : : List *prunequal)
228 : : {
229 : : PartitionPruneInfo *pruneinfo;
230 : 7198 : Bitmapset *allmatchedsubplans = NULL;
231 : : List *allpartrelids;
232 : : List *prunerelinfos;
233 : : int *relid_subplan_map;
234 : : ListCell *lc;
235 : : int i;
236 : :
237 : : /*
238 : : * Scan the subpaths to see which ones are scans of partition child
239 : : * relations, and identify their parent partitioned rels. (Note: we must
240 : : * restrict the parent partitioned rels to be parentrel or children of
241 : : * parentrel, otherwise we couldn't translate prunequal to match.)
242 : : *
243 : : * Also construct a temporary array to map from partition-child-relation
244 : : * relid to the index in 'subpaths' of the scan plan for that partition.
245 : : * (Use of "subplan" rather than "subpath" is a bit of a misnomer, but
246 : : * we'll let it stand.) For convenience, we use 1-based indexes here, so
247 : : * that zero can represent an un-filled array entry.
248 : : */
249 : 7198 : allpartrelids = NIL;
250 : 7198 : relid_subplan_map = palloc0_array(int, root->simple_rel_array_size);
251 : :
252 : 7198 : i = 1;
253 [ + - + + : 21284 : foreach(lc, subpaths)
+ + ]
254 : : {
255 : 14086 : Path *path = (Path *) lfirst(lc);
256 : 14086 : RelOptInfo *pathrel = path->parent;
257 : :
258 : : /* We don't consider partitioned joins here */
259 [ + - ]: 14086 : if (pathrel->reloptkind == RELOPT_OTHER_MEMBER_REL)
260 : : {
261 : 14086 : RelOptInfo *prel = pathrel;
262 : 14086 : Bitmapset *partrelids = NULL;
263 : :
264 : : /*
265 : : * Traverse up to the pathrel's topmost partitioned parent,
266 : : * collecting parent relids as we go; but stop if we reach
267 : : * parentrel. (Normally, a pathrel's topmost partitioned parent
268 : : * is either parentrel or a UNION ALL appendrel child of
269 : : * parentrel. But when handling partitionwise joins of
270 : : * multi-level partitioning trees, we can see an append path whose
271 : : * parentrel is an intermediate partitioned table.)
272 : : */
273 : : do
274 : : {
275 : : AppendRelInfo *appinfo;
276 : :
277 : : Assert(prel->relid < root->simple_rel_array_size);
278 : 16819 : appinfo = root->append_rel_array[prel->relid];
279 : 16819 : prel = find_base_rel(root, appinfo->parent_relid);
280 [ + + + - : 16819 : if (!IS_PARTITIONED_REL(prel))
+ - + - +
- ]
281 : : break; /* reached a non-partitioned parent */
282 : : /* accept this level as an interesting parent */
283 : 13627 : partrelids = bms_add_member(partrelids, prel->relid);
284 [ + + ]: 13627 : if (prel == parentrel)
285 : 10894 : break; /* don't traverse above parentrel */
286 [ + - ]: 2733 : } while (prel->reloptkind == RELOPT_OTHER_MEMBER_REL);
287 : :
288 [ + + ]: 14086 : if (partrelids)
289 : : {
290 : : /*
291 : : * Found some relevant parent partitions, which may or may not
292 : : * overlap with partition trees we already found. Add new
293 : : * information to the allpartrelids list.
294 : : */
295 : 11109 : allpartrelids = add_part_relids(allpartrelids, partrelids);
296 : : /* Also record the subplan in relid_subplan_map[] */
297 : : /* No duplicates please */
298 : : Assert(relid_subplan_map[pathrel->relid] == 0);
299 : 11109 : relid_subplan_map[pathrel->relid] = i;
300 : : }
301 : : }
302 : 14086 : i++;
303 : : }
304 : :
305 : : /*
306 : : * We now build a PartitionedRelPruneInfo for each topmost partitioned rel
307 : : * (omitting any that turn out not to have useful pruning quals).
308 : : */
309 : 7198 : prunerelinfos = NIL;
310 [ + + + + : 13226 : foreach(lc, allpartrelids)
+ + ]
311 : : {
312 : 6028 : Bitmapset *partrelids = (Bitmapset *) lfirst(lc);
313 : : List *pinfolist;
314 : 6028 : Bitmapset *matchedsubplans = NULL;
315 : :
316 : 6028 : pinfolist = make_partitionedrel_pruneinfo(root, parentrel,
317 : : prunequal,
318 : : partrelids,
319 : : relid_subplan_map,
320 : : &matchedsubplans);
321 : :
322 : : /* When pruning is possible, record the matched subplans */
323 [ + + ]: 6028 : if (pinfolist != NIL)
324 : : {
325 : 501 : prunerelinfos = lappend(prunerelinfos, pinfolist);
326 : 501 : allmatchedsubplans = bms_join(matchedsubplans,
327 : : allmatchedsubplans);
328 : : }
329 : : }
330 : :
331 : 7198 : pfree(relid_subplan_map);
332 : :
333 : : /*
334 : : * If none of the partition hierarchies had any useful run-time pruning
335 : : * quals, then we can just not bother with run-time pruning.
336 : : */
337 [ + + ]: 7198 : if (prunerelinfos == NIL)
338 : 6707 : return -1;
339 : :
340 : : /* Else build the result data structure */
341 : 491 : pruneinfo = makeNode(PartitionPruneInfo);
342 : 491 : pruneinfo->relids = bms_copy(parentrel->relids);
343 : 491 : pruneinfo->prune_infos = prunerelinfos;
344 : :
345 : : /*
346 : : * Some subplans may not belong to any of the identified partitioned rels.
347 : : * This can happen for UNION ALL queries which include a non-partitioned
348 : : * table, or when some of the hierarchies aren't run-time prunable. Build
349 : : * a bitmapset of the indexes of all such subplans, so that the executor
350 : : * can identify which subplans should never be pruned.
351 : : */
352 [ + + ]: 491 : if (bms_num_members(allmatchedsubplans) < list_length(subpaths))
353 : : {
354 : : Bitmapset *other_subplans;
355 : :
356 : : /* Create the complement of allmatchedsubplans */
357 : 30 : other_subplans = bms_add_range(NULL, 0, list_length(subpaths) - 1);
358 : 30 : other_subplans = bms_del_members(other_subplans, allmatchedsubplans);
359 : :
360 : 30 : pruneinfo->other_subplans = other_subplans;
361 : : }
362 : : else
363 : 461 : pruneinfo->other_subplans = NULL;
364 : :
365 : 491 : root->partPruneInfos = lappend(root->partPruneInfos, pruneinfo);
366 : :
367 : 491 : return list_length(root->partPruneInfos) - 1;
368 : : }
369 : :
370 : : /*
371 : : * add_part_relids
372 : : * Add new info to a list of Bitmapsets of partitioned relids.
373 : : *
374 : : * Within 'allpartrelids', there is one Bitmapset for each topmost parent
375 : : * partitioned rel. Each Bitmapset contains the RT indexes of the topmost
376 : : * parent as well as its relevant non-leaf child partitions. Since (by
377 : : * construction of the rangetable list) parent partitions must have lower
378 : : * RT indexes than their children, we can distinguish the topmost parent
379 : : * as being the lowest set bit in the Bitmapset.
380 : : *
381 : : * 'partrelids' contains the RT indexes of a parent partitioned rel, and
382 : : * possibly some non-leaf children, that are newly identified as parents of
383 : : * some subpath rel passed to make_partition_pruneinfo(). These are added
384 : : * to an appropriate member of 'allpartrelids'.
385 : : *
386 : : * Note that the list contains only RT indexes of partitioned tables that
387 : : * are parents of some scan-level relation appearing in the 'subpaths' that
388 : : * make_partition_pruneinfo() is dealing with. Also, "topmost" parents are
389 : : * not allowed to be higher than the 'parentrel' associated with the append
390 : : * path. In this way, we avoid expending cycles on partitioned rels that
391 : : * can't contribute useful pruning information for the problem at hand.
392 : : * (It is possible for 'parentrel' to be a child partitioned table, and it
393 : : * is also possible for scan-level relations to be child partitioned tables
394 : : * rather than leaf partitions. Hence we must construct this relation set
395 : : * with reference to the particular append path we're dealing with, rather
396 : : * than looking at the full partitioning structure represented in the
397 : : * RelOptInfos.)
398 : : */
399 : : static List *
400 : 11109 : add_part_relids(List *allpartrelids, Bitmapset *partrelids)
401 : : {
402 : : Index targetpart;
403 : : ListCell *lc;
404 : :
405 : : /* We can easily get the lowest set bit this way: */
406 : 11109 : targetpart = bms_next_member(partrelids, -1);
407 : : Assert(targetpart > 0);
408 : :
409 : : /* Look for a matching topmost parent */
410 [ + + + + : 11169 : foreach(lc, allpartrelids)
+ + ]
411 : : {
412 : 5141 : Bitmapset *currpartrelids = (Bitmapset *) lfirst(lc);
413 : 5141 : Index currtarget = bms_next_member(currpartrelids, -1);
414 : :
415 [ + + ]: 5141 : if (targetpart == currtarget)
416 : : {
417 : : /* Found a match, so add any new RT indexes to this hierarchy */
418 : 5081 : currpartrelids = bms_add_members(currpartrelids, partrelids);
419 : 5081 : lfirst(lc) = currpartrelids;
420 : 5081 : return allpartrelids;
421 : : }
422 : : }
423 : : /* No match, so add the new partition hierarchy to the list */
424 : 6028 : return lappend(allpartrelids, partrelids);
425 : : }
426 : :
427 : : /*
428 : : * make_partitionedrel_pruneinfo
429 : : * Build a List of PartitionedRelPruneInfos, one for each interesting
430 : : * partitioned rel in a partitioning hierarchy. These can be used in the
431 : : * executor to allow additional partition pruning to take place.
432 : : *
433 : : * parentrel: rel associated with the appendpath being considered
434 : : * prunequal: potential pruning quals, represented for parentrel
435 : : * partrelids: Set of RT indexes identifying relevant partitioned tables
436 : : * within a single partitioning hierarchy
437 : : * relid_subplan_map[]: maps child relation relids to subplan indexes
438 : : * matchedsubplans: on success, receives the set of subplan indexes which
439 : : * were matched to this partition hierarchy
440 : : *
441 : : * If we cannot find any useful run-time pruning steps, return NIL.
442 : : * However, on success, each rel identified in partrelids will have
443 : : * an element in the result list, even if some of them are useless.
444 : : */
445 : : static List *
446 : 6028 : make_partitionedrel_pruneinfo(PlannerInfo *root, RelOptInfo *parentrel,
447 : : List *prunequal,
448 : : Bitmapset *partrelids,
449 : : int *relid_subplan_map,
450 : : Bitmapset **matchedsubplans)
451 : : {
452 : 6028 : RelOptInfo *targetpart = NULL;
453 : 6028 : List *pinfolist = NIL;
454 : 6028 : bool doruntimeprune = false;
455 : : int *relid_subpart_map;
456 : 6028 : Bitmapset *subplansfound = NULL;
457 : : ListCell *lc;
458 : : int rti;
459 : : int i;
460 : :
461 : : /*
462 : : * Examine each partitioned rel, constructing a temporary array to map
463 : : * from planner relids to index of the partitioned rel, and building a
464 : : * PartitionedRelPruneInfo for each partitioned rel.
465 : : *
466 : : * In this phase we discover whether runtime pruning is needed at all; if
467 : : * not, we can avoid doing further work.
468 : : */
469 : 6028 : relid_subpart_map = palloc0_array(int, root->simple_rel_array_size);
470 : :
471 : 6028 : i = 1;
472 : 6028 : rti = -1;
473 [ + + ]: 13365 : while ((rti = bms_next_member(partrelids, rti)) > 0)
474 : : {
475 : 7342 : RelOptInfo *subpart = find_base_rel(root, rti);
476 : : PartitionedRelPruneInfo *pinfo;
477 : : List *partprunequal;
478 : : List *initial_pruning_steps;
479 : : List *exec_pruning_steps;
480 : : Bitmapset *execparamids;
481 : : GeneratePruningStepsContext context;
482 : :
483 : : /*
484 : : * Fill the mapping array.
485 : : *
486 : : * relid_subpart_map maps relid of a non-leaf partition to the index
487 : : * in the returned PartitionedRelPruneInfo list of the info for that
488 : : * partition. We use 1-based indexes here, so that zero can represent
489 : : * an un-filled array entry.
490 : : */
491 : : Assert(rti < root->simple_rel_array_size);
492 : 7342 : relid_subpart_map[rti] = i++;
493 : :
494 : : /*
495 : : * Translate pruning qual, if necessary, for this partition.
496 : : *
497 : : * The first item in the list is the target partitioned relation.
498 : : */
499 [ + + ]: 7342 : if (!targetpart)
500 : : {
501 : 6028 : targetpart = subpart;
502 : :
503 : : /*
504 : : * The prunequal is presented to us as a qual for 'parentrel'.
505 : : * Frequently this rel is the same as targetpart, so we can skip
506 : : * an adjust_appendrel_attrs step. But it might not be, and then
507 : : * we have to translate. We update the prunequal parameter here,
508 : : * because in later iterations of the loop for child partitions,
509 : : * we want to translate from parent to child variables.
510 : : */
511 [ + + ]: 6028 : if (!bms_equal(parentrel->relids, subpart->relids))
512 : : {
513 : : int nappinfos;
514 : 50 : AppendRelInfo **appinfos = find_appinfos_by_relids(root,
515 : : subpart->relids,
516 : : &nappinfos);
517 : :
518 : 50 : prunequal = (List *) adjust_appendrel_attrs(root, (Node *)
519 : : prunequal,
520 : : nappinfos,
521 : : appinfos);
522 : :
523 : 50 : pfree(appinfos);
524 : : }
525 : :
526 : 6028 : partprunequal = prunequal;
527 : : }
528 : : else
529 : : {
530 : : /*
531 : : * For sub-partitioned tables the columns may not be in the same
532 : : * order as the parent, so we must translate the prunequal to make
533 : : * it compatible with this relation.
534 : : */
535 : : partprunequal = (List *)
536 : 1314 : adjust_appendrel_attrs_multilevel(root,
537 : : (Node *) prunequal,
538 : : subpart,
539 : : targetpart);
540 : : }
541 : :
542 : : /*
543 : : * Convert pruning qual to pruning steps. We may need to do this
544 : : * twice, once to obtain executor startup pruning steps, and once for
545 : : * executor per-scan pruning steps. This first pass creates startup
546 : : * pruning steps and detects whether there's any possibly-useful quals
547 : : * that would require per-scan pruning.
548 : : */
549 : 7342 : gen_partprune_steps(subpart, partprunequal, PARTTARGET_INITIAL,
550 : : &context);
551 : :
552 [ + + ]: 7342 : if (context.contradictory)
553 : : {
554 : : /*
555 : : * This shouldn't happen as the planner should have detected this
556 : : * earlier. However, we do use additional quals from parameterized
557 : : * paths here. These do only compare Params to the partition key,
558 : : * so this shouldn't cause the discovery of any new qual
559 : : * contradictions that were not previously discovered as the Param
560 : : * values are unknown during planning. Anyway, we'd better do
561 : : * something sane here, so let's just disable run-time pruning.
562 : : */
563 : 5 : return NIL;
564 : : }
565 : :
566 : : /*
567 : : * If no mutable operators or expressions appear in usable pruning
568 : : * clauses, then there's no point in running startup pruning, because
569 : : * plan-time pruning should have pruned everything prunable.
570 : : */
571 [ + + + + ]: 7337 : if (context.has_mutable_op || context.has_mutable_arg)
572 : 311 : initial_pruning_steps = context.steps;
573 : : else
574 : 7026 : initial_pruning_steps = NIL;
575 : :
576 : : /*
577 : : * If no exec Params appear in potentially-usable pruning clauses,
578 : : * then there's no point in even thinking about per-scan pruning.
579 : : */
580 [ + + ]: 7337 : if (context.has_exec_param)
581 : : {
582 : : /* ... OK, we'd better think about it */
583 : 345 : gen_partprune_steps(subpart, partprunequal, PARTTARGET_EXEC,
584 : : &context);
585 : :
586 [ - + ]: 345 : if (context.contradictory)
587 : : {
588 : : /* As above, skip run-time pruning if anything fishy happens */
589 : 0 : return NIL;
590 : : }
591 : :
592 : 345 : exec_pruning_steps = context.steps;
593 : :
594 : : /*
595 : : * Detect which exec Params actually got used; the fact that some
596 : : * were in available clauses doesn't mean we actually used them.
597 : : * Skip per-scan pruning if there are none.
598 : : */
599 : 345 : execparamids = get_partkey_exec_paramids(exec_pruning_steps);
600 : :
601 [ - + ]: 345 : if (bms_is_empty(execparamids))
602 : 0 : exec_pruning_steps = NIL;
603 : : }
604 : : else
605 : : {
606 : : /* No exec Params anywhere, so forget about scan-time pruning */
607 : 6992 : exec_pruning_steps = NIL;
608 : 6992 : execparamids = NULL;
609 : : }
610 : :
611 [ + + + + ]: 7337 : if (initial_pruning_steps || exec_pruning_steps)
612 : 641 : doruntimeprune = true;
613 : :
614 : : /* Begin constructing the PartitionedRelPruneInfo for this rel */
615 : 7337 : pinfo = makeNode(PartitionedRelPruneInfo);
616 : 7337 : pinfo->rtindex = rti;
617 : 7337 : pinfo->initial_pruning_steps = initial_pruning_steps;
618 : 7337 : pinfo->exec_pruning_steps = exec_pruning_steps;
619 : 7337 : pinfo->execparamids = execparamids;
620 : : /* Remaining fields will be filled in the next loop */
621 : :
622 : 7337 : pinfolist = lappend(pinfolist, pinfo);
623 : : }
624 : :
625 [ + + ]: 6023 : if (!doruntimeprune)
626 : : {
627 : : /* No run-time pruning required. */
628 : 5522 : pfree(relid_subpart_map);
629 : 5522 : return NIL;
630 : : }
631 : :
632 : : /*
633 : : * Run-time pruning will be required, so initialize other information.
634 : : * That includes two maps -- one needed to convert partition indexes of
635 : : * leaf partitions to the indexes of their subplans in the subplan list,
636 : : * another needed to convert partition indexes of sub-partitioned
637 : : * partitions to the indexes of their PartitionedRelPruneInfo in the
638 : : * PartitionedRelPruneInfo list.
639 : : */
640 [ + - + + : 1354 : foreach(lc, pinfolist)
+ + ]
641 : : {
642 : 853 : PartitionedRelPruneInfo *pinfo = lfirst(lc);
643 : 853 : RelOptInfo *subpart = find_base_rel(root, pinfo->rtindex);
644 : : Bitmapset *present_parts;
645 : 853 : int nparts = subpart->nparts;
646 : : int *subplan_map;
647 : : int *subpart_map;
648 : : Oid *relid_map;
649 : : int *leafpart_rti_map;
650 : :
651 : : /*
652 : : * Construct the subplan and subpart maps for this partitioning level.
653 : : * Here we convert to zero-based indexes, with -1 for empty entries.
654 : : * Also construct a Bitmapset of all partitions that are present (that
655 : : * is, not pruned already).
656 : : */
657 : 853 : subplan_map = palloc_array(int, nparts);
658 : 853 : memset(subplan_map, -1, nparts * sizeof(int));
659 : 853 : subpart_map = palloc_array(int, nparts);
660 : 853 : memset(subpart_map, -1, nparts * sizeof(int));
661 : 853 : relid_map = palloc0_array(Oid, nparts);
662 : 853 : leafpart_rti_map = palloc0_array(int, nparts);
663 : 853 : present_parts = NULL;
664 : :
665 : 853 : i = -1;
666 [ + + ]: 3202 : while ((i = bms_next_member(subpart->live_parts, i)) >= 0)
667 : : {
668 : 2349 : RelOptInfo *partrel = subpart->part_rels[i];
669 : : int subplanidx;
670 : : int subpartidx;
671 : :
672 : : Assert(partrel != NULL);
673 : :
674 : 2349 : subplan_map[i] = subplanidx = relid_subplan_map[partrel->relid] - 1;
675 : 2349 : subpart_map[i] = subpartidx = relid_subpart_map[partrel->relid] - 1;
676 [ + - ]: 2349 : relid_map[i] = planner_rt_fetch(partrel->relid, root)->relid;
677 : :
678 : : /*
679 : : * Track the RT indexes of "leaf" partitions so they can be
680 : : * included in the PlannerGlobal.prunableRelids set, indicating
681 : : * relations that may be pruned during executor startup.
682 : : *
683 : : * Only leaf partitions with a valid subplan that are prunable
684 : : * using initial pruning are added to prunableRelids. So
685 : : * partitions without a subplan due to constraint exclusion will
686 : : * remain in PlannedStmt.unprunableRelids.
687 : : */
688 [ + + ]: 2349 : if (subplanidx >= 0)
689 : : {
690 : 1992 : present_parts = bms_add_member(present_parts, i);
691 : :
692 : : /*
693 : : * Non-leaf partitions may appear here when they use an
694 : : * unflattened Append or MergeAppend. These should not be
695 : : * included in prunableRelids.
696 : : */
697 [ + + ]: 1992 : if (partrel->nparts == -1)
698 : 1967 : leafpart_rti_map[i] = (int) partrel->relid;
699 : :
700 : : /* Record finding this subplan */
701 : 1992 : subplansfound = bms_add_member(subplansfound, subplanidx);
702 : : }
703 [ + + ]: 357 : else if (subpartidx >= 0)
704 : 352 : present_parts = bms_add_member(present_parts, i);
705 : : }
706 : :
707 : : /*
708 : : * Ensure there were no stray PartitionedRelPruneInfo generated for
709 : : * partitioned tables that we have no sub-paths or
710 : : * sub-PartitionedRelPruneInfo for.
711 : : */
712 : : Assert(!bms_is_empty(present_parts));
713 : :
714 : : /* Record the maps and other information. */
715 : 853 : pinfo->present_parts = present_parts;
716 : 853 : pinfo->nparts = nparts;
717 : 853 : pinfo->subplan_map = subplan_map;
718 : 853 : pinfo->subpart_map = subpart_map;
719 : 853 : pinfo->relid_map = relid_map;
720 : 853 : pinfo->leafpart_rti_map = leafpart_rti_map;
721 : : }
722 : :
723 : 501 : pfree(relid_subpart_map);
724 : :
725 : 501 : *matchedsubplans = subplansfound;
726 : :
727 : 501 : return pinfolist;
728 : : }
729 : :
730 : : /*
731 : : * gen_partprune_steps
732 : : * Process 'clauses' (typically a rel's baserestrictinfo list of clauses)
733 : : * and create a list of "partition pruning steps".
734 : : *
735 : : * 'target' tells whether to generate pruning steps for planning (use
736 : : * immutable clauses only), or for executor startup (use any allowable
737 : : * clause except ones containing PARAM_EXEC Params), or for executor
738 : : * per-scan pruning (use any allowable clause).
739 : : *
740 : : * 'context' is an output argument that receives the steps list as well as
741 : : * some subsidiary flags; see the GeneratePruningStepsContext typedef.
742 : : */
743 : : static void
744 : 16169 : gen_partprune_steps(RelOptInfo *rel, List *clauses, PartClauseTarget target,
745 : : GeneratePruningStepsContext *context)
746 : : {
747 : : /* Initialize all output values to zero/false/NULL */
748 : 16169 : memset(context, 0, sizeof(GeneratePruningStepsContext));
749 : 16169 : context->rel = rel;
750 : 16169 : context->target = target;
751 : :
752 : : /*
753 : : * If this partitioned table is in turn a partition, and it shares any
754 : : * partition keys with its parent, then it's possible that the hierarchy
755 : : * allows the parent a narrower range of values than some of its
756 : : * partitions (particularly the default one). This is normally not
757 : : * useful, but it can be to prune the default partition.
758 : : */
759 [ + + + + ]: 16169 : if (partition_bound_has_default(rel->boundinfo) && rel->partition_qual)
760 : : {
761 : : /* Make a copy to avoid modifying the passed-in List */
762 : 615 : clauses = list_concat_copy(clauses, rel->partition_qual);
763 : : }
764 : :
765 : : /* Down into the rabbit-hole. */
766 : 16169 : (void) gen_partprune_steps_internal(context, clauses);
767 : 16169 : }
768 : :
769 : : /*
770 : : * prune_append_rel_partitions
771 : : * Process rel's baserestrictinfo and make use of quals which can be
772 : : * evaluated during query planning in order to determine the minimum set
773 : : * of partitions which must be scanned to satisfy these quals. Returns
774 : : * the matching partitions in the form of a Bitmapset containing the
775 : : * partitions' indexes in the rel's part_rels array.
776 : : *
777 : : * Callers must ensure that 'rel' is a partitioned table.
778 : : */
779 : : Bitmapset *
780 : 14140 : prune_append_rel_partitions(RelOptInfo *rel)
781 : : {
782 : 14140 : List *clauses = rel->baserestrictinfo;
783 : : List *pruning_steps;
784 : : GeneratePruningStepsContext gcontext;
785 : : PartitionPruneContext context;
786 : :
787 : : Assert(rel->part_scheme != NULL);
788 : :
789 : : /* If there are no partitions, return the empty set */
790 [ - + ]: 14140 : if (rel->nparts == 0)
791 : 0 : return NULL;
792 : :
793 : : /*
794 : : * If pruning is disabled or if there are no clauses to prune with, return
795 : : * all partitions.
796 : : */
797 [ + + + + ]: 14140 : if (!enable_partition_pruning || clauses == NIL)
798 : 5658 : return bms_add_range(NULL, 0, rel->nparts - 1);
799 : :
800 : : /*
801 : : * Process clauses to extract pruning steps that are usable at plan time.
802 : : * If the clauses are found to be contradictory, we can return the empty
803 : : * set.
804 : : */
805 : 8482 : gen_partprune_steps(rel, clauses, PARTTARGET_PLANNER,
806 : : &gcontext);
807 [ + + ]: 8482 : if (gcontext.contradictory)
808 : 118 : return NULL;
809 : 8364 : pruning_steps = gcontext.steps;
810 : :
811 : : /* If there's nothing usable, return all partitions */
812 [ + + ]: 8364 : if (pruning_steps == NIL)
813 : 2542 : return bms_add_range(NULL, 0, rel->nparts - 1);
814 : :
815 : : /* Set up PartitionPruneContext */
816 : 5822 : context.strategy = rel->part_scheme->strategy;
817 : 5822 : context.partnatts = rel->part_scheme->partnatts;
818 : 5822 : context.nparts = rel->nparts;
819 : 5822 : context.boundinfo = rel->boundinfo;
820 : 5822 : context.partcollation = rel->part_scheme->partcollation;
821 : 5822 : context.partsupfunc = rel->part_scheme->partsupfunc;
822 : 5822 : context.stepcmpfuncs = palloc0_array(FmgrInfo,
823 : : context.partnatts * list_length(pruning_steps));
824 : 5822 : context.ppccontext = CurrentMemoryContext;
825 : :
826 : : /* These are not valid when being called from the planner */
827 : 5822 : context.planstate = NULL;
828 : 5822 : context.exprcontext = NULL;
829 : 5822 : context.exprstates = NULL;
830 : :
831 : : /* Actual pruning happens here. */
832 : 5822 : return get_matching_partitions(&context, pruning_steps);
833 : : }
834 : :
835 : : /*
836 : : * get_matching_partitions
837 : : * Determine partitions that survive partition pruning
838 : : *
839 : : * Note: context->exprcontext must be valid when the pruning_steps were
840 : : * generated with a target other than PARTTARGET_PLANNER.
841 : : *
842 : : * Returns a Bitmapset of the RelOptInfo->part_rels indexes of the surviving
843 : : * partitions.
844 : : */
845 : : Bitmapset *
846 : 8499 : get_matching_partitions(PartitionPruneContext *context, List *pruning_steps)
847 : : {
848 : : Bitmapset *result;
849 : 8499 : int num_steps = list_length(pruning_steps),
850 : : i;
851 : : PruneStepResult **results,
852 : : *final_result;
853 : : ListCell *lc;
854 : : bool scan_default;
855 : :
856 : : /* If there are no pruning steps then all partitions match. */
857 [ - + ]: 8499 : if (num_steps == 0)
858 : : {
859 : : Assert(context->nparts > 0);
860 : 0 : return bms_add_range(NULL, 0, context->nparts - 1);
861 : : }
862 : :
863 : : /*
864 : : * Allocate space for individual pruning steps to store its result. Each
865 : : * slot will hold a PruneStepResult after performing a given pruning step.
866 : : * Later steps may use the result of one or more earlier steps. The
867 : : * result of applying all pruning steps is the value contained in the slot
868 : : * of the last pruning step.
869 : : */
870 : 8499 : results = palloc0_array(PruneStepResult *, num_steps);
871 [ + - + + : 21132 : foreach(lc, pruning_steps)
+ + ]
872 : : {
873 : 12633 : PartitionPruneStep *step = lfirst(lc);
874 : :
875 [ + + - ]: 12633 : switch (nodeTag(step))
876 : : {
877 : 10498 : case T_PartitionPruneStepOp:
878 : 20996 : results[step->step_id] =
879 : 10498 : perform_pruning_base_step(context,
880 : : (PartitionPruneStepOp *) step);
881 : 10498 : break;
882 : :
883 : 2135 : case T_PartitionPruneStepCombine:
884 : 4270 : results[step->step_id] =
885 : 2135 : perform_pruning_combine_step(context,
886 : : (PartitionPruneStepCombine *) step,
887 : : results);
888 : 2135 : break;
889 : :
890 : 0 : default:
891 [ # # ]: 0 : elog(ERROR, "invalid pruning step type: %d",
892 : : (int) nodeTag(step));
893 : : }
894 : : }
895 : :
896 : : /*
897 : : * At this point we know the offsets of all the datums whose corresponding
898 : : * partitions need to be in the result, including special null-accepting
899 : : * and default partitions. Collect the actual partition indexes now.
900 : : */
901 : 8499 : final_result = results[num_steps - 1];
902 : : Assert(final_result != NULL);
903 : 8499 : i = -1;
904 : 8499 : result = NULL;
905 : 8499 : scan_default = final_result->scan_default;
906 [ + + ]: 17557 : while ((i = bms_next_member(final_result->bound_offsets, i)) >= 0)
907 : : {
908 : : int partindex;
909 : :
910 : : Assert(i < context->boundinfo->nindexes);
911 : 9058 : partindex = context->boundinfo->indexes[i];
912 : :
913 [ + + ]: 9058 : if (partindex < 0)
914 : : {
915 : : /*
916 : : * In range partitioning cases, if a partition index is -1 it
917 : : * means that the bound at the offset is the upper bound for a
918 : : * range not covered by any partition (other than a possible
919 : : * default partition). In hash partitioning, the same means no
920 : : * partition has been defined for the corresponding remainder
921 : : * value.
922 : : *
923 : : * In either case, the value is still part of the queried range of
924 : : * values, so mark to scan the default partition if one exists.
925 : : */
926 : 1140 : scan_default |= partition_bound_has_default(context->boundinfo);
927 : 1140 : continue;
928 : : }
929 : :
930 : 7918 : result = bms_add_member(result, partindex);
931 : : }
932 : :
933 : : /* Add the null and/or default partition if needed and present. */
934 [ + + ]: 8499 : if (final_result->scan_null)
935 : : {
936 : : Assert(context->strategy == PARTITION_STRATEGY_LIST);
937 : : Assert(partition_bound_accepts_nulls(context->boundinfo));
938 : 140 : result = bms_add_member(result, context->boundinfo->null_index);
939 : : }
940 [ + + ]: 8499 : if (scan_default)
941 : : {
942 : : Assert(context->strategy == PARTITION_STRATEGY_LIST ||
943 : : context->strategy == PARTITION_STRATEGY_RANGE);
944 : : Assert(partition_bound_has_default(context->boundinfo));
945 : 626 : result = bms_add_member(result, context->boundinfo->default_index);
946 : : }
947 : :
948 : 8499 : return result;
949 : : }
950 : :
951 : : /*
952 : : * gen_partprune_steps_internal
953 : : * Processes 'clauses' to generate a List of partition pruning steps. We
954 : : * return NIL when no steps were generated.
955 : : *
956 : : * These partition pruning steps come in 2 forms; operator steps and combine
957 : : * steps.
958 : : *
959 : : * Operator steps (PartitionPruneStepOp) contain details of clauses that we
960 : : * determined that we can use for partition pruning. These contain details of
961 : : * the expression which is being compared to the partition key and the
962 : : * comparison function.
963 : : *
964 : : * Combine steps (PartitionPruneStepCombine) instruct the partition pruning
965 : : * code how it should produce a single set of partitions from multiple input
966 : : * operator and other combine steps. A PARTPRUNE_COMBINE_INTERSECT type
967 : : * combine step will merge its input steps to produce a result which only
968 : : * contains the partitions which are present in all of the input operator
969 : : * steps. A PARTPRUNE_COMBINE_UNION combine step will produce a result that
970 : : * has all of the partitions from each of the input operator steps.
971 : : *
972 : : * For BoolExpr clauses, each argument is processed recursively. Steps
973 : : * generated from processing an OR BoolExpr will be combined using
974 : : * PARTPRUNE_COMBINE_UNION. AND BoolExprs get combined using
975 : : * PARTPRUNE_COMBINE_INTERSECT.
976 : : *
977 : : * Otherwise, the list of clauses we receive we assume to be mutually ANDed.
978 : : * We generate all of the pruning steps we can based on these clauses and then
979 : : * at the end, if we have more than 1 step, we combine each step with a
980 : : * PARTPRUNE_COMBINE_INTERSECT combine step. Single steps are returned as-is.
981 : : *
982 : : * If we find clauses that are mutually contradictory, or contradictory with
983 : : * the partitioning constraint, or a pseudoconstant clause that contains
984 : : * false, we set context->contradictory to true and return NIL (that is, no
985 : : * pruning steps). Caller should consider all partitions as pruned in that
986 : : * case.
987 : : */
988 : : static List *
989 : 20931 : gen_partprune_steps_internal(GeneratePruningStepsContext *context,
990 : : List *clauses)
991 : : {
992 : 20931 : PartitionScheme part_scheme = context->rel->part_scheme;
993 : : List *keyclauses[PARTITION_MAX_KEYS];
994 : 20931 : Bitmapset *nullkeys = NULL,
995 : 20931 : *notnullkeys = NULL;
996 : 20931 : bool generate_opsteps = false;
997 : 20931 : List *result = NIL;
998 : : ListCell *lc;
999 : :
1000 : : /*
1001 : : * If this partitioned relation has a default partition and is itself a
1002 : : * partition (as evidenced by partition_qual being not NIL), we first
1003 : : * check if the clauses contradict the partition constraint. If they do,
1004 : : * there's no need to generate any steps as it'd already be proven that no
1005 : : * partitions need to be scanned.
1006 : : *
1007 : : * This is a measure of last resort only to be used because the default
1008 : : * partition cannot be pruned using the steps generated from clauses that
1009 : : * contradict the parent's partition constraint; regular pruning, which is
1010 : : * cheaper, is sufficient when no default partition exists.
1011 : : */
1012 [ + + + + ]: 27015 : if (partition_bound_has_default(context->rel->boundinfo) &&
1013 : 6084 : predicate_refuted_by(context->rel->partition_qual, clauses, false))
1014 : : {
1015 : 235 : context->contradictory = true;
1016 : 235 : return NIL;
1017 : : }
1018 : :
1019 : 20696 : memset(keyclauses, 0, sizeof(keyclauses));
1020 [ + - + + : 49433 : foreach(lc, clauses)
+ + ]
1021 : : {
1022 : 28855 : Expr *clause = (Expr *) lfirst(lc);
1023 : : int i;
1024 : :
1025 : : /* Look through RestrictInfo, if any */
1026 [ + + ]: 28855 : if (IsA(clause, RestrictInfo))
1027 : 11300 : clause = ((RestrictInfo *) clause)->clause;
1028 : :
1029 : : /* Constant-false-or-null is contradictory */
1030 [ + + ]: 28855 : if (IsA(clause, Const) &&
1031 [ + - ]: 68 : (((Const *) clause)->constisnull ||
1032 [ + - ]: 68 : !DatumGetBool(((Const *) clause)->constvalue)))
1033 : : {
1034 : 68 : context->contradictory = true;
1035 : 118 : return NIL;
1036 : : }
1037 : :
1038 : : /* Get the BoolExpr's out of the way. */
1039 [ + + ]: 28787 : if (IsA(clause, BoolExpr))
1040 : : {
1041 : : /*
1042 : : * Generate steps for arguments.
1043 : : *
1044 : : * While steps generated for the arguments themselves will be
1045 : : * added to context->steps during recursion and will be evaluated
1046 : : * independently, collect their step IDs to be stored in the
1047 : : * combine step we'll be creating.
1048 : : */
1049 [ + + ]: 2518 : if (is_orclause(clause))
1050 : 1662 : {
1051 : 1662 : List *arg_stepids = NIL;
1052 : 1662 : bool all_args_contradictory = true;
1053 : : ListCell *lc1;
1054 : :
1055 : : /*
1056 : : * We can share the outer context area with the recursive
1057 : : * call, but contradictory had better not be true yet.
1058 : : */
1059 : : Assert(!context->contradictory);
1060 : :
1061 : : /*
1062 : : * Get pruning step for each arg. If we get contradictory for
1063 : : * all args, it means the OR expression is false as a whole.
1064 : : */
1065 [ + - + + : 5247 : foreach(lc1, ((BoolExpr *) clause)->args)
+ + ]
1066 : : {
1067 : 3585 : Expr *arg = lfirst(lc1);
1068 : : bool arg_contradictory;
1069 : : List *argsteps;
1070 : :
1071 : 3585 : argsteps = gen_partprune_steps_internal(context,
1072 : : list_make1(arg));
1073 : 3585 : arg_contradictory = context->contradictory;
1074 : : /* Keep context->contradictory clear till we're done */
1075 : 3585 : context->contradictory = false;
1076 : :
1077 [ + + ]: 3585 : if (arg_contradictory)
1078 : : {
1079 : : /* Just ignore self-contradictory arguments. */
1080 : 230 : continue;
1081 : : }
1082 : : else
1083 : 3355 : all_args_contradictory = false;
1084 : :
1085 [ + + ]: 3355 : if (argsteps != NIL)
1086 : : {
1087 : : /*
1088 : : * gen_partprune_steps_internal() always adds a single
1089 : : * combine step when it generates multiple steps, so
1090 : : * here we can just pay attention to the last one in
1091 : : * the list. If it just generated one, then the last
1092 : : * one in the list is still the one we want.
1093 : : */
1094 : 2887 : PartitionPruneStep *last = llast(argsteps);
1095 : :
1096 : 2887 : arg_stepids = lappend_int(arg_stepids, last->step_id);
1097 : : }
1098 : : else
1099 : : {
1100 : : PartitionPruneStep *orstep;
1101 : :
1102 : : /*
1103 : : * The arg didn't contain a clause matching this
1104 : : * partition key. We cannot prune using such an arg.
1105 : : * To indicate that to the pruning code, we must
1106 : : * construct a dummy PartitionPruneStepCombine whose
1107 : : * source_stepids is set to an empty List.
1108 : : */
1109 : 468 : orstep = gen_prune_step_combine(context, NIL,
1110 : : PARTPRUNE_COMBINE_UNION);
1111 : 468 : arg_stepids = lappend_int(arg_stepids, orstep->step_id);
1112 : : }
1113 : : }
1114 : :
1115 : : /* If all the OR arms are contradictory, we can stop */
1116 [ - + ]: 1662 : if (all_args_contradictory)
1117 : : {
1118 : 0 : context->contradictory = true;
1119 : 0 : return NIL;
1120 : : }
1121 : :
1122 [ + - ]: 1662 : if (arg_stepids != NIL)
1123 : : {
1124 : : PartitionPruneStep *step;
1125 : :
1126 : 1662 : step = gen_prune_step_combine(context, arg_stepids,
1127 : : PARTPRUNE_COMBINE_UNION);
1128 : 1662 : result = lappend(result, step);
1129 : : }
1130 : 1662 : continue;
1131 : : }
1132 [ + + ]: 856 : else if (is_andclause(clause))
1133 : 656 : {
1134 : 656 : List *args = ((BoolExpr *) clause)->args;
1135 : : List *argsteps;
1136 : :
1137 : : /*
1138 : : * args may itself contain clauses of arbitrary type, so just
1139 : : * recurse and later combine the component partitions sets
1140 : : * using a combine step.
1141 : : */
1142 : 656 : argsteps = gen_partprune_steps_internal(context, args);
1143 : :
1144 : : /* If any AND arm is contradictory, we can stop immediately */
1145 [ - + ]: 656 : if (context->contradictory)
1146 : 0 : return NIL;
1147 : :
1148 : : /*
1149 : : * gen_partprune_steps_internal() always adds a single combine
1150 : : * step when it generates multiple steps, so here we can just
1151 : : * pay attention to the last one in the list. If it just
1152 : : * generated one, then the last one in the list is still the
1153 : : * one we want.
1154 : : */
1155 [ + + ]: 656 : if (argsteps != NIL)
1156 : 486 : result = lappend(result, llast(argsteps));
1157 : :
1158 : 656 : continue;
1159 : : }
1160 : :
1161 : : /*
1162 : : * Fall-through for a NOT clause, which if it's a Boolean clause,
1163 : : * will be handled in match_clause_to_partition_key(). We
1164 : : * currently don't perform any pruning for more complex NOT
1165 : : * clauses.
1166 : : */
1167 : : }
1168 : :
1169 : : /*
1170 : : * See if we can match this clause to any of the partition keys.
1171 : : */
1172 [ + + ]: 36831 : for (i = 0; i < part_scheme->partnatts; i++)
1173 : : {
1174 : 29889 : Expr *partkey = linitial(context->rel->partexprs[i]);
1175 : 29889 : bool clause_is_not_null = false;
1176 : 29889 : PartClauseInfo *pc = NULL;
1177 : 29889 : List *clause_steps = NIL;
1178 : :
1179 [ + + + + : 29889 : switch (match_clause_to_partition_key(context,
+ + - ]
1180 : : clause, partkey, i,
1181 : : &clause_is_not_null,
1182 : : &pc, &clause_steps))
1183 : : {
1184 : 15442 : case PARTCLAUSE_MATCH_CLAUSE:
1185 : : Assert(pc != NULL);
1186 : :
1187 : : /*
1188 : : * Since we only allow strict operators, check for any
1189 : : * contradicting IS NULL.
1190 : : */
1191 [ + + ]: 15442 : if (bms_is_member(i, nullkeys))
1192 : : {
1193 : 5 : context->contradictory = true;
1194 : 50 : return NIL;
1195 : : }
1196 : 15437 : generate_opsteps = true;
1197 : 15437 : keyclauses[i] = lappend(keyclauses[i], pc);
1198 : 15437 : break;
1199 : :
1200 : 1880 : case PARTCLAUSE_MATCH_NULLNESS:
1201 [ + + ]: 1880 : if (!clause_is_not_null)
1202 : : {
1203 : : /*
1204 : : * check for conflicting IS NOT NULL as well as
1205 : : * contradicting strict clauses
1206 : : */
1207 [ + + ]: 1385 : if (bms_is_member(i, notnullkeys) ||
1208 [ + + ]: 1380 : keyclauses[i] != NIL)
1209 : : {
1210 : 25 : context->contradictory = true;
1211 : 25 : return NIL;
1212 : : }
1213 : 1360 : nullkeys = bms_add_member(nullkeys, i);
1214 : : }
1215 : : else
1216 : : {
1217 : : /* check for conflicting IS NULL */
1218 [ - + ]: 495 : if (bms_is_member(i, nullkeys))
1219 : : {
1220 : 0 : context->contradictory = true;
1221 : 0 : return NIL;
1222 : : }
1223 : 495 : notnullkeys = bms_add_member(notnullkeys, i);
1224 : : }
1225 : 1855 : break;
1226 : :
1227 : 521 : case PARTCLAUSE_MATCH_STEPS:
1228 : : Assert(clause_steps != NIL);
1229 : 521 : result = list_concat(result, clause_steps);
1230 : 521 : break;
1231 : :
1232 : 20 : case PARTCLAUSE_MATCH_CONTRADICT:
1233 : : /* We've nothing more to do if a contradiction was found. */
1234 : 20 : context->contradictory = true;
1235 : 20 : return NIL;
1236 : :
1237 : 10362 : case PARTCLAUSE_NOMATCH:
1238 : :
1239 : : /*
1240 : : * Clause didn't match this key, but it might match the
1241 : : * next one.
1242 : : */
1243 : 10362 : continue;
1244 : :
1245 : 1664 : case PARTCLAUSE_UNSUPPORTED:
1246 : : /* This clause cannot be used for pruning. */
1247 : 1664 : break;
1248 : : }
1249 : :
1250 : : /* done; go check the next clause. */
1251 : 19477 : break;
1252 : : }
1253 : : }
1254 : :
1255 : : /*-----------
1256 : : * Now generate some (more) pruning steps. We have three strategies:
1257 : : *
1258 : : * 1) Generate pruning steps based on IS NULL clauses:
1259 : : * a) For list partitioning, null partition keys can only be found in
1260 : : * the designated null-accepting partition, so if there are IS NULL
1261 : : * clauses containing partition keys we should generate a pruning
1262 : : * step that gets rid of all partitions but that one. We can
1263 : : * disregard any OpExpr we may have found.
1264 : : * b) For range partitioning, only the default partition can contain
1265 : : * NULL values, so the same rationale applies.
1266 : : * c) For hash partitioning, we only apply this strategy if we have
1267 : : * IS NULL clauses for all the keys. Strategy 2 below will take
1268 : : * care of the case where some keys have OpExprs and others have
1269 : : * IS NULL clauses.
1270 : : *
1271 : : * 2) If not, generate steps based on OpExprs we have (if any).
1272 : : *
1273 : : * 3) If this doesn't work either, we may be able to generate steps to
1274 : : * prune just the null-accepting partition (if one exists), if we have
1275 : : * IS NOT NULL clauses for all partition keys.
1276 : : */
1277 [ + + ]: 20578 : if (!bms_is_empty(nullkeys) &&
1278 [ + + ]: 985 : (part_scheme->strategy == PARTITION_STRATEGY_LIST ||
1279 [ + + ]: 475 : part_scheme->strategy == PARTITION_STRATEGY_RANGE ||
1280 [ + - ]: 370 : (part_scheme->strategy == PARTITION_STRATEGY_HASH &&
1281 [ + + ]: 370 : bms_num_members(nullkeys) == part_scheme->partnatts)))
1282 : 655 : {
1283 : : PartitionPruneStep *step;
1284 : :
1285 : : /* Strategy 1 */
1286 : 655 : step = gen_prune_step_op(context, InvalidStrategy,
1287 : : false, NIL, NIL, nullkeys);
1288 : 655 : result = lappend(result, step);
1289 : : }
1290 [ + + ]: 19923 : else if (generate_opsteps)
1291 : : {
1292 : : List *opsteps;
1293 : :
1294 : : /* Strategy 2 */
1295 : 13302 : opsteps = gen_prune_steps_from_opexps(context, keyclauses, nullkeys);
1296 : 13302 : result = list_concat(result, opsteps);
1297 : : }
1298 [ + + ]: 6621 : else if (bms_num_members(notnullkeys) == part_scheme->partnatts)
1299 : : {
1300 : : PartitionPruneStep *step;
1301 : :
1302 : : /* Strategy 3 */
1303 : 160 : step = gen_prune_step_op(context, InvalidStrategy,
1304 : : false, NIL, NIL, NULL);
1305 : 160 : result = lappend(result, step);
1306 : : }
1307 : :
1308 : : /*
1309 : : * Finally, if there are multiple steps, since the 'clauses' are mutually
1310 : : * ANDed, add an INTERSECT step to combine the partition sets resulting
1311 : : * from them and append it to the result list.
1312 : : */
1313 [ + + ]: 20578 : if (list_length(result) > 1)
1314 : : {
1315 : 1480 : List *step_ids = NIL;
1316 : : PartitionPruneStep *final;
1317 : :
1318 [ + - + + : 5355 : foreach(lc, result)
+ + ]
1319 : : {
1320 : 3875 : PartitionPruneStep *step = lfirst(lc);
1321 : :
1322 : 3875 : step_ids = lappend_int(step_ids, step->step_id);
1323 : : }
1324 : :
1325 : 1480 : final = gen_prune_step_combine(context, step_ids,
1326 : : PARTPRUNE_COMBINE_INTERSECT);
1327 : 1480 : result = lappend(result, final);
1328 : : }
1329 : :
1330 : 20578 : return result;
1331 : : }
1332 : :
1333 : : /*
1334 : : * gen_prune_step_op
1335 : : * Generate a pruning step for a specific operator
1336 : : *
1337 : : * The step is assigned a unique step identifier and added to context's 'steps'
1338 : : * list.
1339 : : */
1340 : : static PartitionPruneStep *
1341 : 15507 : gen_prune_step_op(GeneratePruningStepsContext *context,
1342 : : StrategyNumber opstrategy, bool op_is_ne,
1343 : : List *exprs, List *cmpfns,
1344 : : Bitmapset *nullkeys)
1345 : : {
1346 : 15507 : PartitionPruneStepOp *opstep = makeNode(PartitionPruneStepOp);
1347 : :
1348 : 15507 : opstep->step.step_id = context->next_step_id++;
1349 : :
1350 : : /*
1351 : : * For clauses that contain an <> operator, set opstrategy to
1352 : : * InvalidStrategy to signal get_matching_list_bounds to do the right
1353 : : * thing.
1354 : : */
1355 [ + + ]: 15507 : opstep->opstrategy = op_is_ne ? InvalidStrategy : opstrategy;
1356 : : Assert(list_length(exprs) == list_length(cmpfns));
1357 : 15507 : opstep->exprs = exprs;
1358 : 15507 : opstep->cmpfns = cmpfns;
1359 : 15507 : opstep->nullkeys = nullkeys;
1360 : :
1361 : 15507 : context->steps = lappend(context->steps, opstep);
1362 : :
1363 : 15507 : return (PartitionPruneStep *) opstep;
1364 : : }
1365 : :
1366 : : /*
1367 : : * gen_prune_step_combine
1368 : : * Generate a pruning step for a combination of several other steps
1369 : : *
1370 : : * The step is assigned a unique step identifier and added to context's
1371 : : * 'steps' list.
1372 : : */
1373 : : static PartitionPruneStep *
1374 : 3610 : gen_prune_step_combine(GeneratePruningStepsContext *context,
1375 : : List *source_stepids,
1376 : : PartitionPruneCombineOp combineOp)
1377 : : {
1378 : 3610 : PartitionPruneStepCombine *cstep = makeNode(PartitionPruneStepCombine);
1379 : :
1380 : 3610 : cstep->step.step_id = context->next_step_id++;
1381 : 3610 : cstep->combineOp = combineOp;
1382 : 3610 : cstep->source_stepids = source_stepids;
1383 : :
1384 : 3610 : context->steps = lappend(context->steps, cstep);
1385 : :
1386 : 3610 : return (PartitionPruneStep *) cstep;
1387 : : }
1388 : :
1389 : : /*
1390 : : * gen_prune_steps_from_opexps
1391 : : * Generate and return a list of PartitionPruneStepOp that are based on
1392 : : * OpExpr and BooleanTest clauses that have been matched to the partition
1393 : : * key.
1394 : : *
1395 : : * 'keyclauses' is an array of List pointers, indexed by the partition key's
1396 : : * index. Each List element in the array can contain clauses that match to
1397 : : * the corresponding partition key column. Partition key columns without any
1398 : : * matched clauses will have an empty List.
1399 : : *
1400 : : * Some partitioning strategies allow pruning to still occur when we only have
1401 : : * clauses for a prefix of the partition key columns, for example, RANGE
1402 : : * partitioning. Other strategies, such as HASH partitioning, require clauses
1403 : : * for all partition key columns.
1404 : : *
1405 : : * When we return multiple pruning steps here, it's up to the caller to add a
1406 : : * relevant "combine" step to combine the returned steps. This is not done
1407 : : * here as callers may wish to include additional pruning steps before
1408 : : * combining them all.
1409 : : */
1410 : : static List *
1411 : 13302 : gen_prune_steps_from_opexps(GeneratePruningStepsContext *context,
1412 : : List **keyclauses, Bitmapset *nullkeys)
1413 : : {
1414 : 13302 : PartitionScheme part_scheme = context->rel->part_scheme;
1415 : 13302 : List *opsteps = NIL;
1416 : : List *btree_clauses[BTMaxStrategyNumber + 1],
1417 : : *hash_clauses[HTMaxStrategyNumber + 1];
1418 : : int i;
1419 : : ListCell *lc;
1420 : :
1421 : 13302 : memset(btree_clauses, 0, sizeof(btree_clauses));
1422 : 13302 : memset(hash_clauses, 0, sizeof(hash_clauses));
1423 [ + + ]: 26067 : for (i = 0; i < part_scheme->partnatts; i++)
1424 : : {
1425 : 15292 : List *clauselist = keyclauses[i];
1426 : 15292 : bool consider_next_key = true;
1427 : :
1428 : : /*
1429 : : * For range partitioning, if we have no clauses for the current key,
1430 : : * we can't consider any later keys either, so we can stop here.
1431 : : */
1432 [ + + + + ]: 15292 : if (part_scheme->strategy == PARTITION_STRATEGY_RANGE &&
1433 : : clauselist == NIL)
1434 : 530 : break;
1435 : :
1436 : : /*
1437 : : * For hash partitioning, if a column doesn't have the necessary
1438 : : * equality clause, there should be an IS NULL clause, otherwise
1439 : : * pruning is not possible.
1440 : : */
1441 [ + + + + ]: 14762 : if (part_scheme->strategy == PARTITION_STRATEGY_HASH &&
1442 [ + + ]: 645 : clauselist == NIL && !bms_is_member(i, nullkeys))
1443 : 60 : return NIL;
1444 : :
1445 [ + + + + : 29839 : foreach(lc, clauselist)
+ + ]
1446 : : {
1447 : 15137 : PartClauseInfo *pc = (PartClauseInfo *) lfirst(lc);
1448 : : Oid lefttype,
1449 : : righttype;
1450 : :
1451 : : /* Look up the operator's btree/hash strategy number. */
1452 [ + + ]: 15137 : if (pc->op_strategy == InvalidStrategy)
1453 : 525 : get_op_opfamily_properties(pc->opno,
1454 : 525 : part_scheme->partopfamily[i],
1455 : : false,
1456 : : &pc->op_strategy,
1457 : : &lefttype,
1458 : : &righttype);
1459 : :
1460 [ + + - ]: 15137 : switch (part_scheme->strategy)
1461 : : {
1462 : 14238 : case PARTITION_STRATEGY_LIST:
1463 : : case PARTITION_STRATEGY_RANGE:
1464 : 28476 : btree_clauses[pc->op_strategy] =
1465 : 14238 : lappend(btree_clauses[pc->op_strategy], pc);
1466 : :
1467 : : /*
1468 : : * We can't consider subsequent partition keys if the
1469 : : * clause for the current key contains a non-inclusive
1470 : : * operator.
1471 : : */
1472 [ + + ]: 14238 : if (pc->op_strategy == BTLessStrategyNumber ||
1473 [ + + ]: 12750 : pc->op_strategy == BTGreaterStrategyNumber)
1474 : 2072 : consider_next_key = false;
1475 : 14238 : break;
1476 : :
1477 : 899 : case PARTITION_STRATEGY_HASH:
1478 [ - + ]: 899 : if (pc->op_strategy != HTEqualStrategyNumber)
1479 [ # # ]: 0 : elog(ERROR, "invalid clause for hash partitioning");
1480 : 1798 : hash_clauses[pc->op_strategy] =
1481 : 899 : lappend(hash_clauses[pc->op_strategy], pc);
1482 : 899 : break;
1483 : :
1484 : 0 : default:
1485 [ # # ]: 0 : elog(ERROR, "invalid partition strategy: %c",
1486 : : part_scheme->strategy);
1487 : : break;
1488 : : }
1489 : : }
1490 : :
1491 : : /*
1492 : : * If we've decided that clauses for subsequent partition keys
1493 : : * wouldn't be useful for pruning, don't search any further.
1494 : : */
1495 [ + + ]: 14702 : if (!consider_next_key)
1496 : 1937 : break;
1497 : : }
1498 : :
1499 : : /*
1500 : : * Now, we have divided clauses according to their operator strategies.
1501 : : * Check for each strategy if we can generate pruning step(s) by
1502 : : * collecting a list of expressions whose values will constitute a vector
1503 : : * that can be used as a lookup key by a partition bound searching
1504 : : * function.
1505 : : */
1506 [ + + - ]: 13242 : switch (part_scheme->strategy)
1507 : : {
1508 : 12768 : case PARTITION_STRATEGY_LIST:
1509 : : case PARTITION_STRATEGY_RANGE:
1510 : : {
1511 : 12768 : List *eq_clauses = btree_clauses[BTEqualStrategyNumber];
1512 : 12768 : List *le_clauses = btree_clauses[BTLessEqualStrategyNumber];
1513 : 12768 : List *ge_clauses = btree_clauses[BTGreaterEqualStrategyNumber];
1514 : : int strat;
1515 : :
1516 : : /*
1517 : : * For each clause under consideration for a given strategy,
1518 : : * we collect expressions from clauses for earlier keys, whose
1519 : : * operator strategy is inclusive, into a list called
1520 : : * 'prefix'. By appending the clause's own expression to the
1521 : : * 'prefix', we'll generate one step using the so generated
1522 : : * vector and assign the current strategy to it. Actually,
1523 : : * 'prefix' might contain multiple clauses for the same key,
1524 : : * in which case, we must generate steps for various
1525 : : * combinations of expressions of different keys, which
1526 : : * get_steps_using_prefix takes care of for us.
1527 : : */
1528 [ + + ]: 76608 : for (strat = 1; strat <= BTMaxStrategyNumber; strat++)
1529 : : {
1530 [ + + + + : 78028 : foreach(lc, btree_clauses[strat])
+ + ]
1531 : : {
1532 : 14228 : PartClauseInfo *pc = lfirst(lc);
1533 : : ListCell *eq_start;
1534 : : ListCell *le_start;
1535 : : ListCell *ge_start;
1536 : : ListCell *lc1;
1537 : 14228 : List *prefix = NIL;
1538 : : List *pc_steps;
1539 : 14228 : bool prefix_valid = true;
1540 : : bool pk_has_clauses;
1541 : : int keyno;
1542 : :
1543 : : /*
1544 : : * If this is a clause for the first partition key,
1545 : : * there are no preceding expressions; generate a
1546 : : * pruning step without a prefix.
1547 : : *
1548 : : * Note that we pass NULL for step_nullkeys, because
1549 : : * we don't search list/range partition bounds where
1550 : : * some keys are NULL.
1551 : : */
1552 [ + + ]: 14228 : if (pc->keyno == 0)
1553 : : {
1554 : : Assert(pc->op_strategy == strat);
1555 : 13638 : pc_steps = get_steps_using_prefix(context, strat,
1556 : 13638 : pc->op_is_ne,
1557 : : pc->expr,
1558 : : pc->cmpfn,
1559 : : NULL,
1560 : : NIL);
1561 : 13638 : opsteps = list_concat(opsteps, pc_steps);
1562 : 13638 : continue;
1563 : : }
1564 : :
1565 : 590 : eq_start = list_head(eq_clauses);
1566 : 590 : le_start = list_head(le_clauses);
1567 : 590 : ge_start = list_head(ge_clauses);
1568 : :
1569 : : /*
1570 : : * We arrange clauses into prefix in ascending order
1571 : : * of their partition key numbers.
1572 : : */
1573 [ + + ]: 1310 : for (keyno = 0; keyno < pc->keyno; keyno++)
1574 : : {
1575 : 760 : pk_has_clauses = false;
1576 : :
1577 : : /*
1578 : : * Expressions from = clauses can always be in the
1579 : : * prefix, provided they're from an earlier key.
1580 : : */
1581 [ + + + + : 1375 : for_each_cell(lc1, eq_clauses, eq_start)
+ + ]
1582 : : {
1583 : 1145 : PartClauseInfo *eqpc = lfirst(lc1);
1584 : :
1585 [ + + ]: 1145 : if (eqpc->keyno == keyno)
1586 : : {
1587 : 615 : prefix = lappend(prefix, eqpc);
1588 : 615 : pk_has_clauses = true;
1589 : : }
1590 : : else
1591 : : {
1592 : : Assert(eqpc->keyno > keyno);
1593 : 530 : break;
1594 : : }
1595 : : }
1596 : 760 : eq_start = lc1;
1597 : :
1598 : : /*
1599 : : * If we're generating steps for </<= strategy, we
1600 : : * can add other <= clauses to the prefix,
1601 : : * provided they're from an earlier key.
1602 : : */
1603 [ + + + + ]: 760 : if (strat == BTLessStrategyNumber ||
1604 : : strat == BTLessEqualStrategyNumber)
1605 : : {
1606 [ + + + + : 95 : for_each_cell(lc1, le_clauses, le_start)
+ + ]
1607 : : {
1608 : 25 : PartClauseInfo *lepc = lfirst(lc1);
1609 : :
1610 [ + + ]: 25 : if (lepc->keyno == keyno)
1611 : : {
1612 : 15 : prefix = lappend(prefix, lepc);
1613 : 15 : pk_has_clauses = true;
1614 : : }
1615 : : else
1616 : : {
1617 : : Assert(lepc->keyno > keyno);
1618 : 10 : break;
1619 : : }
1620 : : }
1621 : 80 : le_start = lc1;
1622 : : }
1623 : :
1624 : : /*
1625 : : * If we're generating steps for >/>= strategy, we
1626 : : * can add other >= clauses to the prefix,
1627 : : * provided they're from an earlier key.
1628 : : */
1629 [ + + + + ]: 760 : if (strat == BTGreaterStrategyNumber ||
1630 : : strat == BTGreaterEqualStrategyNumber)
1631 : : {
1632 [ + + + - : 330 : for_each_cell(lc1, ge_clauses, ge_start)
+ + ]
1633 : : {
1634 : 250 : PartClauseInfo *gepc = lfirst(lc1);
1635 : :
1636 [ + + ]: 250 : if (gepc->keyno == keyno)
1637 : : {
1638 : 120 : prefix = lappend(prefix, gepc);
1639 : 120 : pk_has_clauses = true;
1640 : : }
1641 : : else
1642 : : {
1643 : : Assert(gepc->keyno > keyno);
1644 : 130 : break;
1645 : : }
1646 : : }
1647 : 210 : ge_start = lc1;
1648 : : }
1649 : :
1650 : : /*
1651 : : * If this key has no clauses, prefix is not valid
1652 : : * anymore.
1653 : : */
1654 [ + + ]: 760 : if (!pk_has_clauses)
1655 : : {
1656 : 40 : prefix_valid = false;
1657 : 40 : break;
1658 : : }
1659 : : }
1660 : :
1661 : : /*
1662 : : * If prefix_valid, generate PartitionPruneStepOps.
1663 : : * Otherwise, we would not find clauses for a valid
1664 : : * subset of the partition keys anymore for the
1665 : : * strategy; give up on generating partition pruning
1666 : : * steps further for the strategy.
1667 : : *
1668 : : * As mentioned above, if 'prefix' contains multiple
1669 : : * expressions for the same key, the following will
1670 : : * generate multiple steps, one for each combination
1671 : : * of the expressions for different keys.
1672 : : *
1673 : : * Note that we pass NULL for step_nullkeys, because
1674 : : * we don't search list/range partition bounds where
1675 : : * some keys are NULL.
1676 : : */
1677 [ + + ]: 590 : if (prefix_valid)
1678 : : {
1679 : : Assert(pc->op_strategy == strat);
1680 : 550 : pc_steps = get_steps_using_prefix(context, strat,
1681 : 550 : pc->op_is_ne,
1682 : : pc->expr,
1683 : : pc->cmpfn,
1684 : : NULL,
1685 : : prefix);
1686 : 550 : opsteps = list_concat(opsteps, pc_steps);
1687 : : }
1688 : : else
1689 : 40 : break;
1690 : : }
1691 : : }
1692 : 12768 : break;
1693 : : }
1694 : :
1695 : 474 : case PARTITION_STRATEGY_HASH:
1696 : : {
1697 : 474 : List *eq_clauses = hash_clauses[HTEqualStrategyNumber];
1698 : :
1699 : : /* For hash partitioning, we have just the = strategy. */
1700 [ + - ]: 474 : if (eq_clauses != NIL)
1701 : : {
1702 : : PartClauseInfo *pc;
1703 : : List *pc_steps;
1704 : 474 : List *prefix = NIL;
1705 : : int last_keyno;
1706 : : ListCell *lc1;
1707 : :
1708 : : /*
1709 : : * Locate the clause for the greatest column. This may
1710 : : * not belong to the last partition key, but it is the
1711 : : * clause belonging to the last partition key we found a
1712 : : * clause for above.
1713 : : */
1714 : 474 : pc = llast(eq_clauses);
1715 : :
1716 : : /*
1717 : : * There might be multiple clauses which matched to that
1718 : : * partition key; find the first such clause. While at
1719 : : * it, add all the clauses before that one to 'prefix'.
1720 : : */
1721 : 474 : last_keyno = pc->keyno;
1722 [ + - + - : 889 : foreach(lc, eq_clauses)
+ - ]
1723 : : {
1724 : 889 : pc = lfirst(lc);
1725 [ + + ]: 889 : if (pc->keyno == last_keyno)
1726 : 474 : break;
1727 : 415 : prefix = lappend(prefix, pc);
1728 : : }
1729 : :
1730 : : /*
1731 : : * For each clause for the "last" column, after appending
1732 : : * the clause's own expression to the 'prefix', we'll
1733 : : * generate one step using the so generated vector and
1734 : : * assign = as its strategy. Actually, 'prefix' might
1735 : : * contain multiple clauses for the same key, in which
1736 : : * case, we must generate steps for various combinations
1737 : : * of expressions of different keys, which
1738 : : * get_steps_using_prefix will take care of for us.
1739 : : */
1740 [ + - + + : 948 : for_each_cell(lc1, eq_clauses, lc)
+ + ]
1741 : : {
1742 : 474 : pc = lfirst(lc1);
1743 : :
1744 : : /*
1745 : : * Note that we pass nullkeys for step_nullkeys,
1746 : : * because we need to tell hash partition bound search
1747 : : * function which of the keys we found IS NULL clauses
1748 : : * for.
1749 : : */
1750 : : Assert(pc->op_strategy == HTEqualStrategyNumber);
1751 : : pc_steps =
1752 : 474 : get_steps_using_prefix(context,
1753 : : HTEqualStrategyNumber,
1754 : : false,
1755 : : pc->expr,
1756 : : pc->cmpfn,
1757 : : nullkeys,
1758 : : prefix);
1759 : 474 : opsteps = list_concat(opsteps, pc_steps);
1760 : : }
1761 : : }
1762 : 474 : break;
1763 : : }
1764 : :
1765 : 0 : default:
1766 [ # # ]: 0 : elog(ERROR, "invalid partition strategy: %c",
1767 : : part_scheme->strategy);
1768 : : break;
1769 : : }
1770 : :
1771 : 13242 : return opsteps;
1772 : : }
1773 : :
1774 : : /*
1775 : : * If the partition key has a collation, then the clause must have the same
1776 : : * input collation. If the partition key is non-collatable, we assume the
1777 : : * collation doesn't matter, because while collation wasn't considered when
1778 : : * performing partitioning, the clause still may have a collation assigned
1779 : : * due to the other input being of a collatable type.
1780 : : *
1781 : : * See also IndexCollMatchesExprColl.
1782 : : */
1783 : : #define PartCollMatchesExprColl(partcoll, exprcoll) \
1784 : : ((partcoll) == InvalidOid || (partcoll) == (exprcoll))
1785 : :
1786 : : /*
1787 : : * match_clause_to_partition_key
1788 : : * Attempt to match the given 'clause' with the specified partition key.
1789 : : *
1790 : : * Return value is:
1791 : : * * PARTCLAUSE_NOMATCH if the clause doesn't match this partition key (but
1792 : : * caller should keep trying, because it might match a subsequent key).
1793 : : * Output arguments: none set.
1794 : : *
1795 : : * * PARTCLAUSE_MATCH_CLAUSE if there is a match.
1796 : : * Output arguments: *pc is set to a PartClauseInfo constructed for the
1797 : : * matched clause.
1798 : : *
1799 : : * * PARTCLAUSE_MATCH_NULLNESS if there is a match, and the matched clause was
1800 : : * either a "a IS NULL" or "a IS NOT NULL" clause.
1801 : : * Output arguments: *clause_is_not_null is set to false in the former case
1802 : : * true otherwise.
1803 : : *
1804 : : * * PARTCLAUSE_MATCH_STEPS if there is a match.
1805 : : * Output arguments: *clause_steps is set to the list of recursively
1806 : : * generated steps for the clause.
1807 : : *
1808 : : * * PARTCLAUSE_MATCH_CONTRADICT if the clause is self-contradictory, ie
1809 : : * it provably returns FALSE or NULL.
1810 : : * Output arguments: none set.
1811 : : *
1812 : : * * PARTCLAUSE_UNSUPPORTED if the clause doesn't match this partition key
1813 : : * and couldn't possibly match any other one either, due to its form or
1814 : : * properties (such as containing a volatile function).
1815 : : * Output arguments: none set.
1816 : : *
1817 : : * Note that when pulling up a subquery, the clause operands may get wrapped
1818 : : * in PlaceHolderVars to enforce separate identity or as a result of outer
1819 : : * joins. We must strip such no-op PlaceHolderVars before comparing operands
1820 : : * to the partition key, otherwise the equal() checks will fail to recognize
1821 : : * valid matches. This is safe because the clauses here are always
1822 : : * relation-scan-level expressions, where a PlaceHolderVar with empty
1823 : : * phnullingrels is effectively a no-op. Stripping may also bring separate
1824 : : * RelabelType nodes into adjacency, so we must loop when peeling those.
1825 : : */
1826 : : static PartClauseMatchStatus
1827 : 29889 : match_clause_to_partition_key(GeneratePruningStepsContext *context,
1828 : : Expr *clause, const Expr *partkey, int partkeyidx,
1829 : : bool *clause_is_not_null, PartClauseInfo **pc,
1830 : : List **clause_steps)
1831 : : {
1832 : : PartClauseMatchStatus boolmatchstatus;
1833 : 29889 : PartitionScheme part_scheme = context->rel->part_scheme;
1834 : 29889 : Oid partopfamily = part_scheme->partopfamily[partkeyidx],
1835 : 29889 : partcoll = part_scheme->partcollation[partkeyidx];
1836 : : Expr *expr;
1837 : : bool notclause;
1838 : :
1839 : : /*
1840 : : * Recognize specially shaped clauses that match a Boolean partition key.
1841 : : */
1842 : 29889 : boolmatchstatus = match_boolean_partition_clause(partopfamily, clause,
1843 : : partkey, &expr,
1844 : : ¬clause);
1845 : :
1846 [ + + ]: 29889 : if (boolmatchstatus == PARTCLAUSE_MATCH_CLAUSE)
1847 : : {
1848 : : PartClauseInfo *partclause;
1849 : :
1850 : : /*
1851 : : * For bool tests in the form of partkey IS NOT true and IS NOT false,
1852 : : * we invert these clauses. Effectively, "partkey IS NOT true"
1853 : : * becomes "partkey IS false OR partkey IS NULL". We do this by
1854 : : * building an OR BoolExpr and forming a clause just like that and
1855 : : * punt it off to gen_partprune_steps_internal() to generate pruning
1856 : : * steps.
1857 : : */
1858 [ + + ]: 570 : if (notclause)
1859 : : {
1860 : : List *new_clauses;
1861 : : List *or_clause;
1862 : 180 : BooleanTest *new_booltest = (BooleanTest *) copyObject(clause);
1863 : : NullTest *nulltest;
1864 : :
1865 : : /* We expect 'notclause' to only be set to true for BooleanTests */
1866 : : Assert(IsA(clause, BooleanTest));
1867 : :
1868 : : /* reverse the bool test */
1869 [ + + ]: 180 : if (new_booltest->booltesttype == IS_NOT_TRUE)
1870 : 110 : new_booltest->booltesttype = IS_FALSE;
1871 [ + - ]: 70 : else if (new_booltest->booltesttype == IS_NOT_FALSE)
1872 : 70 : new_booltest->booltesttype = IS_TRUE;
1873 : : else
1874 : : {
1875 : : /*
1876 : : * We only expect match_boolean_partition_clause to return
1877 : : * PARTCLAUSE_MATCH_CLAUSE for IS_NOT_TRUE and IS_NOT_FALSE.
1878 : : */
1879 : : Assert(false);
1880 : : }
1881 : :
1882 : 180 : nulltest = makeNode(NullTest);
1883 : 180 : nulltest->arg = copyObject(partkey);
1884 : 180 : nulltest->nulltesttype = IS_NULL;
1885 : 180 : nulltest->argisrow = false;
1886 : 180 : nulltest->location = -1;
1887 : :
1888 : 180 : new_clauses = list_make2(new_booltest, nulltest);
1889 : 180 : or_clause = list_make1(makeBoolExpr(OR_EXPR, new_clauses, -1));
1890 : :
1891 : : /* Finally, generate steps */
1892 : 180 : *clause_steps = gen_partprune_steps_internal(context, or_clause);
1893 : :
1894 [ - + ]: 180 : if (context->contradictory)
1895 : 0 : return PARTCLAUSE_MATCH_CONTRADICT; /* shouldn't happen */
1896 [ - + ]: 180 : else if (*clause_steps == NIL)
1897 : 0 : return PARTCLAUSE_UNSUPPORTED; /* step generation failed */
1898 : 180 : return PARTCLAUSE_MATCH_STEPS;
1899 : : }
1900 : :
1901 : 390 : partclause = palloc_object(PartClauseInfo);
1902 : 390 : partclause->keyno = partkeyidx;
1903 : : /* Do pruning with the Boolean equality operator. */
1904 : 390 : partclause->opno = BooleanEqualOperator;
1905 : 390 : partclause->op_is_ne = false;
1906 : 390 : partclause->expr = expr;
1907 : : /* We know that expr is of Boolean type. */
1908 : 390 : partclause->cmpfn = part_scheme->partsupfunc[partkeyidx].fn_oid;
1909 : 390 : partclause->op_strategy = InvalidStrategy;
1910 : :
1911 : 390 : *pc = partclause;
1912 : :
1913 : 390 : return PARTCLAUSE_MATCH_CLAUSE;
1914 : : }
1915 [ + + ]: 29319 : else if (boolmatchstatus == PARTCLAUSE_MATCH_NULLNESS)
1916 : : {
1917 : : /*
1918 : : * Handle IS UNKNOWN and IS NOT UNKNOWN. These just logically
1919 : : * translate to IS NULL and IS NOT NULL.
1920 : : */
1921 : 80 : *clause_is_not_null = notclause;
1922 : 80 : return PARTCLAUSE_MATCH_NULLNESS;
1923 : : }
1924 [ + + + - ]: 53902 : else if (IsA(clause, OpExpr) &&
1925 : 24663 : list_length(((OpExpr *) clause)->args) == 2)
1926 : : {
1927 : 24663 : OpExpr *opclause = (OpExpr *) clause;
1928 : : Expr *leftop,
1929 : : *rightop;
1930 : : Oid opno,
1931 : : op_lefttype,
1932 : : op_righttype,
1933 : 24663 : negator = InvalidOid;
1934 : : Oid cmpfn;
1935 : : int op_strategy;
1936 : 24663 : bool is_opne_listp = false;
1937 : : PartClauseInfo *partclause;
1938 : :
1939 : 24663 : leftop = (Expr *) get_leftop(clause);
1940 : 24663 : leftop = (Expr *) strip_noop_phvs((Node *) leftop);
1941 [ + + ]: 25083 : while (IsA(leftop, RelabelType))
1942 : 420 : leftop = ((RelabelType *) leftop)->arg;
1943 : 24663 : rightop = (Expr *) get_rightop(clause);
1944 : 24663 : rightop = (Expr *) strip_noop_phvs((Node *) rightop);
1945 [ - + ]: 24663 : while (IsA(rightop, RelabelType))
1946 : 0 : rightop = ((RelabelType *) rightop)->arg;
1947 : 24663 : opno = opclause->opno;
1948 : :
1949 : : /* check if the clause matches this partition key */
1950 [ + + ]: 24663 : if (equal(leftop, partkey))
1951 : 15146 : expr = rightop;
1952 [ + + ]: 9517 : else if (equal(rightop, partkey))
1953 : : {
1954 : : /*
1955 : : * It's only useful if we can commute the operator to put the
1956 : : * partkey on the left. If we can't, the clause can be deemed
1957 : : * UNSUPPORTED. Even if its leftop matches some later partkey, we
1958 : : * now know it has Vars on the right, so it's no use.
1959 : : */
1960 : 1071 : opno = get_commutator(opno);
1961 [ - + ]: 1071 : if (!OidIsValid(opno))
1962 : 0 : return PARTCLAUSE_UNSUPPORTED;
1963 : 1071 : expr = leftop;
1964 : : }
1965 : : else
1966 : : /* clause does not match this partition key, but perhaps next. */
1967 : 8446 : return PARTCLAUSE_NOMATCH;
1968 : :
1969 : : /*
1970 : : * Partition key match also requires collation match. There may be
1971 : : * multiple partkeys with the same expression but different
1972 : : * collations, so failure is NOMATCH.
1973 : : */
1974 [ + + + + ]: 16217 : if (!PartCollMatchesExprColl(partcoll, opclause->inputcollid))
1975 : 50 : return PARTCLAUSE_NOMATCH;
1976 : :
1977 : : /*
1978 : : * See if the operator is relevant to the partitioning opfamily.
1979 : : *
1980 : : * Normally we only care about operators that are listed as being part
1981 : : * of the partitioning operator family. But there is one exception:
1982 : : * the not-equals operators are not listed in any operator family
1983 : : * whatsoever, but their negators (equality) are. We can use one of
1984 : : * those if we find it, but only for list partitioning.
1985 : : *
1986 : : * Note: we report NOMATCH on failure if the negator isn't the
1987 : : * equality operator for the partkey's opfamily as other partkeys may
1988 : : * have the same expression but different opfamily. That's unlikely,
1989 : : * but not much more so than duplicate expressions with different
1990 : : * collations.
1991 : : */
1992 [ + + ]: 16167 : if (op_in_opfamily(opno, partopfamily))
1993 : : {
1994 : 15877 : get_op_opfamily_properties(opno, partopfamily, false,
1995 : : &op_strategy, &op_lefttype,
1996 : : &op_righttype);
1997 : : }
1998 : : else
1999 : : {
2000 : : /* not supported for anything apart from LIST partitioned tables */
2001 [ + + ]: 290 : if (part_scheme->strategy != PARTITION_STRATEGY_LIST)
2002 : 80 : return PARTCLAUSE_UNSUPPORTED;
2003 : :
2004 : : /* See if the negator is equality */
2005 : 210 : negator = get_negator(opno);
2006 [ + - + + ]: 210 : if (OidIsValid(negator) && op_in_opfamily(negator, partopfamily))
2007 : : {
2008 : 200 : get_op_opfamily_properties(negator, partopfamily, false,
2009 : : &op_strategy, &op_lefttype,
2010 : : &op_righttype);
2011 [ + - ]: 200 : if (op_strategy == BTEqualStrategyNumber)
2012 : 200 : is_opne_listp = true; /* bingo */
2013 : : }
2014 : :
2015 : : /* Nope, it's not <> either. */
2016 [ + + ]: 210 : if (!is_opne_listp)
2017 : 10 : return PARTCLAUSE_NOMATCH;
2018 : : }
2019 : :
2020 : : /*
2021 : : * Only allow strict operators. This will guarantee nulls are
2022 : : * filtered. (This test is likely useless, since btree and hash
2023 : : * comparison operators are generally strict.)
2024 : : */
2025 [ - + ]: 16077 : if (!op_strict(opno))
2026 : 0 : return PARTCLAUSE_UNSUPPORTED;
2027 : :
2028 : : /*
2029 : : * OK, we have a match to the partition key and a suitable operator.
2030 : : * Examine the other argument to see if it's usable for pruning.
2031 : : *
2032 : : * In most of these cases, we can return UNSUPPORTED because the same
2033 : : * failure would occur no matter which partkey it's matched to. (In
2034 : : * particular, now that we've successfully matched one side of the
2035 : : * opclause to a partkey, there is no chance that matching the other
2036 : : * side to another partkey will produce a usable result, since that'd
2037 : : * mean there are Vars on both sides.)
2038 : : *
2039 : : * Also, if we reject an argument for a target-dependent reason, set
2040 : : * appropriate fields of *context to report that. We postpone these
2041 : : * tests until after matching the partkey and the operator, so as to
2042 : : * reduce the odds of setting the context fields for clauses that do
2043 : : * not end up contributing to pruning steps.
2044 : : *
2045 : : * First, check for non-Const argument. (We assume that any immutable
2046 : : * subexpression will have been folded to a Const already.)
2047 : : */
2048 [ + + ]: 16077 : if (!IsA(expr, Const))
2049 : : {
2050 : : Bitmapset *paramids;
2051 : :
2052 : : /*
2053 : : * When pruning in the planner, we only support pruning using
2054 : : * comparisons to constants. We cannot prune on the basis of
2055 : : * anything that's not immutable. (Note that has_mutable_arg and
2056 : : * has_exec_param do not get set for this target value.)
2057 : : */
2058 [ + + ]: 1774 : if (context->target == PARTTARGET_PLANNER)
2059 : 636 : return PARTCLAUSE_UNSUPPORTED;
2060 : :
2061 : : /*
2062 : : * We can never prune using an expression that contains Vars.
2063 : : */
2064 [ + + ]: 1138 : if (contain_var_clause((Node *) expr))
2065 : 34 : return PARTCLAUSE_UNSUPPORTED;
2066 : :
2067 : : /*
2068 : : * And we must reject anything containing a volatile function.
2069 : : * Stable functions are OK though.
2070 : : */
2071 [ - + ]: 1104 : if (contain_volatile_functions((Node *) expr))
2072 : 0 : return PARTCLAUSE_UNSUPPORTED;
2073 : :
2074 : : /*
2075 : : * See if there are any exec Params. If so, we can only use this
2076 : : * expression during per-scan pruning.
2077 : : */
2078 : 1104 : paramids = pull_exec_paramids(expr);
2079 [ + + ]: 1104 : if (!bms_is_empty(paramids))
2080 : : {
2081 : 710 : context->has_exec_param = true;
2082 [ + + ]: 710 : if (context->target != PARTTARGET_EXEC)
2083 : 350 : return PARTCLAUSE_UNSUPPORTED;
2084 : : }
2085 : : else
2086 : : {
2087 : : /* It's potentially usable, but mutable */
2088 : 394 : context->has_mutable_arg = true;
2089 : : }
2090 : : }
2091 : :
2092 : : /*
2093 : : * Check whether the comparison operator itself is immutable. (We
2094 : : * assume anything that's in a btree or hash opclass is at least
2095 : : * stable, but we need to check for immutability.)
2096 : : */
2097 [ + + ]: 15057 : if (op_volatile(opno) != PROVOLATILE_IMMUTABLE)
2098 : : {
2099 : 30 : context->has_mutable_op = true;
2100 : :
2101 : : /*
2102 : : * When pruning in the planner, we cannot prune with mutable
2103 : : * operators.
2104 : : */
2105 [ + + ]: 30 : if (context->target == PARTTARGET_PLANNER)
2106 : 5 : return PARTCLAUSE_UNSUPPORTED;
2107 : : }
2108 : :
2109 : : /*
2110 : : * Now find the procedure to use, based on the types. If the clause's
2111 : : * other argument is of the same type as the partitioning opclass's
2112 : : * declared input type, we can use the procedure cached in
2113 : : * PartitionKey. If not, search for a cross-type one in the same
2114 : : * opfamily; if one doesn't exist, report no match.
2115 : : */
2116 [ + + ]: 15052 : if (op_righttype == part_scheme->partopcintype[partkeyidx])
2117 : 14857 : cmpfn = part_scheme->partsupfunc[partkeyidx].fn_oid;
2118 : : else
2119 : : {
2120 [ + - - ]: 195 : switch (part_scheme->strategy)
2121 : : {
2122 : : /*
2123 : : * For range and list partitioning, we need the ordering
2124 : : * procedure with lefttype being the partition key's type,
2125 : : * and righttype the clause's operator's right type.
2126 : : */
2127 : 195 : case PARTITION_STRATEGY_LIST:
2128 : : case PARTITION_STRATEGY_RANGE:
2129 : : cmpfn =
2130 : 195 : get_opfamily_proc(part_scheme->partopfamily[partkeyidx],
2131 : 195 : part_scheme->partopcintype[partkeyidx],
2132 : : op_righttype, BTORDER_PROC);
2133 : 195 : break;
2134 : :
2135 : : /*
2136 : : * For hash partitioning, we need the hashing procedure
2137 : : * for the clause's type.
2138 : : */
2139 : 0 : case PARTITION_STRATEGY_HASH:
2140 : : cmpfn =
2141 : 0 : get_opfamily_proc(part_scheme->partopfamily[partkeyidx],
2142 : : op_righttype, op_righttype,
2143 : : HASHEXTENDED_PROC);
2144 : 0 : break;
2145 : :
2146 : 0 : default:
2147 [ # # ]: 0 : elog(ERROR, "invalid partition strategy: %c",
2148 : : part_scheme->strategy);
2149 : : cmpfn = InvalidOid; /* keep compiler quiet */
2150 : : break;
2151 : : }
2152 : :
2153 [ - + ]: 195 : if (!OidIsValid(cmpfn))
2154 : 0 : return PARTCLAUSE_NOMATCH;
2155 : : }
2156 : :
2157 : : /*
2158 : : * Build the clause, passing the negator if applicable.
2159 : : */
2160 : 15052 : partclause = palloc_object(PartClauseInfo);
2161 : 15052 : partclause->keyno = partkeyidx;
2162 [ + + ]: 15052 : if (is_opne_listp)
2163 : : {
2164 : : Assert(OidIsValid(negator));
2165 : 170 : partclause->opno = negator;
2166 : 170 : partclause->op_is_ne = true;
2167 : 170 : partclause->op_strategy = InvalidStrategy;
2168 : : }
2169 : : else
2170 : : {
2171 : 14882 : partclause->opno = opno;
2172 : 14882 : partclause->op_is_ne = false;
2173 : 14882 : partclause->op_strategy = op_strategy;
2174 : : }
2175 : 15052 : partclause->expr = expr;
2176 : 15052 : partclause->cmpfn = cmpfn;
2177 : :
2178 : 15052 : *pc = partclause;
2179 : :
2180 : 15052 : return PARTCLAUSE_MATCH_CLAUSE;
2181 : : }
2182 [ + + ]: 4576 : else if (IsA(clause, ScalarArrayOpExpr))
2183 : : {
2184 : 644 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
2185 : 644 : Oid saop_op = saop->opno;
2186 : 644 : Oid saop_coll = saop->inputcollid;
2187 : 644 : Expr *leftop = (Expr *) linitial(saop->args),
2188 : 644 : *rightop = (Expr *) lsecond(saop->args);
2189 : : List *elem_exprs,
2190 : : *elem_clauses;
2191 : : ListCell *lc1;
2192 : :
2193 : 644 : leftop = (Expr *) strip_noop_phvs((Node *) leftop);
2194 [ + + ]: 784 : while (IsA(leftop, RelabelType))
2195 : 140 : leftop = ((RelabelType *) leftop)->arg;
2196 : :
2197 : : /* check if the LHS matches this partition key */
2198 [ + + + + ]: 644 : if (!equal(leftop, partkey) ||
2199 [ - + ]: 180 : !PartCollMatchesExprColl(partcoll, saop->inputcollid))
2200 : 164 : return PARTCLAUSE_NOMATCH;
2201 : :
2202 : : /*
2203 : : * See if the operator is relevant to the partitioning opfamily.
2204 : : *
2205 : : * In case of NOT IN (..), we get a '<>', which we handle if list
2206 : : * partitioning is in use and we're able to confirm that it's negator
2207 : : * is a btree equality operator belonging to the partitioning operator
2208 : : * family. As above, report NOMATCH for non-matching operator.
2209 : : */
2210 [ + + ]: 480 : if (!op_in_opfamily(saop_op, partopfamily))
2211 : : {
2212 : : Oid negator;
2213 : :
2214 [ + + ]: 60 : if (part_scheme->strategy != PARTITION_STRATEGY_LIST)
2215 : 10 : return PARTCLAUSE_NOMATCH;
2216 : :
2217 : 50 : negator = get_negator(saop_op);
2218 [ + - + + ]: 50 : if (OidIsValid(negator) && op_in_opfamily(negator, partopfamily))
2219 : 10 : {
2220 : : int strategy;
2221 : : Oid lefttype,
2222 : : righttype;
2223 : :
2224 : 10 : get_op_opfamily_properties(negator, partopfamily,
2225 : : false, &strategy,
2226 : : &lefttype, &righttype);
2227 [ - + ]: 10 : if (strategy != BTEqualStrategyNumber)
2228 : 0 : return PARTCLAUSE_NOMATCH;
2229 : : }
2230 : : else
2231 : 40 : return PARTCLAUSE_NOMATCH; /* no useful negator */
2232 : : }
2233 : :
2234 : : /*
2235 : : * Only allow strict operators. This will guarantee nulls are
2236 : : * filtered. (This test is likely useless, since btree and hash
2237 : : * comparison operators are generally strict.)
2238 : : */
2239 [ - + ]: 430 : if (!op_strict(saop_op))
2240 : 0 : return PARTCLAUSE_UNSUPPORTED;
2241 : :
2242 : : /*
2243 : : * OK, we have a match to the partition key and a suitable operator.
2244 : : * Examine the array argument to see if it's usable for pruning. This
2245 : : * is identical to the logic for a plain OpExpr.
2246 : : */
2247 [ + + ]: 430 : if (!IsA(rightop, Const))
2248 : : {
2249 : : Bitmapset *paramids;
2250 : :
2251 : : /*
2252 : : * When pruning in the planner, we only support pruning using
2253 : : * comparisons to constants. We cannot prune on the basis of
2254 : : * anything that's not immutable. (Note that has_mutable_arg and
2255 : : * has_exec_param do not get set for this target value.)
2256 : : */
2257 [ + + ]: 93 : if (context->target == PARTTARGET_PLANNER)
2258 : 44 : return PARTCLAUSE_UNSUPPORTED;
2259 : :
2260 : : /*
2261 : : * We can never prune using an expression that contains Vars.
2262 : : */
2263 [ - + ]: 49 : if (contain_var_clause((Node *) rightop))
2264 : 0 : return PARTCLAUSE_UNSUPPORTED;
2265 : :
2266 : : /*
2267 : : * And we must reject anything containing a volatile function.
2268 : : * Stable functions are OK though.
2269 : : */
2270 [ - + ]: 49 : if (contain_volatile_functions((Node *) rightop))
2271 : 0 : return PARTCLAUSE_UNSUPPORTED;
2272 : :
2273 : : /*
2274 : : * See if there are any exec Params. If so, we can only use this
2275 : : * expression during per-scan pruning.
2276 : : */
2277 : 49 : paramids = pull_exec_paramids(rightop);
2278 [ + + ]: 49 : if (!bms_is_empty(paramids))
2279 : : {
2280 : 10 : context->has_exec_param = true;
2281 [ + + ]: 10 : if (context->target != PARTTARGET_EXEC)
2282 : 5 : return PARTCLAUSE_UNSUPPORTED;
2283 : : }
2284 : : else
2285 : : {
2286 : : /* It's potentially usable, but mutable */
2287 : 39 : context->has_mutable_arg = true;
2288 : : }
2289 : : }
2290 : :
2291 : : /*
2292 : : * Check whether the comparison operator itself is immutable. (We
2293 : : * assume anything that's in a btree or hash opclass is at least
2294 : : * stable, but we need to check for immutability.)
2295 : : */
2296 [ + + ]: 381 : if (op_volatile(saop_op) != PROVOLATILE_IMMUTABLE)
2297 : : {
2298 : 30 : context->has_mutable_op = true;
2299 : :
2300 : : /*
2301 : : * When pruning in the planner, we cannot prune with mutable
2302 : : * operators.
2303 : : */
2304 [ + + ]: 30 : if (context->target == PARTTARGET_PLANNER)
2305 : 15 : return PARTCLAUSE_UNSUPPORTED;
2306 : : }
2307 : :
2308 : : /*
2309 : : * Examine the contents of the array argument.
2310 : : */
2311 : 366 : elem_exprs = NIL;
2312 [ + + ]: 366 : if (IsA(rightop, Const))
2313 : : {
2314 : : /*
2315 : : * For a constant array, convert the elements to a list of Const
2316 : : * nodes, one for each array element (excepting nulls).
2317 : : */
2318 : 322 : Const *arr = (Const *) rightop;
2319 : : ArrayType *arrval;
2320 : : int16 elemlen;
2321 : : bool elembyval;
2322 : : char elemalign;
2323 : : Datum *elem_values;
2324 : : bool *elem_nulls;
2325 : : int num_elems,
2326 : : i;
2327 : :
2328 : : /* If the array itself is null, the saop returns null */
2329 [ + + ]: 322 : if (arr->constisnull)
2330 : 20 : return PARTCLAUSE_MATCH_CONTRADICT;
2331 : :
2332 : 307 : arrval = DatumGetArrayTypeP(arr->constvalue);
2333 : 307 : get_typlenbyvalalign(ARR_ELEMTYPE(arrval),
2334 : : &elemlen, &elembyval, &elemalign);
2335 : 307 : deconstruct_array(arrval,
2336 : : ARR_ELEMTYPE(arrval),
2337 : : elemlen, elembyval, elemalign,
2338 : : &elem_values, &elem_nulls,
2339 : : &num_elems);
2340 [ + + ]: 1078 : for (i = 0; i < num_elems; i++)
2341 : : {
2342 : : Const *elem_expr;
2343 : :
2344 : : /*
2345 : : * A null array element must lead to a null comparison result,
2346 : : * since saop_op is known strict. We can ignore it in the
2347 : : * useOr case, but otherwise it implies self-contradiction.
2348 : : */
2349 [ + + ]: 776 : if (elem_nulls[i])
2350 : : {
2351 [ + + ]: 45 : if (saop->useOr)
2352 : 40 : continue;
2353 : 5 : return PARTCLAUSE_MATCH_CONTRADICT;
2354 : : }
2355 : :
2356 : 731 : elem_expr = makeConst(ARR_ELEMTYPE(arrval), -1,
2357 : : arr->constcollid, elemlen,
2358 : 731 : elem_values[i], false, elembyval);
2359 : 731 : elem_exprs = lappend(elem_exprs, elem_expr);
2360 : : }
2361 : : }
2362 [ + + ]: 44 : else if (IsA(rightop, ArrayExpr))
2363 : : {
2364 : 39 : ArrayExpr *arrexpr = castNode(ArrayExpr, rightop);
2365 : :
2366 : : /*
2367 : : * For a nested ArrayExpr, we don't know how to get the actual
2368 : : * scalar values out into a flat list, so we give up doing
2369 : : * anything with this ScalarArrayOpExpr.
2370 : : */
2371 [ - + ]: 39 : if (arrexpr->multidims)
2372 : 0 : return PARTCLAUSE_UNSUPPORTED;
2373 : :
2374 : : /*
2375 : : * Otherwise, we can just use the list of element values.
2376 : : */
2377 : 39 : elem_exprs = arrexpr->elements;
2378 : : }
2379 : : else
2380 : : {
2381 : : /* Give up on any other clause types. */
2382 : 5 : return PARTCLAUSE_UNSUPPORTED;
2383 : : }
2384 : :
2385 : : /*
2386 : : * Now generate a list of clauses, one for each array element, of the
2387 : : * form leftop saop_op elem_expr
2388 : : */
2389 : 341 : elem_clauses = NIL;
2390 [ + - + + : 1154 : foreach(lc1, elem_exprs)
+ + ]
2391 : : {
2392 : : Expr *elem_clause;
2393 : :
2394 : 813 : elem_clause = make_opclause(saop_op, BOOLOID, false,
2395 : 813 : leftop, lfirst(lc1),
2396 : : InvalidOid, saop_coll);
2397 : 813 : elem_clauses = lappend(elem_clauses, elem_clause);
2398 : : }
2399 : :
2400 : : /*
2401 : : * If we have an ANY clause and multiple elements, now turn the list
2402 : : * of clauses into an OR expression.
2403 : : */
2404 [ + + + + ]: 341 : if (saop->useOr && list_length(elem_clauses) > 1)
2405 : 276 : elem_clauses = list_make1(makeBoolExpr(OR_EXPR, elem_clauses, -1));
2406 : :
2407 : : /* Finally, generate steps */
2408 : 341 : *clause_steps = gen_partprune_steps_internal(context, elem_clauses);
2409 [ - + ]: 341 : if (context->contradictory)
2410 : 0 : return PARTCLAUSE_MATCH_CONTRADICT;
2411 [ - + ]: 341 : else if (*clause_steps == NIL)
2412 : 0 : return PARTCLAUSE_UNSUPPORTED; /* step generation failed */
2413 : 341 : return PARTCLAUSE_MATCH_STEPS;
2414 : : }
2415 [ + + ]: 3932 : else if (IsA(clause, NullTest))
2416 : : {
2417 : 3232 : NullTest *nulltest = (NullTest *) clause;
2418 : 3232 : Expr *arg = nulltest->arg;
2419 : :
2420 : 3232 : arg = (Expr *) strip_noop_phvs((Node *) arg);
2421 [ - + ]: 3232 : while (IsA(arg, RelabelType))
2422 : 0 : arg = ((RelabelType *) arg)->arg;
2423 : :
2424 : : /* Does arg match with this partition key column? */
2425 [ + + ]: 3232 : if (!equal(arg, partkey))
2426 : 1432 : return PARTCLAUSE_NOMATCH;
2427 : :
2428 : 1800 : *clause_is_not_null = (nulltest->nulltesttype == IS_NOT_NULL);
2429 : :
2430 : 1800 : return PARTCLAUSE_MATCH_NULLNESS;
2431 : : }
2432 : :
2433 : : /*
2434 : : * If we get here then the return value depends on the result of the
2435 : : * match_boolean_partition_clause call above. If the call returned
2436 : : * PARTCLAUSE_UNSUPPORTED then we're either not dealing with a bool qual
2437 : : * or the bool qual is not suitable for pruning. Since the qual didn't
2438 : : * match up to any of the other qual types supported here, then trying to
2439 : : * match it against any other partition key is a waste of time, so just
2440 : : * return PARTCLAUSE_UNSUPPORTED. If the qual just couldn't be matched to
2441 : : * this partition key, then it may match another, so return
2442 : : * PARTCLAUSE_NOMATCH. The only other value that
2443 : : * match_boolean_partition_clause can return is PARTCLAUSE_MATCH_CLAUSE,
2444 : : * and since that value was already dealt with above, then we can just
2445 : : * return boolmatchstatus.
2446 : : */
2447 : 700 : return boolmatchstatus;
2448 : : }
2449 : :
2450 : : /*
2451 : : * get_steps_using_prefix
2452 : : * Generate a list of PartitionPruneStepOps based on the given input.
2453 : : *
2454 : : * 'step_lastexpr' and 'step_lastcmpfn' are the Expr and comparison function
2455 : : * belonging to the final partition key that we have a clause for. 'prefix'
2456 : : * is a list of PartClauseInfos for partition key numbers prior to the given
2457 : : * 'step_lastexpr' and 'step_lastcmpfn'. 'prefix' may contain multiple
2458 : : * PartClauseInfos belonging to a single partition key. We will generate a
2459 : : * PartitionPruneStepOp for each combination of the given PartClauseInfos
2460 : : * using, at most, one PartClauseInfo per partition key.
2461 : : *
2462 : : * For LIST and RANGE partitioned tables, callers must ensure that
2463 : : * step_nullkeys is NULL, and that prefix contains at least one clause for
2464 : : * each of the partition keys prior to the key that 'step_lastexpr' and
2465 : : * 'step_lastcmpfn' belong to.
2466 : : *
2467 : : * For HASH partitioned tables, callers must ensure that 'prefix' contains at
2468 : : * least one clause for each of the partition keys apart from the final key
2469 : : * (the expr and comparison function for the final key are in 'step_lastexpr'
2470 : : * and 'step_lastcmpfn'). A bit set in step_nullkeys can substitute clauses
2471 : : * in the 'prefix' list for any given key. If a bit is set in 'step_nullkeys'
2472 : : * for a given key, then there must be no PartClauseInfo for that key in the
2473 : : * 'prefix' list.
2474 : : *
2475 : : * For each of the above cases, callers must ensure that PartClauseInfos in
2476 : : * 'prefix' are sorted in ascending order of keyno.
2477 : : */
2478 : : static List *
2479 : 14662 : get_steps_using_prefix(GeneratePruningStepsContext *context,
2480 : : StrategyNumber step_opstrategy,
2481 : : bool step_op_is_ne,
2482 : : Expr *step_lastexpr,
2483 : : Oid step_lastcmpfn,
2484 : : Bitmapset *step_nullkeys,
2485 : : List *prefix)
2486 : : {
2487 : : /* step_nullkeys must be empty for RANGE and LIST partitioned tables */
2488 : : Assert(step_nullkeys == NULL ||
2489 : : context->rel->part_scheme->strategy == PARTITION_STRATEGY_HASH);
2490 : :
2491 : : /*
2492 : : * No recursive processing is required when 'prefix' is an empty list.
2493 : : * This occurs when there is only 1 partition key column.
2494 : : */
2495 [ + + ]: 14662 : if (prefix == NIL)
2496 : : {
2497 : : PartitionPruneStep *step;
2498 : :
2499 : 13817 : step = gen_prune_step_op(context,
2500 : : step_opstrategy,
2501 : : step_op_is_ne,
2502 : : list_make1(step_lastexpr),
2503 : : list_make1_oid(step_lastcmpfn),
2504 : : step_nullkeys);
2505 : 13817 : return list_make1(step);
2506 : : }
2507 : :
2508 : : /* Recurse to generate steps for every combination of clauses. */
2509 : 845 : return get_steps_using_prefix_recurse(context,
2510 : : step_opstrategy,
2511 : : step_op_is_ne,
2512 : : step_lastexpr,
2513 : : step_lastcmpfn,
2514 : : step_nullkeys,
2515 : : prefix,
2516 : : list_head(prefix),
2517 : : NIL, NIL);
2518 : : }
2519 : :
2520 : : /*
2521 : : * get_steps_using_prefix_recurse
2522 : : * Generate and return a list of PartitionPruneStepOps using the 'prefix'
2523 : : * list of PartClauseInfos starting at the 'start' cell.
2524 : : *
2525 : : * When 'prefix' contains multiple PartClauseInfos for a single partition key
2526 : : * we create a PartitionPruneStepOp for each combination of duplicated
2527 : : * PartClauseInfos. The returned list will contain a PartitionPruneStepOp
2528 : : * for each unique combination of input PartClauseInfos containing at most one
2529 : : * PartClauseInfo per partition key.
2530 : : *
2531 : : * 'prefix' is the input list of PartClauseInfos sorted by keyno.
2532 : : * 'start' marks the cell that searching the 'prefix' list should start from.
2533 : : * 'step_exprs' and 'step_cmpfns' each contains the expressions and cmpfns
2534 : : * we've generated so far from the clauses for the previous part keys.
2535 : : */
2536 : : static List *
2537 : 1155 : get_steps_using_prefix_recurse(GeneratePruningStepsContext *context,
2538 : : StrategyNumber step_opstrategy,
2539 : : bool step_op_is_ne,
2540 : : Expr *step_lastexpr,
2541 : : Oid step_lastcmpfn,
2542 : : Bitmapset *step_nullkeys,
2543 : : List *prefix,
2544 : : ListCell *start,
2545 : : List *step_exprs,
2546 : : List *step_cmpfns)
2547 : : {
2548 : 1155 : List *result = NIL;
2549 : : ListCell *lc;
2550 : : int cur_keyno;
2551 : : int final_keyno;
2552 : :
2553 : : /* Actually, recursion would be limited by PARTITION_MAX_KEYS. */
2554 : 1155 : check_stack_depth();
2555 : :
2556 : : Assert(start != NULL);
2557 : 1155 : cur_keyno = ((PartClauseInfo *) lfirst(start))->keyno;
2558 : 1155 : final_keyno = ((PartClauseInfo *) llast(prefix))->keyno;
2559 : :
2560 : : /* Check if we need to recurse. */
2561 [ + + ]: 1155 : if (cur_keyno < final_keyno)
2562 : : {
2563 : : PartClauseInfo *pc;
2564 : : ListCell *next_start;
2565 : :
2566 : : /*
2567 : : * Find the first PartClauseInfo belonging to the next partition key,
2568 : : * the next recursive call must start iteration of the prefix list
2569 : : * from that point.
2570 : : */
2571 [ + - + - : 600 : for_each_cell(lc, prefix, start)
+ - ]
2572 : : {
2573 : 600 : pc = lfirst(lc);
2574 : :
2575 [ + + ]: 600 : if (pc->keyno > cur_keyno)
2576 : 290 : break;
2577 : : }
2578 : :
2579 : : /* record where to start iterating in the next recursive call */
2580 : 290 : next_start = lc;
2581 : :
2582 : : /*
2583 : : * For each PartClauseInfo with keyno set to cur_keyno, add its expr
2584 : : * and cmpfn to step_exprs and step_cmpfns, respectively, and recurse
2585 : : * using 'next_start' as the starting point in the 'prefix' list.
2586 : : */
2587 [ + - + - : 600 : for_each_cell(lc, prefix, start)
+ - ]
2588 : : {
2589 : : List *moresteps;
2590 : : List *step_exprs1,
2591 : : *step_cmpfns1;
2592 : :
2593 : 600 : pc = lfirst(lc);
2594 [ + + ]: 600 : if (pc->keyno == cur_keyno)
2595 : : {
2596 : : /* Leave the original step_exprs unmodified. */
2597 : 310 : step_exprs1 = list_copy(step_exprs);
2598 : 310 : step_exprs1 = lappend(step_exprs1, pc->expr);
2599 : :
2600 : : /* Leave the original step_cmpfns unmodified. */
2601 : 310 : step_cmpfns1 = list_copy(step_cmpfns);
2602 : 310 : step_cmpfns1 = lappend_oid(step_cmpfns1, pc->cmpfn);
2603 : : }
2604 : : else
2605 : : {
2606 : : /* check the 'prefix' list is sorted correctly */
2607 : : Assert(pc->keyno > cur_keyno);
2608 : 290 : break;
2609 : : }
2610 : :
2611 : 310 : moresteps = get_steps_using_prefix_recurse(context,
2612 : : step_opstrategy,
2613 : : step_op_is_ne,
2614 : : step_lastexpr,
2615 : : step_lastcmpfn,
2616 : : step_nullkeys,
2617 : : prefix,
2618 : : next_start,
2619 : : step_exprs1,
2620 : : step_cmpfns1);
2621 : 310 : result = list_concat(result, moresteps);
2622 : :
2623 : 310 : list_free(step_exprs1);
2624 : 310 : list_free(step_cmpfns1);
2625 : : }
2626 : : }
2627 : : else
2628 : : {
2629 : : /*
2630 : : * End the current recursion cycle and start generating steps, one for
2631 : : * each clause with cur_keyno, which is all clauses from here onward
2632 : : * till the end of the list. Note that for hash partitioning,
2633 : : * step_nullkeys is allowed to be non-empty, in which case step_exprs
2634 : : * would only contain expressions for the partition keys that are not
2635 : : * specified in step_nullkeys.
2636 : : */
2637 : : Assert(list_length(step_exprs) == cur_keyno ||
2638 : : !bms_is_empty(step_nullkeys));
2639 : :
2640 : : /*
2641 : : * Note also that for hash partitioning, each partition key should
2642 : : * have either equality clauses or an IS NULL clause, so if a
2643 : : * partition key doesn't have an expression, it would be specified in
2644 : : * step_nullkeys.
2645 : : */
2646 : : Assert(context->rel->part_scheme->strategy
2647 : : != PARTITION_STRATEGY_HASH ||
2648 : : list_length(step_exprs) + 2 + bms_num_members(step_nullkeys) ==
2649 : : context->rel->part_scheme->partnatts);
2650 [ + - + + : 1740 : for_each_cell(lc, prefix, start)
+ + ]
2651 : : {
2652 : 875 : PartClauseInfo *pc = lfirst(lc);
2653 : : PartitionPruneStep *step;
2654 : : List *step_exprs1,
2655 : : *step_cmpfns1;
2656 : :
2657 : : Assert(pc->keyno == cur_keyno);
2658 : :
2659 : : /* Leave the original step_exprs unmodified. */
2660 : 875 : step_exprs1 = list_copy(step_exprs);
2661 : 875 : step_exprs1 = lappend(step_exprs1, pc->expr);
2662 : 875 : step_exprs1 = lappend(step_exprs1, step_lastexpr);
2663 : :
2664 : : /* Leave the original step_cmpfns unmodified. */
2665 : 875 : step_cmpfns1 = list_copy(step_cmpfns);
2666 : 875 : step_cmpfns1 = lappend_oid(step_cmpfns1, pc->cmpfn);
2667 : 875 : step_cmpfns1 = lappend_oid(step_cmpfns1, step_lastcmpfn);
2668 : :
2669 : 875 : step = gen_prune_step_op(context,
2670 : : step_opstrategy, step_op_is_ne,
2671 : : step_exprs1, step_cmpfns1,
2672 : : step_nullkeys);
2673 : 875 : result = lappend(result, step);
2674 : : }
2675 : : }
2676 : :
2677 : 1155 : return result;
2678 : : }
2679 : :
2680 : : /*
2681 : : * get_matching_hash_bounds
2682 : : * Determine offset of the hash bound matching the specified values,
2683 : : * considering that all the non-null values come from clauses containing
2684 : : * a compatible hash equality operator and any keys that are null come
2685 : : * from an IS NULL clause.
2686 : : *
2687 : : * Generally this function will return a single matching bound offset,
2688 : : * although if a partition has not been setup for a given modulus then we may
2689 : : * return no matches. If the number of clauses found don't cover the entire
2690 : : * partition key, then we'll need to return all offsets.
2691 : : *
2692 : : * 'opstrategy' if non-zero must be HTEqualStrategyNumber.
2693 : : *
2694 : : * 'values' contains Datums indexed by the partition key to use for pruning.
2695 : : *
2696 : : * 'nvalues', the number of Datums in the 'values' array.
2697 : : *
2698 : : * 'partsupfunc' contains partition hashing functions that can produce correct
2699 : : * hash for the type of the values contained in 'values'.
2700 : : *
2701 : : * 'nullkeys' is the set of partition keys that are null.
2702 : : */
2703 : : static PruneStepResult *
2704 : 261 : get_matching_hash_bounds(PartitionPruneContext *context,
2705 : : StrategyNumber opstrategy, const Datum *values, int nvalues,
2706 : : FmgrInfo *partsupfunc, Bitmapset *nullkeys)
2707 : : {
2708 : 261 : PruneStepResult *result = palloc0_object(PruneStepResult);
2709 : 261 : PartitionBoundInfo boundinfo = context->boundinfo;
2710 : 261 : int *partindices = boundinfo->indexes;
2711 : 261 : int partnatts = context->partnatts;
2712 : : bool isnull[PARTITION_MAX_KEYS];
2713 : : int i;
2714 : : uint64 rowHash;
2715 : : int greatest_modulus;
2716 : 261 : Oid *partcollation = context->partcollation;
2717 : :
2718 : : Assert(context->strategy == PARTITION_STRATEGY_HASH);
2719 : :
2720 : : /*
2721 : : * For hash partitioning we can only perform pruning based on equality
2722 : : * clauses to the partition key or IS NULL clauses. We also can only
2723 : : * prune if we got values for all keys.
2724 : : */
2725 [ + - ]: 261 : if (nvalues + bms_num_members(nullkeys) == partnatts)
2726 : : {
2727 : : /*
2728 : : * If there are any values, they must have come from clauses
2729 : : * containing an equality operator compatible with hash partitioning.
2730 : : */
2731 : : Assert(opstrategy == HTEqualStrategyNumber || nvalues == 0);
2732 : :
2733 [ + + ]: 1066 : for (i = 0; i < partnatts; i++)
2734 : 805 : isnull[i] = bms_is_member(i, nullkeys);
2735 : :
2736 : 261 : rowHash = compute_partition_hash_value(partnatts, partsupfunc, partcollation,
2737 : : values, isnull);
2738 : :
2739 : 261 : greatest_modulus = boundinfo->nindexes;
2740 [ + + ]: 261 : if (partindices[rowHash % greatest_modulus] >= 0)
2741 : 256 : result->bound_offsets =
2742 : 256 : bms_make_singleton(rowHash % greatest_modulus);
2743 : : }
2744 : : else
2745 : : {
2746 : : /* Report all valid offsets into the boundinfo->indexes array. */
2747 : 0 : result->bound_offsets = bms_add_range(NULL, 0,
2748 : 0 : boundinfo->nindexes - 1);
2749 : : }
2750 : :
2751 : : /*
2752 : : * There is neither a special hash null partition or the default hash
2753 : : * partition.
2754 : : */
2755 : 261 : result->scan_null = result->scan_default = false;
2756 : :
2757 : 261 : return result;
2758 : : }
2759 : :
2760 : : /*
2761 : : * get_matching_list_bounds
2762 : : * Determine the offsets of list bounds matching the specified value,
2763 : : * according to the semantics of the given operator strategy
2764 : : *
2765 : : * scan_default will be set in the returned struct, if the default partition
2766 : : * needs to be scanned, provided one exists at all. scan_null will be set if
2767 : : * the special null-accepting partition needs to be scanned.
2768 : : *
2769 : : * 'opstrategy' if non-zero must be a btree strategy number.
2770 : : *
2771 : : * 'value' contains the value to use for pruning.
2772 : : *
2773 : : * 'nvalues', if non-zero, should be exactly 1, because of list partitioning.
2774 : : *
2775 : : * 'partsupfunc' contains the list partitioning comparison function to be used
2776 : : * to perform partition_list_bsearch
2777 : : *
2778 : : * 'nullkeys' is the set of partition keys that are null.
2779 : : */
2780 : : static PruneStepResult *
2781 : 5413 : get_matching_list_bounds(PartitionPruneContext *context,
2782 : : StrategyNumber opstrategy, Datum value, int nvalues,
2783 : : FmgrInfo *partsupfunc, Bitmapset *nullkeys)
2784 : : {
2785 : 5413 : PruneStepResult *result = palloc0_object(PruneStepResult);
2786 : 5413 : PartitionBoundInfo boundinfo = context->boundinfo;
2787 : : int off,
2788 : : minoff,
2789 : : maxoff;
2790 : : bool is_equal;
2791 : 5413 : bool inclusive = false;
2792 : 5413 : Oid *partcollation = context->partcollation;
2793 : :
2794 : : Assert(context->strategy == PARTITION_STRATEGY_LIST);
2795 : : Assert(context->partnatts == 1);
2796 : :
2797 : 5413 : result->scan_null = result->scan_default = false;
2798 : :
2799 [ + + ]: 5413 : if (!bms_is_empty(nullkeys))
2800 : : {
2801 : : /*
2802 : : * Nulls may exist in only one partition - the partition whose
2803 : : * accepted set of values includes null or the default partition if
2804 : : * the former doesn't exist.
2805 : : */
2806 [ + + ]: 275 : if (partition_bound_accepts_nulls(boundinfo))
2807 : 195 : result->scan_null = true;
2808 : : else
2809 : 80 : result->scan_default = partition_bound_has_default(boundinfo);
2810 : 275 : return result;
2811 : : }
2812 : :
2813 : : /*
2814 : : * If there are no datums to compare keys with, but there are partitions,
2815 : : * just return the default partition if one exists.
2816 : : */
2817 [ - + ]: 5138 : if (boundinfo->ndatums == 0)
2818 : : {
2819 : 0 : result->scan_default = partition_bound_has_default(boundinfo);
2820 : 0 : return result;
2821 : : }
2822 : :
2823 : 5138 : minoff = 0;
2824 : 5138 : maxoff = boundinfo->ndatums - 1;
2825 : :
2826 : : /*
2827 : : * If there are no values to compare with the datums in boundinfo, it
2828 : : * means the caller asked for partitions for all non-null datums. Add
2829 : : * indexes of *all* partitions, including the default if any.
2830 : : */
2831 [ + + ]: 5138 : if (nvalues == 0)
2832 : : {
2833 : : Assert(boundinfo->ndatums > 0);
2834 : 100 : result->bound_offsets = bms_add_range(NULL, 0,
2835 : 50 : boundinfo->ndatums - 1);
2836 : 50 : result->scan_default = partition_bound_has_default(boundinfo);
2837 : 50 : return result;
2838 : : }
2839 : :
2840 : : /* Special case handling of values coming from a <> operator clause. */
2841 [ + + ]: 5088 : if (opstrategy == InvalidStrategy)
2842 : : {
2843 : : /*
2844 : : * First match to all bounds. We'll remove any matching datums below.
2845 : : */
2846 : : Assert(boundinfo->ndatums > 0);
2847 : 224 : result->bound_offsets = bms_add_range(NULL, 0,
2848 : 112 : boundinfo->ndatums - 1);
2849 : :
2850 : 112 : off = partition_list_bsearch(partsupfunc, partcollation, boundinfo,
2851 : : value, &is_equal);
2852 [ + + + + ]: 112 : if (off >= 0 && is_equal)
2853 : : {
2854 : :
2855 : : /* We have a match. Remove from the result. */
2856 : : Assert(boundinfo->indexes[off] >= 0);
2857 : 87 : result->bound_offsets = bms_del_member(result->bound_offsets,
2858 : : off);
2859 : : }
2860 : :
2861 : : /* Always include the default partition if any. */
2862 : 112 : result->scan_default = partition_bound_has_default(boundinfo);
2863 : :
2864 : 112 : return result;
2865 : : }
2866 : :
2867 : : /*
2868 : : * With range queries, always include the default list partition, because
2869 : : * list partitions divide the key space in a discontinuous manner, not all
2870 : : * values in the given range will have a partition assigned. This may not
2871 : : * technically be true for some data types (e.g. integer types), however,
2872 : : * we currently lack any sort of infrastructure to provide us with proofs
2873 : : * that would allow us to do anything smarter here.
2874 : : */
2875 [ + + ]: 4976 : if (opstrategy != BTEqualStrategyNumber)
2876 : 791 : result->scan_default = partition_bound_has_default(boundinfo);
2877 : :
2878 [ + + + + : 4976 : switch (opstrategy)
+ - ]
2879 : : {
2880 : 4185 : case BTEqualStrategyNumber:
2881 : 4185 : off = partition_list_bsearch(partsupfunc,
2882 : : partcollation,
2883 : : boundinfo, value,
2884 : : &is_equal);
2885 [ + + + + ]: 4185 : if (off >= 0 && is_equal)
2886 : : {
2887 : : Assert(boundinfo->indexes[off] >= 0);
2888 : 1954 : result->bound_offsets = bms_make_singleton(off);
2889 : : }
2890 : : else
2891 : 2231 : result->scan_default = partition_bound_has_default(boundinfo);
2892 : 4185 : return result;
2893 : :
2894 : 362 : case BTGreaterEqualStrategyNumber:
2895 : 362 : inclusive = true;
2896 : : pg_fallthrough;
2897 : 401 : case BTGreaterStrategyNumber:
2898 : 401 : off = partition_list_bsearch(partsupfunc,
2899 : : partcollation,
2900 : : boundinfo, value,
2901 : : &is_equal);
2902 [ + + ]: 401 : if (off >= 0)
2903 : : {
2904 : : /* We don't want the matched datum to be in the result. */
2905 [ + + + + ]: 316 : if (!is_equal || !inclusive)
2906 : 114 : off++;
2907 : : }
2908 : : else
2909 : : {
2910 : : /*
2911 : : * This case means all partition bounds are greater, which in
2912 : : * turn means that all partitions satisfy this key.
2913 : : */
2914 : 85 : off = 0;
2915 : : }
2916 : :
2917 : : /*
2918 : : * off is greater than the numbers of datums we have partitions
2919 : : * for. The only possible partition that could contain a match is
2920 : : * the default partition, but we must've set context->scan_default
2921 : : * above anyway if one exists.
2922 : : */
2923 [ + + ]: 401 : if (off > boundinfo->ndatums - 1)
2924 : 5 : return result;
2925 : :
2926 : 396 : minoff = off;
2927 : 396 : break;
2928 : :
2929 : 81 : case BTLessEqualStrategyNumber:
2930 : 81 : inclusive = true;
2931 : : pg_fallthrough;
2932 : 390 : case BTLessStrategyNumber:
2933 : 390 : off = partition_list_bsearch(partsupfunc,
2934 : : partcollation,
2935 : : boundinfo, value,
2936 : : &is_equal);
2937 [ + - + + : 390 : if (off >= 0 && is_equal && !inclusive)
+ + ]
2938 : 37 : off--;
2939 : :
2940 : : /*
2941 : : * off is smaller than the datums of all non-default partitions.
2942 : : * The only possible partition that could contain a match is the
2943 : : * default partition, but we must've set context->scan_default
2944 : : * above anyway if one exists.
2945 : : */
2946 [ + + ]: 390 : if (off < 0)
2947 : 5 : return result;
2948 : :
2949 : 385 : maxoff = off;
2950 : 385 : break;
2951 : :
2952 : 0 : default:
2953 [ # # ]: 0 : elog(ERROR, "invalid strategy number %d", opstrategy);
2954 : : break;
2955 : : }
2956 : :
2957 : : Assert(minoff >= 0 && maxoff >= 0);
2958 : 781 : result->bound_offsets = bms_add_range(NULL, minoff, maxoff);
2959 : 781 : return result;
2960 : : }
2961 : :
2962 : :
2963 : : /*
2964 : : * get_matching_range_bounds
2965 : : * Determine the offsets of range bounds matching the specified values,
2966 : : * according to the semantics of the given operator strategy
2967 : : *
2968 : : * Each datum whose offset is in result is to be treated as the upper bound of
2969 : : * the partition that will contain the desired values.
2970 : : *
2971 : : * scan_default is set in the returned struct if a default partition exists
2972 : : * and we're absolutely certain that it needs to be scanned. We do *not* set
2973 : : * it just because values match portions of the key space uncovered by
2974 : : * partitions other than default (space which we normally assume to belong to
2975 : : * the default partition): the final set of bounds obtained after combining
2976 : : * multiple pruning steps might exclude it, so we infer its inclusion
2977 : : * elsewhere.
2978 : : *
2979 : : * 'opstrategy' must be a btree strategy number.
2980 : : *
2981 : : * 'values' contains Datums indexed by the partition key to use for pruning.
2982 : : *
2983 : : * 'nvalues', number of Datums in 'values' array. Must be <= context->partnatts.
2984 : : *
2985 : : * 'partsupfunc' contains the range partitioning comparison functions to be
2986 : : * used to perform partition_range_datum_bsearch or partition_rbound_datum_cmp
2987 : : * using.
2988 : : *
2989 : : * 'nullkeys' is the set of partition keys that are null.
2990 : : */
2991 : : static PruneStepResult *
2992 : 4820 : get_matching_range_bounds(PartitionPruneContext *context,
2993 : : StrategyNumber opstrategy, const Datum *values, int nvalues,
2994 : : FmgrInfo *partsupfunc, Bitmapset *nullkeys)
2995 : : {
2996 : 4820 : PruneStepResult *result = palloc0_object(PruneStepResult);
2997 : 4820 : PartitionBoundInfo boundinfo = context->boundinfo;
2998 : 4820 : Oid *partcollation = context->partcollation;
2999 : 4820 : int partnatts = context->partnatts;
3000 : 4820 : int *partindices = boundinfo->indexes;
3001 : : int off,
3002 : : minoff,
3003 : : maxoff;
3004 : : bool is_equal;
3005 : 4820 : bool inclusive = false;
3006 : :
3007 : : Assert(context->strategy == PARTITION_STRATEGY_RANGE);
3008 : : Assert(nvalues <= partnatts);
3009 : :
3010 : 4820 : result->scan_null = result->scan_default = false;
3011 : :
3012 : : /*
3013 : : * If there are no datums to compare keys with, or if we got an IS NULL
3014 : : * clause just return the default partition, if it exists.
3015 : : */
3016 [ + + + + ]: 4820 : if (boundinfo->ndatums == 0 || !bms_is_empty(nullkeys))
3017 : : {
3018 : 55 : result->scan_default = partition_bound_has_default(boundinfo);
3019 : 55 : return result;
3020 : : }
3021 : :
3022 : 4765 : minoff = 0;
3023 : 4765 : maxoff = boundinfo->ndatums;
3024 : :
3025 : : /*
3026 : : * If there are no values to compare with the datums in boundinfo, it
3027 : : * means the caller asked for partitions for all non-null datums. Add
3028 : : * indexes of *all* partitions, including the default partition if one
3029 : : * exists.
3030 : : */
3031 [ + + ]: 4765 : if (nvalues == 0)
3032 : : {
3033 : 30 : result->scan_default = partition_bound_has_default(boundinfo);
3034 : : Assert(partindices[minoff] >= -1 &&
3035 : : partindices[maxoff] >= -1);
3036 : 30 : result->bound_offsets = bms_add_range(NULL, minoff, maxoff);
3037 : :
3038 : 30 : return result;
3039 : : }
3040 : :
3041 : : /*
3042 : : * If the query does not constrain all key columns, we'll need to scan the
3043 : : * default partition, if any.
3044 : : */
3045 [ + + ]: 4735 : if (nvalues < partnatts)
3046 : 599 : result->scan_default = partition_bound_has_default(boundinfo);
3047 : :
3048 [ + + + + : 4735 : switch (opstrategy)
+ - ]
3049 : : {
3050 : 3446 : case BTEqualStrategyNumber:
3051 : : /* Look for the smallest bound that is = lookup value. */
3052 : 3446 : off = partition_range_datum_bsearch(partsupfunc,
3053 : : partcollation,
3054 : : boundinfo,
3055 : : nvalues, values,
3056 : : &is_equal);
3057 : :
3058 [ + + + + ]: 3446 : if (off >= 0 && is_equal)
3059 : : {
3060 [ + + ]: 963 : if (nvalues == partnatts)
3061 : : {
3062 : : /* There can only be zero or one matching partition. */
3063 : 600 : result->bound_offsets = bms_make_singleton(off + 1);
3064 : 600 : return result;
3065 : : }
3066 : : else
3067 : : {
3068 : 363 : int saved_off = off;
3069 : :
3070 : : /*
3071 : : * Since the lookup value contains only a prefix of keys,
3072 : : * we must find other bounds that may also match the
3073 : : * prefix. partition_range_datum_bsearch() returns the
3074 : : * offset of one of them, find others by checking adjacent
3075 : : * bounds.
3076 : : */
3077 : :
3078 : : /*
3079 : : * First find greatest bound that's smaller than the
3080 : : * lookup value.
3081 : : */
3082 [ + + ]: 568 : while (off >= 1)
3083 : : {
3084 : : int32 cmpval;
3085 : :
3086 : : cmpval =
3087 : 493 : partition_rbound_datum_cmp(partsupfunc,
3088 : : partcollation,
3089 : 493 : boundinfo->datums[off - 1],
3090 : 493 : boundinfo->kind[off - 1],
3091 : : values, nvalues);
3092 [ + + ]: 493 : if (cmpval != 0)
3093 : 288 : break;
3094 : 205 : off--;
3095 : : }
3096 : :
3097 : : Assert(0 ==
3098 : : partition_rbound_datum_cmp(partsupfunc,
3099 : : partcollation,
3100 : : boundinfo->datums[off],
3101 : : boundinfo->kind[off],
3102 : : values, nvalues));
3103 : :
3104 : : /*
3105 : : * We can treat 'off' as the offset of the smallest bound
3106 : : * to be included in the result, if we know it is the
3107 : : * upper bound of the partition in which the lookup value
3108 : : * could possibly exist. One case it couldn't is if the
3109 : : * bound, or precisely the matched portion of its prefix,
3110 : : * is not inclusive.
3111 : : */
3112 [ + + ]: 363 : if (boundinfo->kind[off][nvalues] ==
3113 : : PARTITION_RANGE_DATUM_MINVALUE)
3114 : 25 : off++;
3115 : :
3116 : 363 : minoff = off;
3117 : :
3118 : : /*
3119 : : * Now find smallest bound that's greater than the lookup
3120 : : * value.
3121 : : */
3122 : 363 : off = saved_off;
3123 [ + + ]: 598 : while (off < boundinfo->ndatums - 1)
3124 : : {
3125 : : int32 cmpval;
3126 : :
3127 : 553 : cmpval = partition_rbound_datum_cmp(partsupfunc,
3128 : : partcollation,
3129 : 553 : boundinfo->datums[off + 1],
3130 : 553 : boundinfo->kind[off + 1],
3131 : : values, nvalues);
3132 [ + + ]: 553 : if (cmpval != 0)
3133 : 318 : break;
3134 : 235 : off++;
3135 : : }
3136 : :
3137 : : Assert(0 ==
3138 : : partition_rbound_datum_cmp(partsupfunc,
3139 : : partcollation,
3140 : : boundinfo->datums[off],
3141 : : boundinfo->kind[off],
3142 : : values, nvalues));
3143 : :
3144 : : /*
3145 : : * off + 1, then would be the offset of the greatest bound
3146 : : * to be included in the result.
3147 : : */
3148 : 363 : maxoff = off + 1;
3149 : : }
3150 : :
3151 : : Assert(minoff >= 0 && maxoff >= 0);
3152 : 363 : result->bound_offsets = bms_add_range(NULL, minoff, maxoff);
3153 : : }
3154 : : else
3155 : : {
3156 : : /*
3157 : : * The lookup value falls in the range between some bounds in
3158 : : * boundinfo. 'off' would be the offset of the greatest bound
3159 : : * that is <= lookup value, so add off + 1 to the result
3160 : : * instead as the offset of the upper bound of the only
3161 : : * partition that may contain the lookup value. If 'off' is
3162 : : * -1 indicating that all bounds are greater, then we simply
3163 : : * end up adding the first bound's offset, that is, 0.
3164 : : */
3165 : 2483 : result->bound_offsets = bms_make_singleton(off + 1);
3166 : : }
3167 : :
3168 : 2846 : return result;
3169 : :
3170 : 421 : case BTGreaterEqualStrategyNumber:
3171 : 421 : inclusive = true;
3172 : : pg_fallthrough;
3173 : 681 : case BTGreaterStrategyNumber:
3174 : :
3175 : : /*
3176 : : * Look for the smallest bound that is > or >= lookup value and
3177 : : * set minoff to its offset.
3178 : : */
3179 : 681 : off = partition_range_datum_bsearch(partsupfunc,
3180 : : partcollation,
3181 : : boundinfo,
3182 : : nvalues, values,
3183 : : &is_equal);
3184 [ + + ]: 681 : if (off < 0)
3185 : : {
3186 : : /*
3187 : : * All bounds are greater than the lookup value, so include
3188 : : * all of them in the result.
3189 : : */
3190 : 50 : minoff = 0;
3191 : : }
3192 : : else
3193 : : {
3194 [ + + + + ]: 631 : if (is_equal && nvalues < partnatts)
3195 : : {
3196 : : /*
3197 : : * Since the lookup value contains only a prefix of keys,
3198 : : * we must find other bounds that may also match the
3199 : : * prefix. partition_range_datum_bsearch() returns the
3200 : : * offset of one of them, find others by checking adjacent
3201 : : * bounds.
3202 : : *
3203 : : * Based on whether the lookup values are inclusive or
3204 : : * not, we must either include the indexes of all such
3205 : : * bounds in the result (that is, set minoff to the index
3206 : : * of smallest such bound) or find the smallest one that's
3207 : : * greater than the lookup values and set minoff to that.
3208 : : */
3209 [ + + + - ]: 110 : while (off >= 1 && off < boundinfo->ndatums - 1)
3210 : : {
3211 : : int32 cmpval;
3212 : : int nextoff;
3213 : :
3214 [ + + ]: 90 : nextoff = inclusive ? off - 1 : off + 1;
3215 : : cmpval =
3216 : 90 : partition_rbound_datum_cmp(partsupfunc,
3217 : : partcollation,
3218 : 90 : boundinfo->datums[nextoff],
3219 : 90 : boundinfo->kind[nextoff],
3220 : : values, nvalues);
3221 [ + + ]: 90 : if (cmpval != 0)
3222 : 45 : break;
3223 : :
3224 : 45 : off = nextoff;
3225 : : }
3226 : :
3227 : : Assert(0 ==
3228 : : partition_rbound_datum_cmp(partsupfunc,
3229 : : partcollation,
3230 : : boundinfo->datums[off],
3231 : : boundinfo->kind[off],
3232 : : values, nvalues));
3233 : :
3234 [ + + ]: 65 : minoff = inclusive ? off : off + 1;
3235 : : }
3236 : : else
3237 : : {
3238 : :
3239 : : /*
3240 : : * lookup value falls in the range between some bounds in
3241 : : * boundinfo. off would be the offset of the greatest
3242 : : * bound that is <= lookup value, so add off + 1 to the
3243 : : * result instead as the offset of the upper bound of the
3244 : : * smallest partition that may contain the lookup value.
3245 : : */
3246 : 566 : minoff = off + 1;
3247 : : }
3248 : : }
3249 : 681 : break;
3250 : :
3251 : 67 : case BTLessEqualStrategyNumber:
3252 : 67 : inclusive = true;
3253 : : pg_fallthrough;
3254 : 608 : case BTLessStrategyNumber:
3255 : :
3256 : : /*
3257 : : * Look for the greatest bound that is < or <= lookup value and
3258 : : * set maxoff to its offset.
3259 : : */
3260 : 608 : off = partition_range_datum_bsearch(partsupfunc,
3261 : : partcollation,
3262 : : boundinfo,
3263 : : nvalues, values,
3264 : : &is_equal);
3265 [ + - ]: 608 : if (off >= 0)
3266 : : {
3267 : : /*
3268 : : * See the comment above.
3269 : : */
3270 [ + + + + ]: 608 : if (is_equal && nvalues < partnatts)
3271 : : {
3272 [ + - + + ]: 108 : while (off >= 1 && off < boundinfo->ndatums - 1)
3273 : : {
3274 : : int32 cmpval;
3275 : : int nextoff;
3276 : :
3277 [ + + ]: 103 : nextoff = inclusive ? off + 1 : off - 1;
3278 : 103 : cmpval = partition_rbound_datum_cmp(partsupfunc,
3279 : : partcollation,
3280 : 103 : boundinfo->datums[nextoff],
3281 : 103 : boundinfo->kind[nextoff],
3282 : : values, nvalues);
3283 [ + + ]: 103 : if (cmpval != 0)
3284 : 83 : break;
3285 : :
3286 : 20 : off = nextoff;
3287 : : }
3288 : :
3289 : : Assert(0 ==
3290 : : partition_rbound_datum_cmp(partsupfunc,
3291 : : partcollation,
3292 : : boundinfo->datums[off],
3293 : : boundinfo->kind[off],
3294 : : values, nvalues));
3295 : :
3296 : 88 : maxoff = inclusive ? off + 1 : off;
3297 : : }
3298 : :
3299 : : /*
3300 : : * The lookup value falls in the range between some bounds in
3301 : : * boundinfo. 'off' would be the offset of the greatest bound
3302 : : * that is <= lookup value, so add off + 1 to the result
3303 : : * instead as the offset of the upper bound of the greatest
3304 : : * partition that may contain lookup value. If the lookup
3305 : : * value had exactly matched the bound, but it isn't
3306 : : * inclusive, no need add the adjacent partition.
3307 : : */
3308 [ + + + + ]: 520 : else if (!is_equal || inclusive)
3309 : 375 : maxoff = off + 1;
3310 : : else
3311 : 145 : maxoff = off;
3312 : : }
3313 : : else
3314 : : {
3315 : : /*
3316 : : * 'off' is -1 indicating that all bounds are greater, so just
3317 : : * set the first bound's offset as maxoff.
3318 : : */
3319 : 0 : maxoff = off + 1;
3320 : : }
3321 : 608 : break;
3322 : :
3323 : 0 : default:
3324 [ # # ]: 0 : elog(ERROR, "invalid strategy number %d", opstrategy);
3325 : : break;
3326 : : }
3327 : :
3328 : : Assert(minoff >= 0 && minoff <= boundinfo->ndatums);
3329 : : Assert(maxoff >= 0 && maxoff <= boundinfo->ndatums);
3330 : :
3331 : : /*
3332 : : * If the smallest partition to return has MINVALUE (negative infinity) as
3333 : : * its lower bound, increment it to point to the next finite bound
3334 : : * (supposedly its upper bound), so that we don't inadvertently end up
3335 : : * scanning the default partition.
3336 : : */
3337 [ + + + + ]: 1289 : if (minoff < boundinfo->ndatums && partindices[minoff] < 0)
3338 : : {
3339 : 733 : int lastkey = nvalues - 1;
3340 : :
3341 [ + + ]: 733 : if (boundinfo->kind[minoff][lastkey] ==
3342 : : PARTITION_RANGE_DATUM_MINVALUE)
3343 : : {
3344 : 135 : minoff++;
3345 : : Assert(boundinfo->indexes[minoff] >= 0);
3346 : : }
3347 : : }
3348 : :
3349 : : /*
3350 : : * If the previous greatest partition has MAXVALUE (positive infinity) as
3351 : : * its upper bound (something only possible to do with multi-column range
3352 : : * partitioning), we scan switch to it as the greatest partition to
3353 : : * return. Again, so that we don't inadvertently end up scanning the
3354 : : * default partition.
3355 : : */
3356 [ + - + + ]: 1289 : if (maxoff >= 1 && partindices[maxoff] < 0)
3357 : : {
3358 : 845 : int lastkey = nvalues - 1;
3359 : :
3360 [ + + ]: 845 : if (boundinfo->kind[maxoff - 1][lastkey] ==
3361 : : PARTITION_RANGE_DATUM_MAXVALUE)
3362 : : {
3363 : 129 : maxoff--;
3364 : : Assert(boundinfo->indexes[maxoff] >= 0);
3365 : : }
3366 : : }
3367 : :
3368 : : Assert(minoff >= 0 && maxoff >= 0);
3369 [ + - ]: 1289 : if (minoff <= maxoff)
3370 : 1289 : result->bound_offsets = bms_add_range(NULL, minoff, maxoff);
3371 : :
3372 : 1289 : return result;
3373 : : }
3374 : :
3375 : : /*
3376 : : * pull_exec_paramids
3377 : : * Returns a Bitmapset containing the paramids of all Params with
3378 : : * paramkind = PARAM_EXEC in 'expr'.
3379 : : */
3380 : : static Bitmapset *
3381 : 1543 : pull_exec_paramids(Expr *expr)
3382 : : {
3383 : 1543 : Bitmapset *result = NULL;
3384 : :
3385 : 1543 : (void) pull_exec_paramids_walker((Node *) expr, &result);
3386 : :
3387 : 1543 : return result;
3388 : : }
3389 : :
3390 : : static bool
3391 : 1964 : pull_exec_paramids_walker(Node *node, Bitmapset **context)
3392 : : {
3393 [ + + ]: 1964 : if (node == NULL)
3394 : 15 : return false;
3395 [ + + ]: 1949 : if (IsA(node, Param))
3396 : : {
3397 : 1536 : Param *param = (Param *) node;
3398 : :
3399 [ + + ]: 1536 : if (param->paramkind == PARAM_EXEC)
3400 : 1130 : *context = bms_add_member(*context, param->paramid);
3401 : 1536 : return false;
3402 : : }
3403 : 413 : return expression_tree_walker(node, pull_exec_paramids_walker, context);
3404 : : }
3405 : :
3406 : : /*
3407 : : * get_partkey_exec_paramids
3408 : : * Loop through given pruning steps and find out which exec Params
3409 : : * are used.
3410 : : *
3411 : : * Returns a Bitmapset of Param IDs.
3412 : : */
3413 : : static Bitmapset *
3414 : 345 : get_partkey_exec_paramids(List *steps)
3415 : : {
3416 : 345 : Bitmapset *execparamids = NULL;
3417 : : ListCell *lc;
3418 : :
3419 [ + - + + : 788 : foreach(lc, steps)
+ + ]
3420 : : {
3421 : 443 : PartitionPruneStepOp *step = (PartitionPruneStepOp *) lfirst(lc);
3422 : : ListCell *lc2;
3423 : :
3424 [ + + ]: 443 : if (!IsA(step, PartitionPruneStepOp))
3425 : 44 : continue;
3426 : :
3427 [ + - + + : 838 : foreach(lc2, step->exprs)
+ + ]
3428 : : {
3429 : 439 : Expr *expr = lfirst(lc2);
3430 : :
3431 : : /* We can be quick for plain Consts */
3432 [ + + ]: 439 : if (!IsA(expr, Const))
3433 : 390 : execparamids = bms_join(execparamids,
3434 : : pull_exec_paramids(expr));
3435 : : }
3436 : : }
3437 : :
3438 : 345 : return execparamids;
3439 : : }
3440 : :
3441 : : /*
3442 : : * perform_pruning_base_step
3443 : : * Determines the indexes of datums that satisfy conditions specified in
3444 : : * 'opstep'.
3445 : : *
3446 : : * Result also contains whether special null-accepting and/or default
3447 : : * partition need to be scanned.
3448 : : */
3449 : : static PruneStepResult *
3450 : 10498 : perform_pruning_base_step(PartitionPruneContext *context,
3451 : : PartitionPruneStepOp *opstep)
3452 : : {
3453 : : ListCell *lc1,
3454 : : *lc2;
3455 : : int keyno,
3456 : : nvalues;
3457 : : Datum values[PARTITION_MAX_KEYS];
3458 : : FmgrInfo *partsupfunc;
3459 : : int stateidx;
3460 : :
3461 : : /*
3462 : : * There better be the same number of expressions and compare functions.
3463 : : */
3464 : : Assert(list_length(opstep->exprs) == list_length(opstep->cmpfns));
3465 : :
3466 : 10498 : nvalues = 0;
3467 : 10498 : lc1 = list_head(opstep->exprs);
3468 : 10498 : lc2 = list_head(opstep->cmpfns);
3469 : :
3470 : : /*
3471 : : * Generate the partition lookup key that will be used by one of the
3472 : : * get_matching_*_bounds functions called below.
3473 : : */
3474 [ + + ]: 22538 : for (keyno = 0; keyno < context->partnatts; keyno++)
3475 : : {
3476 : : /*
3477 : : * For hash partitioning, it is possible that values of some keys are
3478 : : * not provided in operator clauses, but instead the planner found
3479 : : * that they appeared in a IS NULL clause.
3480 : : */
3481 [ + + ]: 12350 : if (bms_is_member(keyno, opstep->nullkeys))
3482 : 689 : continue;
3483 : :
3484 : : /*
3485 : : * For range partitioning, we must only perform pruning with values
3486 : : * for either all partition keys or a prefix thereof.
3487 : : */
3488 [ + + + + ]: 11661 : if (keyno > nvalues && context->strategy == PARTITION_STRATEGY_RANGE)
3489 : 306 : break;
3490 : :
3491 [ + + ]: 11355 : if (lc1 != NULL)
3492 : : {
3493 : : Expr *expr;
3494 : : Datum datum;
3495 : : bool isnull;
3496 : : Oid cmpfn;
3497 : :
3498 : 10666 : expr = lfirst(lc1);
3499 : 10666 : stateidx = PruneCxtStateIdx(context->partnatts,
3500 : : opstep->step.step_id, keyno);
3501 : 10666 : partkey_datum_from_expr(context, expr, stateidx,
3502 : : &datum, &isnull);
3503 : :
3504 : : /*
3505 : : * Since we only allow strict operators in pruning steps, any
3506 : : * null-valued comparison value must cause the comparison to fail,
3507 : : * so that no partitions could match.
3508 : : */
3509 [ + + ]: 10666 : if (isnull)
3510 : : {
3511 : : PruneStepResult *result;
3512 : :
3513 : 4 : result = palloc_object(PruneStepResult);
3514 : 4 : result->bound_offsets = NULL;
3515 : 4 : result->scan_default = false;
3516 : 4 : result->scan_null = false;
3517 : :
3518 : 4 : return result;
3519 : : }
3520 : :
3521 : : /* Set up the stepcmpfuncs entry, unless we already did */
3522 : 10662 : cmpfn = lfirst_oid(lc2);
3523 : : Assert(OidIsValid(cmpfn));
3524 [ + + ]: 10662 : if (cmpfn != context->stepcmpfuncs[stateidx].fn_oid)
3525 : : {
3526 : : /*
3527 : : * If the needed support function is the same one cached in
3528 : : * the relation's partition key, copy the cached FmgrInfo.
3529 : : * Otherwise (i.e., when we have a cross-type comparison), an
3530 : : * actual lookup is required.
3531 : : */
3532 [ + + ]: 8554 : if (cmpfn == context->partsupfunc[keyno].fn_oid)
3533 : 8469 : fmgr_info_copy(&context->stepcmpfuncs[stateidx],
3534 : 8469 : &context->partsupfunc[keyno],
3535 : : context->ppccontext);
3536 : : else
3537 : 85 : fmgr_info_cxt(cmpfn, &context->stepcmpfuncs[stateidx],
3538 : : context->ppccontext);
3539 : : }
3540 : :
3541 : 10662 : values[keyno] = datum;
3542 : 10662 : nvalues++;
3543 : :
3544 : 10662 : lc1 = lnext(opstep->exprs, lc1);
3545 : 10662 : lc2 = lnext(opstep->cmpfns, lc2);
3546 : : }
3547 : : }
3548 : :
3549 : : /*
3550 : : * Point partsupfunc to the entry for the 0th key of this step; the
3551 : : * additional support functions, if any, follow consecutively.
3552 : : */
3553 : 10494 : stateidx = PruneCxtStateIdx(context->partnatts, opstep->step.step_id, 0);
3554 : 10494 : partsupfunc = &context->stepcmpfuncs[stateidx];
3555 : :
3556 [ + + + - ]: 10494 : switch (context->strategy)
3557 : : {
3558 : 261 : case PARTITION_STRATEGY_HASH:
3559 : 261 : return get_matching_hash_bounds(context,
3560 : 261 : opstep->opstrategy,
3561 : : values, nvalues,
3562 : : partsupfunc,
3563 : : opstep->nullkeys);
3564 : :
3565 : 5413 : case PARTITION_STRATEGY_LIST:
3566 : 5413 : return get_matching_list_bounds(context,
3567 : 5413 : opstep->opstrategy,
3568 : : values[0], nvalues,
3569 : : &partsupfunc[0],
3570 : : opstep->nullkeys);
3571 : :
3572 : 4820 : case PARTITION_STRATEGY_RANGE:
3573 : 4820 : return get_matching_range_bounds(context,
3574 : 4820 : opstep->opstrategy,
3575 : : values, nvalues,
3576 : : partsupfunc,
3577 : : opstep->nullkeys);
3578 : :
3579 : 0 : default:
3580 [ # # ]: 0 : elog(ERROR, "unexpected partition strategy: %d",
3581 : : (int) context->strategy);
3582 : : break;
3583 : : }
3584 : :
3585 : : return NULL;
3586 : : }
3587 : :
3588 : : /*
3589 : : * perform_pruning_combine_step
3590 : : * Determines the indexes of datums obtained by combining those given
3591 : : * by the steps identified by cstep->source_stepids using the specified
3592 : : * combination method
3593 : : *
3594 : : * Since cstep may refer to the result of earlier steps, we also receive
3595 : : * step_results here.
3596 : : */
3597 : : static PruneStepResult *
3598 : 2135 : perform_pruning_combine_step(PartitionPruneContext *context,
3599 : : PartitionPruneStepCombine *cstep,
3600 : : PruneStepResult **step_results)
3601 : : {
3602 : 2135 : PruneStepResult *result = palloc0_object(PruneStepResult);
3603 : : bool firststep;
3604 : : ListCell *lc1;
3605 : :
3606 : : /*
3607 : : * A combine step without any source steps is an indication to not perform
3608 : : * any partition pruning. Return all datum indexes in that case.
3609 : : */
3610 [ + + ]: 2135 : if (cstep->source_stepids == NIL)
3611 : : {
3612 : 319 : PartitionBoundInfo boundinfo = context->boundinfo;
3613 : :
3614 : 319 : result->bound_offsets =
3615 : 319 : bms_add_range(NULL, 0, boundinfo->nindexes - 1);
3616 : 319 : result->scan_default = partition_bound_has_default(boundinfo);
3617 : 319 : result->scan_null = partition_bound_accepts_nulls(boundinfo);
3618 : 319 : return result;
3619 : : }
3620 : :
3621 [ + + - ]: 1816 : switch (cstep->combineOp)
3622 : : {
3623 : 989 : case PARTPRUNE_COMBINE_UNION:
3624 [ + - + + : 3023 : foreach(lc1, cstep->source_stepids)
+ + ]
3625 : : {
3626 : 2034 : int step_id = lfirst_int(lc1);
3627 : : PruneStepResult *step_result;
3628 : :
3629 : : /*
3630 : : * step_results[step_id] must contain a valid result, which is
3631 : : * confirmed by the fact that cstep's step_id is greater than
3632 : : * step_id and the fact that results of the individual steps
3633 : : * are evaluated in sequence of their step_ids.
3634 : : */
3635 [ - + ]: 2034 : if (step_id >= cstep->step.step_id)
3636 [ # # ]: 0 : elog(ERROR, "invalid pruning combine step argument");
3637 : 2034 : step_result = step_results[step_id];
3638 : : Assert(step_result != NULL);
3639 : :
3640 : : /* Record any additional datum indexes from this step */
3641 : 4068 : result->bound_offsets = bms_add_members(result->bound_offsets,
3642 : 2034 : step_result->bound_offsets);
3643 : :
3644 : : /* Update whether to scan null and default partitions. */
3645 [ + + ]: 2034 : if (!result->scan_null)
3646 : 1949 : result->scan_null = step_result->scan_null;
3647 [ + + ]: 2034 : if (!result->scan_default)
3648 : 1799 : result->scan_default = step_result->scan_default;
3649 : : }
3650 : 989 : break;
3651 : :
3652 : 827 : case PARTPRUNE_COMBINE_INTERSECT:
3653 : 827 : firststep = true;
3654 [ + - + + : 2947 : foreach(lc1, cstep->source_stepids)
+ + ]
3655 : : {
3656 : 2120 : int step_id = lfirst_int(lc1);
3657 : : PruneStepResult *step_result;
3658 : :
3659 [ - + ]: 2120 : if (step_id >= cstep->step.step_id)
3660 [ # # ]: 0 : elog(ERROR, "invalid pruning combine step argument");
3661 : 2120 : step_result = step_results[step_id];
3662 : : Assert(step_result != NULL);
3663 : :
3664 [ + + ]: 2120 : if (firststep)
3665 : : {
3666 : : /* Copy step's result the first time. */
3667 : 827 : result->bound_offsets =
3668 : 827 : bms_copy(step_result->bound_offsets);
3669 : 827 : result->scan_null = step_result->scan_null;
3670 : 827 : result->scan_default = step_result->scan_default;
3671 : 827 : firststep = false;
3672 : : }
3673 : : else
3674 : : {
3675 : : /* Record datum indexes common to both steps */
3676 : 1293 : result->bound_offsets =
3677 : 1293 : bms_int_members(result->bound_offsets,
3678 : 1293 : step_result->bound_offsets);
3679 : :
3680 : : /* Update whether to scan null and default partitions. */
3681 [ + + ]: 1293 : if (result->scan_null)
3682 : 80 : result->scan_null = step_result->scan_null;
3683 [ + + ]: 1293 : if (result->scan_default)
3684 : 630 : result->scan_default = step_result->scan_default;
3685 : : }
3686 : : }
3687 : 827 : break;
3688 : : }
3689 : :
3690 : 1816 : return result;
3691 : : }
3692 : :
3693 : : /*
3694 : : * match_boolean_partition_clause
3695 : : *
3696 : : * If we're able to match the clause to the partition key as specially-shaped
3697 : : * boolean clause, set *outconst to a Const containing a true, false or NULL
3698 : : * value, set *notclause according to if the clause was in the "not" form,
3699 : : * i.e. "IS NOT TRUE", "IS NOT FALSE" or "IS NOT UNKNOWN" and return
3700 : : * PARTCLAUSE_MATCH_CLAUSE for "IS [NOT] (TRUE|FALSE)" clauses and
3701 : : * PARTCLAUSE_MATCH_NULLNESS for "IS [NOT] UNKNOWN" clauses. Otherwise,
3702 : : * return PARTCLAUSE_UNSUPPORTED if the clause cannot be used for partition
3703 : : * pruning, and PARTCLAUSE_NOMATCH for supported clauses that do not match this
3704 : : * 'partkey'.
3705 : : */
3706 : : static PartClauseMatchStatus
3707 : 29889 : match_boolean_partition_clause(Oid partopfamily, Expr *clause, const Expr *partkey,
3708 : : Expr **outconst, bool *notclause)
3709 : : {
3710 : : Expr *leftop;
3711 : :
3712 : 29889 : *outconst = NULL;
3713 : 29889 : *notclause = false;
3714 : :
3715 : : /*
3716 : : * Partitioning currently can only use built-in AMs, so checking for
3717 : : * built-in boolean opfamilies is good enough.
3718 : : */
3719 [ + + + - ]: 29889 : if (!IsBuiltinBooleanOpfamily(partopfamily))
3720 : 28659 : return PARTCLAUSE_UNSUPPORTED;
3721 : :
3722 [ + + ]: 1230 : if (IsA(clause, BooleanTest))
3723 : : {
3724 : 670 : BooleanTest *btest = (BooleanTest *) clause;
3725 : :
3726 : 670 : leftop = btest->arg;
3727 : 670 : leftop = (Expr *) strip_noop_phvs((Node *) leftop);
3728 [ - + ]: 670 : while (IsA(leftop, RelabelType))
3729 : 0 : leftop = ((RelabelType *) leftop)->arg;
3730 : :
3731 [ + + ]: 670 : if (equal(leftop, partkey))
3732 : : {
3733 [ + + + + : 490 : switch (btest->booltesttype)
+ + - ]
3734 : : {
3735 : 110 : case IS_NOT_TRUE:
3736 : 110 : *notclause = true;
3737 : : pg_fallthrough;
3738 : 225 : case IS_TRUE:
3739 : 225 : *outconst = (Expr *) makeBoolConst(true, false);
3740 : 225 : return PARTCLAUSE_MATCH_CLAUSE;
3741 : 70 : case IS_NOT_FALSE:
3742 : 70 : *notclause = true;
3743 : : pg_fallthrough;
3744 : 185 : case IS_FALSE:
3745 : 185 : *outconst = (Expr *) makeBoolConst(false, false);
3746 : 185 : return PARTCLAUSE_MATCH_CLAUSE;
3747 : 45 : case IS_NOT_UNKNOWN:
3748 : 45 : *notclause = true;
3749 : : pg_fallthrough;
3750 : 80 : case IS_UNKNOWN:
3751 : 80 : return PARTCLAUSE_MATCH_NULLNESS;
3752 : 0 : default:
3753 : 0 : return PARTCLAUSE_UNSUPPORTED;
3754 : : }
3755 : : }
3756 : : /* does not match partition key */
3757 : 180 : return PARTCLAUSE_NOMATCH;
3758 : : }
3759 : : else
3760 : : {
3761 : 560 : bool is_not_clause = is_notclause(clause);
3762 : :
3763 [ + + ]: 560 : leftop = is_not_clause ? get_notclausearg(clause) : clause;
3764 : :
3765 : 560 : leftop = (Expr *) strip_noop_phvs((Node *) leftop);
3766 [ - + ]: 560 : while (IsA(leftop, RelabelType))
3767 : 0 : leftop = ((RelabelType *) leftop)->arg;
3768 : :
3769 : : /* Compare to the partition key, and make up a clause ... */
3770 [ + + ]: 560 : if (equal(leftop, partkey))
3771 : 120 : *outconst = (Expr *) makeBoolConst(!is_not_clause, false);
3772 [ + + ]: 440 : else if (equal(negate_clause((Node *) leftop), partkey))
3773 : 40 : *outconst = (Expr *) makeBoolConst(is_not_clause, false);
3774 : : else
3775 : 400 : return PARTCLAUSE_NOMATCH;
3776 : :
3777 : 160 : return PARTCLAUSE_MATCH_CLAUSE;
3778 : : }
3779 : : }
3780 : :
3781 : : /*
3782 : : * partkey_datum_from_expr
3783 : : * Evaluate expression for potential partition pruning
3784 : : *
3785 : : * Evaluate 'expr'; set *value and *isnull to the resulting Datum and nullflag.
3786 : : *
3787 : : * If expr isn't a Const, its ExprState is in stateidx of the context
3788 : : * exprstate array.
3789 : : *
3790 : : * Note that the evaluated result may be in the per-tuple memory context of
3791 : : * context->exprcontext, and we may have leaked other memory there too.
3792 : : * This memory must be recovered by resetting that ExprContext after
3793 : : * we're done with the pruning operation (see execPartition.c).
3794 : : */
3795 : : static void
3796 : 10666 : partkey_datum_from_expr(PartitionPruneContext *context,
3797 : : Expr *expr, int stateidx,
3798 : : Datum *value, bool *isnull)
3799 : : {
3800 [ + + ]: 10666 : if (IsA(expr, Const))
3801 : : {
3802 : : /* We can always determine the value of a constant */
3803 : 7779 : Const *con = (Const *) expr;
3804 : :
3805 : 7779 : *value = con->constvalue;
3806 : 7779 : *isnull = con->constisnull;
3807 : : }
3808 : : else
3809 : : {
3810 : : ExprState *exprstate;
3811 : : ExprContext *ectx;
3812 : :
3813 : : /*
3814 : : * We should never see a non-Const in a step unless the caller has
3815 : : * passed a valid ExprContext.
3816 : : */
3817 : : Assert(context->exprcontext != NULL);
3818 : :
3819 : 2887 : exprstate = context->exprstates[stateidx];
3820 : 2887 : ectx = context->exprcontext;
3821 : 2887 : *value = ExecEvalExprSwitchContext(exprstate, ectx, isnull);
3822 : : }
3823 : 10666 : }
|