LCOV - code coverage report
Current view: top level - src/backend/partitioning - partprune.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12beta1 Lines: 898 962 93.3 %
Date: 2019-06-16 15:06:48 Functions: 22 22 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13