pg.ddx.io  pgsql-bugs@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Amit Langote <Langote_Amit_f8@lab.ntt.co.jp>
To: David Rowley <david.rowley@2ndquadrant.com>
To: Tom Lane <tgl@sss.pgh.pa.us>
Cc: Kyotaro HORIGUCHI <horiguchi.kyotaro@lab.ntt.co.jp>
Cc: ajax@tvsquared.com, PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>
Subject: Re: inconsistent results querying table partitioned by date
Date: Wed, 15 May 2019 11:10:24 +0900
Message-ID: <588f56cb-aaed-14b0-8a21-13486bd1c706@lab.ntt.co.jp> (raw)
In-Reply-To: <CAKJS1f82n-WNsu6G5WNXGFV4MsnosydiouRvTNnZYmQz0tciuQ@mail.gmail.com>
References: <FAD28A83-AC73-489E-A058-2681FA31D648@tvsquared.com>
	<24525.1557444159@sss.pgh.pa.us>
	<49cd5235-cbe6-e686-8014-85c1e45efe56@lab.ntt.co.jp>
	<20190510.153337.236910404.horiguchi.kyotaro@lab.ntt.co.jp>
	<90aeaf38-270a-7e45-6b7d-af2e3d1e3719@lab.ntt.co.jp>
	<20307.1557522309@sss.pgh.pa.us>
	<a0bca4f7-b493-4d0a-8080-8dad3748c5ae@lab.ntt.co.jp>
	<CAKJS1f92Uq+SV+WKKa+B5Fd9PcrwhYFsvxUudm_9F8egi4paXQ@mail.gmail.com>
	<d7878f1f-f7c5-4f23-127e-ced79a64ddf1@lab.ntt.co.jp>
	<CAKJS1f-xHgnr0QVfGtt9BU38kB8a5fp4Y=CYbChV8xSqw6pZ9w@mail.gmail.com>
	<e903adfc-c7a5-58f9-6b7f-16ab6f48be5c@lab.ntt.co.jp>
	<28453.1557867500@sss.pgh.pa.us>
	<CAKJS1f82n-WNsu6G5WNXGFV4MsnosydiouRvTNnZYmQz0tciuQ@mail.gmail.com>

Thanks for the updated patches.

On 2019/05/15 8:52, David Rowley wrote:
> On Wed, 15 May 2019 at 08:58, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> So I think David's got the right idea that match_clause_to_partition_key
>> is where to handle this, and I like the fact that his patch explicitly
>> represents whether we're trying to do run-time or plan-time pruning.
>> I agree it's kind of invasive, and I wonder why.  Shouldn't the
>> additional flag just be a field in the "context" struct, instead of
>> being a separate parameter that has to be laboriously passed through
>> many call levels?
> 
> Thanks for having a look.  I originally stayed clear of "context"
> since it looks more like how we output the pruning steps, rather than
> a context as to how they should be generated. But it's true, using it
> saves having to pass the extra argument around, so I made that change.
> 
>> (For myself, I'd have made it just a bool not an enum, given that
>> I don't foresee a need for additional values.  But that's definitely
>> a matter of preference.)
> 
> I've changed to bool, mostly because it makes the patch a bit smaller.

Looks good.  Thanks for tweaking many comments for clarity, except this
one could be improved a bit more:

+ * 'forplanner' must be true when being called from the query planner.

This description of 'forplanner' might make it sound like it's redundant
(always true), because gen_partprune_steps() is only called from the
planner today.  How about making it say the same thing as the comment next
to its definition in GeneratePruningStepsContext struct):

'forplanner' must be true if generating steps to be used during query
planning.

>> Also, I'm a bit confused by the fact that we seem to have a bunch
>> of spare-parts patches in this thread.  What combination is actually
>> being proposed for commit?
> 
> I was also confused at the extra two patches Amit posted. The extra
> one for the tests didn't look very valid to me, as I mentioned
> yesterday.

As I said in my previous reply, 0001 contains wrong expected output
because of the other bugs discussed earlier.  I guess that's not very helpful.

Anyway, I'm attaching a squashed version of those two patches as
0001-Fix-bugs-in-pruning-with-composite-range-partition-k.patch.  It
applies as-is to both master and v11 branches.

> I propose the attached for master, and I'll post something for v11 shortly.

Thanks.  I'm re-attaching both of your patches here just to have all the
patches in one place.

Thanks,
Amit

Attachments: download all (3 files, .tar.gz)

0001-Fix-bugs-in-pruning-with-composite-range-partition-k.patch (text/plain, 9.5K) download From 98fcda92959d46a471e3b64e90dd74489c3d992a Mon Sep 17 00:00:00 2001 From: amit <amitlangote09@gmail.com> Date: Fri, 10 May 2019 13:52:41 +0900 Subject: [PATCH] Fix bugs in pruning with composite range partition keys * Force using equality (= operator) semantics when comparing clause expressions against partition bounds if the expression for the last matched key cannot be evaluated in a given pruning context; for example, if the expression is stable and pruning is invoked by the planner * Ignore keys after a given key for which we detected a clause containing a non-inclusive operator --- src/backend/partitioning/partprune.c | 88 +++++++++++++-------------- src/test/regress/expected/partition_prune.out | 45 ++++++++++++++ src/test/regress/sql/partition_prune.sql | 8 +++ 3 files changed, 95 insertions(+), 46 deletions(-) diff --git a/src/backend/partitioning/partprune.c b/src/backend/partitioning/partprune.c index b5c1c7d4dd..7c894fc6ad 100644 --- a/src/backend/partitioning/partprune.c +++ b/src/backend/partitioning/partprune.c @@ -1152,17 +1152,24 @@ gen_prune_steps_from_opexps(PartitionScheme part_scheme, List *opsteps = NIL; List *btree_clauses[BTMaxStrategyNumber + 1], *hash_clauses[HTMaxStrategyNumber + 1]; - bool need_next_less, - need_next_eq, - need_next_greater; + bool consider_next_key; int i; + consider_next_key = true; memset(btree_clauses, 0, sizeof(btree_clauses)); memset(hash_clauses, 0, sizeof(hash_clauses)); for (i = 0; i < part_scheme->partnatts; i++) { List *clauselist = keyclauses[i]; - bool consider_next_key = true; + + /* + * If the previous key was found to be compared using such an operator + * that comparisons of subsequent key columns against partition bounds + * that occurs during partition pruning would be redundant, then don't + * bother generating pruning steps for them. + */ + if (!consider_next_key) + break; /* * To be useful for pruning, we must have clauses for a prefix of @@ -1182,7 +1189,6 @@ gen_prune_steps_from_opexps(PartitionScheme part_scheme, clauselist == NIL && !bms_is_member(i, nullkeys)) return NULL; - need_next_eq = need_next_less = need_next_greater = true; foreach(lc, clauselist) { PartClauseInfo *pc = (PartClauseInfo *) lfirst(lc); @@ -1198,13 +1204,13 @@ gen_prune_steps_from_opexps(PartitionScheme part_scheme, &lefttype, &righttype); + switch (part_scheme->strategy) { case PARTITION_STRATEGY_LIST: case PARTITION_STRATEGY_RANGE: { PartClauseInfo *last = NULL; - bool inclusive = false; /* * Add this clause to the list of clauses to be used @@ -1222,35 +1228,14 @@ gen_prune_steps_from_opexps(PartitionScheme part_scheme, lappend(btree_clauses[pc->op_strategy], pc); /* - * We may not need the next clause if they're of - * certain strategy. + * We won't need the clause for the next key if the + * clause for the current key contains a non-inclusive + * operator. */ - switch (pc->op_strategy) - { - case BTLessEqualStrategyNumber: - inclusive = true; - /* fall through */ - case BTLessStrategyNumber: - if (!inclusive) - need_next_eq = need_next_less = false; - break; - case BTEqualStrategyNumber: - /* always accept clauses for the next key. */ - break; - case BTGreaterEqualStrategyNumber: - inclusive = true; - /* fall through */ - case BTGreaterStrategyNumber: - if (!inclusive) - need_next_eq = need_next_greater = false; - break; - } + if (pc->op_strategy == BTLessStrategyNumber || + pc->op_strategy == BTGreaterStrategyNumber) + consider_next_key = false; - /* We may want to change our mind. */ - if (consider_next_key) - consider_next_key = (need_next_eq || - need_next_less || - need_next_greater); break; } @@ -1267,13 +1252,6 @@ gen_prune_steps_from_opexps(PartitionScheme part_scheme, break; } } - - /* - * If we've decided that clauses for subsequent partition keys - * wouldn't be useful for pruning, don't search any further. - */ - if (!consider_next_key) - break; } /* @@ -2736,7 +2714,7 @@ get_matching_range_bounds(PartitionPruneContext *context, /* * Look for the greatest bound that is < or <= lookup value and - * set minoff to its offset. + * set maxoff to its offset. */ off = partition_range_datum_bsearch(partsupfunc, partcollation, @@ -3103,11 +3081,29 @@ perform_pruning_base_step(PartitionPruneContext *context, opstep->nullkeys); case PARTITION_STRATEGY_RANGE: - return get_matching_range_bounds(context, - opstep->opstrategy, - values, nvalues, - partsupfunc, - opstep->nullkeys); + { + int opstrategy = opstep->opstrategy; + + /* + * If we got values for only a subset (prefix) of the + * expressions in opstep->exprs, adjust the strategy to + * be used for pruning. Originally, it would be the strategy + * of the operator comparing the *last* expression against the + * corresponding partition key, but it would be wrong to use + * the same strategy now that we'll be comparing the values of + * only a prefix of expressions against the partition bounds. + * Use equality strategy, because all expressions in the + * prefix must have been extracted from clauses containing + * equality (=) or inclusive operators (<=, >=) anyway. + */ + if (nvalues < list_length(opstep->exprs)) + opstrategy = BTEqualStrategyNumber; + return get_matching_range_bounds(context, + opstrategy, + values, nvalues, + partsupfunc, + opstep->nullkeys); + } default: elog(ERROR, "unexpected partition strategy: %d", diff --git a/src/test/regress/expected/partition_prune.out b/src/test/regress/expected/partition_prune.out index 6f320dfff4..889d4e14e2 100644 --- a/src/test/regress/expected/partition_prune.out +++ b/src/test/regress/expected/partition_prune.out @@ -938,6 +938,51 @@ explain (costs off) select * from mc3p where (a = 1 and abs(b) = 1) or (a = 10 a Filter: (((a = 1) AND (abs(b) = 1)) OR ((a = 10) AND (abs(b) = 9))) (9 rows) +-- +-- Check that pruning with composite range partitioning works correctly +-- correctly in the face of combination of static and runtime values being +-- passed to perform plan-time pruning with +-- +explain (analyze, costs off, summary off, timing off) select * from mc3p where a = 1 and abs(b) < (select 2); + QUERY PLAN +-------------------------------------------------------- + Append (actual rows=0 loops=1) + InitPlan 1 (returns $0) + -> Result (actual rows=1 loops=1) + -> Seq Scan on mc3p0 (actual rows=0 loops=1) + Filter: ((a = 1) AND (abs(b) < $0)) + -> Seq Scan on mc3p1 (actual rows=0 loops=1) + Filter: ((a = 1) AND (abs(b) < $0)) + -> Seq Scan on mc3p_default (actual rows=0 loops=1) + Filter: ((a = 1) AND (abs(b) < $0)) +(9 rows) + +explain (analyze, costs off, summary off, timing off) select * from mc3p where a < (select 1) and abs(b) = 1; + QUERY PLAN +-------------------------------------------------------- + Append (actual rows=0 loops=1) + InitPlan 1 (returns $0) + -> Result (actual rows=1 loops=1) + -> Seq Scan on mc3p0 (actual rows=0 loops=1) + Filter: ((a < $0) AND (abs(b) = 1)) + -> Seq Scan on mc3p1 (never executed) + Filter: ((a < $0) AND (abs(b) = 1)) + -> Seq Scan on mc3p2 (never executed) + Filter: ((a < $0) AND (abs(b) = 1)) + -> Seq Scan on mc3p3 (never executed) + Filter: ((a < $0) AND (abs(b) = 1)) + -> Seq Scan on mc3p4 (never executed) + Filter: ((a < $0) AND (abs(b) = 1)) + -> Seq Scan on mc3p5 (never executed) + Filter: ((a < $0) AND (abs(b) = 1)) + -> Seq Scan on mc3p6 (never executed) + Filter: ((a < $0) AND (abs(b) = 1)) + -> Seq Scan on mc3p7 (never executed) + Filter: ((a < $0) AND (abs(b) = 1)) + -> Seq Scan on mc3p_default (actual rows=0 loops=1) + Filter: ((a < $0) AND (abs(b) = 1)) +(21 rows) + -- a simpler multi-column keys case create table mc2p (a int, b int) partition by range (a, b); create table mc2p_default partition of mc2p default; diff --git a/src/test/regress/sql/partition_prune.sql b/src/test/regress/sql/partition_prune.sql index eafbec6f35..b78b08dfc1 100644 --- a/src/test/regress/sql/partition_prune.sql +++ b/src/test/regress/sql/partition_prune.sql @@ -122,6 +122,14 @@ explain (costs off) select * from mc3p where a = 1 or abs(b) = 1 or c = 1; explain (costs off) select * from mc3p where (a = 1 and abs(b) = 1) or (a = 10 and abs(b) = 10); explain (costs off) select * from mc3p where (a = 1 and abs(b) = 1) or (a = 10 and abs(b) = 9); +-- +-- Check that pruning with composite range partitioning works correctly +-- correctly in the face of combination of static and runtime values being +-- passed to perform plan-time pruning with +-- +explain (analyze, costs off, summary off, timing off) select * from mc3p where a = 1 and abs(b) < (select 2); +explain (analyze, costs off, summary off, timing off) select * from mc3p where a < (select 1) and abs(b) = 1; + -- a simpler multi-column keys case create table mc2p (a int, b int) partition by range (a, b); create table mc2p_default partition of mc2p default; -- 2.11.0
dont_prune_with_nonimmutable_opfuncs_during_planning_v2.patch (text/plain, 10.0K) download diff --git a/src/backend/partitioning/partprune.c b/src/backend/partitioning/partprune.c index 59f34f5cac..5e1329a5e4 100644 --- a/src/backend/partitioning/partprune.c +++ b/src/backend/partitioning/partprune.c @@ -39,6 +39,7 @@ #include "access/nbtree.h" #include "catalog/pg_operator.h" #include "catalog/pg_opfamily.h" +#include "catalog/pg_proc.h" #include "catalog/pg_type.h" #include "executor/executor.h" #include "miscadmin.h" @@ -95,6 +96,8 @@ typedef struct GeneratePruningStepsContext { int next_step_id; List *steps; + bool forplanner; /* true when generating steps to be used + * during query planning */ } GeneratePruningStepsContext; /* The result of performing one PartitionPruneStep */ @@ -117,7 +120,7 @@ static List *make_partitionedrel_pruneinfo(PlannerInfo *root, List *partitioned_rels, List *prunequal, Bitmapset **matchedsubplans); static List *gen_partprune_steps(RelOptInfo *rel, List *clauses, - bool *contradictory); + bool forplanner, bool *contradictory); static List *gen_partprune_steps_internal(GeneratePruningStepsContext *context, RelOptInfo *rel, List *clauses, bool *contradictory); @@ -409,8 +412,13 @@ make_partitionedrel_pruneinfo(PlannerInfo *root, RelOptInfo *parentrel, targetpart->relids); } - /* Convert pruning qual to pruning steps. */ - pruning_steps = gen_partprune_steps(subpart, partprunequal, + /* + * Convert pruning qual to pruning steps. Since these steps will be + * executed during execution, we can pass 'forplanner' as false to + * allow steps to be generated that are unsafe for evaluation during + * planning, e.g. evaluation of stable functions. + */ + pruning_steps = gen_partprune_steps(subpart, partprunequal, false, &contradictory); if (contradictory) @@ -523,18 +531,22 @@ make_partitionedrel_pruneinfo(PlannerInfo *root, RelOptInfo *parentrel, /* * gen_partprune_steps * Process 'clauses' (a rel's baserestrictinfo list of clauses) and return - * a list of "partition pruning steps" + * a list of "partition pruning steps". + * + * 'forplanner' must be true when being called from the query planner. * * If the clauses in the input list are contradictory or there is a * pseudo-constant "false", *contradictory is set to true upon return. */ static List * -gen_partprune_steps(RelOptInfo *rel, List *clauses, bool *contradictory) +gen_partprune_steps(RelOptInfo *rel, List *clauses, bool forplanner, + bool *contradictory) { GeneratePruningStepsContext context; context.next_step_id = 0; context.steps = NIL; + context.forplanner = forplanner; /* The clauses list may be modified below, so better make a copy. */ clauses = list_copy(clauses); @@ -574,9 +586,11 @@ gen_partprune_steps(RelOptInfo *rel, List *clauses, bool *contradictory) /* * prune_append_rel_partitions - * Returns indexes into rel->part_rels of the minimum set of child - * partitions which must be scanned to satisfy rel's baserestrictinfo - * quals. + * Process rel's baserestrictinfo and make use of quals which can be + * evaluated during query planning in order to determine the minimum set + * of partitions which must be scanned to satisfy these quals. Returns + * the matching partitions in the form of a Bitmapset containing the + * indexes into rel's part_rels array. * * Callers must ensure that 'rel' is a partitioned table. */ @@ -603,9 +617,12 @@ prune_append_rel_partitions(RelOptInfo *rel) /* * Process clauses. If the clauses are found to be contradictory, we can - * return the empty set. + * return the empty set. Pass 'forplanner' as true to indicate to the + * pruning code that we only want pruning steps that can be evaluated + * during planning. */ - pruning_steps = gen_partprune_steps(rel, clauses, &contradictory); + pruning_steps = gen_partprune_steps(rel, clauses, true, + &contradictory); if (contradictory) return NULL; @@ -1646,18 +1663,48 @@ match_clause_to_partition_key(RelOptInfo *rel, /* * Matched with this key. Now check various properties of the clause - * to see if it's sane to use it for pruning. In most of these cases, - * we can return UNSUPPORTED because the same failure would occur no - * matter which partkey it's matched to. + * to see if it's sane to use it for pruning. This sometimes depends + * on if we're generating pruning steps for evaluation in the planner + * or in the executor. The planner is unable to evaluate any stable + * functions, for example. In most of these cases, we can return + * UNSUPPORTED because the same failure would occur no matter which + * partkey it's matched to. */ - /* - * We can't prune using an expression with Vars. (Report failure as - * UNSUPPORTED, not NOMATCH: as in the no-commutator case above, we - * now know there are Vars on both sides, so it's no good.) - */ - if (contain_var_clause((Node *) expr)) - return PARTCLAUSE_UNSUPPORTED; + if (context->forplanner) + { + /* + * When pruning in the planner, we only support pruning using + * constants. Immutable functions will have been folded to consts + * already so we could be dealing with a Var or an unsupported + * function call, to which we must reject. + */ + if (!IsA(expr, Const)) + return PARTCLAUSE_UNSUPPORTED; + + /* + * We must reject comparing to consts if the comparison function + * itself is not immutable. (This is the case for most of the + * built-in timestamptz operators.) + */ + if (op_volatile(opno) != PROVOLATILE_IMMUTABLE) + return PARTCLAUSE_UNSUPPORTED; + } + else + { + /* + * Otherwise, non-consts are supported, but we can't prune using + * an expression with Vars. (Report failure as UNSUPPORTED, not + * NOMATCH: as in the no-commutator case above, we now know there + * are Vars on both sides, so it's no good.) + */ + if (contain_var_clause((Node *) expr)) + return PARTCLAUSE_UNSUPPORTED; + + /* And we must reject anything containing a volatile function. */ + if (contain_volatile_functions((Node *) expr)) + return PARTCLAUSE_UNSUPPORTED; + } /* * Only allow strict operators. This will guarantee nulls are @@ -1666,10 +1713,6 @@ match_clause_to_partition_key(RelOptInfo *rel, if (!op_strict(opno)) return PARTCLAUSE_UNSUPPORTED; - /* We can't use any volatile expressions to prune partitions. */ - if (contain_volatile_functions((Node *) expr)) - return PARTCLAUSE_UNSUPPORTED; - /* * See if the operator is relevant to the partitioning opfamily. * @@ -2961,15 +3004,18 @@ analyze_partkey_exprs(PartitionedRelPruneInfo *pinfo, List *steps, { PartitionPruneStepOp *step = (PartitionPruneStepOp *) lfirst(lc); ListCell *lc2; + ListCell *lc3; int keyno; if (!IsA(step, PartitionPruneStepOp)) continue; keyno = 0; - foreach(lc2, step->exprs) + forboth(lc2, step->exprs, lc3, step->cmpfns) { Expr *expr = lfirst(lc2); + Oid fnoid = lfirst_oid(lc3); + if (!IsA(expr, Const)) { @@ -2992,6 +3038,18 @@ analyze_partkey_exprs(PartitionedRelPruneInfo *pinfo, List *steps, doruntimeprune = true; } + + /* + * Pruning done during planning won't have pruned using quals with + * a non-immutable comparison functions, so we'll switch on + * run-time pruning for these. + */ + else if (func_volatile(fnoid) != PROVOLATILE_IMMUTABLE) + { + /* No need to check for exec params inside a const */ + doruntimeprune = true; + pinfo->do_initial_prune = true; + } keyno++; } } diff --git a/src/test/regress/expected/partition_prune.out b/src/test/regress/expected/partition_prune.out index bd64bed8fc..b30797434f 100644 --- a/src/test/regress/expected/partition_prune.out +++ b/src/test/regress/expected/partition_prune.out @@ -3036,6 +3036,24 @@ select * from listp where a = (select null::int); (7 rows) drop table listp; +-- +-- check that stable query clauses are only used in run-time pruning +-- +create table stable_qual_pruning (a timestamp) partition by range (a); +create table stable_qual_pruning1 partition of stable_qual_pruning for values from ('2019-01-01') to ('2019-02-01'); +create table stable_qual_pruning2 partition of stable_qual_pruning for values from ('2019-02-01') to ('2019-03-01'); +-- timestamp < timestamptz comparison is only stable, not immutable +explain (analyze, costs off, summary off, timing off) +select * from stable_qual_pruning where a < '2019-02-01'::timestamptz; + QUERY PLAN +-------------------------------------------------------------------------------- + Append (actual rows=0 loops=1) + Subplans Removed: 1 + -> Seq Scan on stable_qual_pruning1 (actual rows=0 loops=1) + Filter: (a < 'Fri Feb 01 00:00:00 2019 PST'::timestamp with time zone) +(4 rows) + +drop table stable_qual_pruning; -- Ensure runtime pruning works with initplans params with boolean types create table boolvalues (value bool not null); insert into boolvalues values('t'),('f'); diff --git a/src/test/regress/sql/partition_prune.sql b/src/test/regress/sql/partition_prune.sql index 246c6274af..9e10819be0 100644 --- a/src/test/regress/sql/partition_prune.sql +++ b/src/test/regress/sql/partition_prune.sql @@ -754,6 +754,18 @@ select * from listp where a = (select null::int); drop table listp; +-- +-- check that stable query clauses are only used in run-time pruning +-- +create table stable_qual_pruning (a timestamp) partition by range (a); +create table stable_qual_pruning1 partition of stable_qual_pruning for values from ('2019-01-01') to ('2019-02-01'); +create table stable_qual_pruning2 partition of stable_qual_pruning for values from ('2019-02-01') to ('2019-03-01'); +-- timestamp < timestamptz comparison is only stable, not immutable +explain (analyze, costs off, summary off, timing off) +select * from stable_qual_pruning where a < '2019-02-01'::timestamptz; + +drop table stable_qual_pruning; + -- Ensure runtime pruning works with initplans params with boolean types create table boolvalues (value bool not null); insert into boolvalues values('t'),('f');
pg11_dont_prune_with_nonimmutable_opfuncs_during_planning_v2.patch (text/plain, 9.8K) download diff --git a/src/backend/partitioning/partprune.c b/src/backend/partitioning/partprune.c index 354eb0d4e6..88ba3d6295 100644 --- a/src/backend/partitioning/partprune.c +++ b/src/backend/partitioning/partprune.c @@ -39,6 +39,7 @@ #include "access/nbtree.h" #include "catalog/pg_operator.h" #include "catalog/pg_opfamily.h" +#include "catalog/pg_proc.h" #include "catalog/pg_type.h" #include "executor/executor.h" #include "miscadmin.h" @@ -96,6 +97,8 @@ typedef struct GeneratePruningStepsContext { int next_step_id; List *steps; + bool forplanner; /* true when generating steps to be used + * during query planning */ } GeneratePruningStepsContext; /* The result of performing one PartitionPruneStep */ @@ -113,7 +116,7 @@ typedef struct PruneStepResult static List *gen_partprune_steps(RelOptInfo *rel, List *clauses, - bool *contradictory); + bool forplanner, bool *contradictory); static List *gen_partprune_steps_internal(GeneratePruningStepsContext *context, RelOptInfo *rel, List *clauses, bool *contradictory); @@ -285,7 +288,13 @@ make_partition_pruneinfo(PlannerInfo *root, List *partitioned_rels, targetpart->relids); } - pruning_steps = gen_partprune_steps(subpart, partprunequal, + /* + * Convert pruning qual to pruning steps. Since these steps will be + * executed during execution, we can pass 'forplanner' as false to + * allow steps to be generated that are unsafe for evaluation during + * planning, e.g. evaluation of stable functions. + */ + pruning_steps = gen_partprune_steps(subpart, partprunequal, false, &contradictory); if (contradictory) @@ -354,18 +363,22 @@ make_partition_pruneinfo(PlannerInfo *root, List *partitioned_rels, /* * gen_partprune_steps * Process 'clauses' (a rel's baserestrictinfo list of clauses) and return - * a list of "partition pruning steps" + * a list of "partition pruning steps". + * + * 'forplanner' must be true when being called from the query planner. * * If the clauses in the input list are contradictory or there is a * pseudo-constant "false", *contradictory is set to true upon return. */ static List * -gen_partprune_steps(RelOptInfo *rel, List *clauses, bool *contradictory) +gen_partprune_steps(RelOptInfo *rel, List *clauses, bool forplanner, + bool *contradictory) { GeneratePruningStepsContext context; context.next_step_id = 0; context.steps = NIL; + context.forplanner = forplanner; /* The clauses list may be modified below, so better make a copy. */ clauses = list_copy(clauses); @@ -405,8 +418,10 @@ gen_partprune_steps(RelOptInfo *rel, List *clauses, bool *contradictory) /* * prune_append_rel_partitions - * Returns RT indexes of the minimum set of child partitions which must - * be scanned to satisfy rel's baserestrictinfo quals. + * Process rel's baserestrictinfo and make use of quals which can be + * evaluated during query planning in order to determine the minimum set + * of partitions which must be scanned to satisfy these quals. Returns + * the Relids of the matching partitions. * * Callers must ensure that 'rel' is a partitioned table. */ @@ -430,9 +445,12 @@ prune_append_rel_partitions(RelOptInfo *rel) /* * Process clauses. If the clauses are found to be contradictory, we can - * return the empty set. + * return the empty set. Pass 'forplanner' as true to indicate to the + * pruning code that we only want pruning steps that can be evaluated + * during planning. */ - pruning_steps = gen_partprune_steps(rel, clauses, &contradictory); + pruning_steps = gen_partprune_steps(rel, clauses, true, + &contradictory); if (contradictory) return NULL; @@ -1479,18 +1497,48 @@ match_clause_to_partition_key(RelOptInfo *rel, /* * Matched with this key. Now check various properties of the clause - * to see if it's sane to use it for pruning. In most of these cases, - * we can return UNSUPPORTED because the same failure would occur no - * matter which partkey it's matched to. + * to see if it's sane to use it for pruning. This sometimes depends + * on if we're generating pruning steps for evaluation in the planner + * or in the executor. The planner is unable to evaluate any stable + * functions, for example. In most of these cases, we can return + * UNSUPPORTED because the same failure would occur no matter which + * partkey it's matched to. */ - /* - * We can't prune using an expression with Vars. (Report failure as - * UNSUPPORTED, not NOMATCH: as in the no-commutator case above, we - * now know there are Vars on both sides, so it's no good.) - */ - if (contain_var_clause((Node *) expr)) - return PARTCLAUSE_UNSUPPORTED; + if (context->forplanner) + { + /* + * When pruning in the planner, we only support pruning using + * constants. Immutable functions will have been folded to consts + * already so we could be dealing with a Var or an unsupported + * function call, to which we must reject. + */ + if (!IsA(expr, Const)) + return PARTCLAUSE_UNSUPPORTED; + + /* + * We must reject comparing to consts if the comparison function + * itself is not immutable. (This is the case for most of the + * built-in timestamptz operators.) + */ + if (op_volatile(opno) != PROVOLATILE_IMMUTABLE) + return PARTCLAUSE_UNSUPPORTED; + } + else + { + /* + * Otherwise, non-consts are supported, but we can't prune using + * an expression with Vars. (Report failure as UNSUPPORTED, not + * NOMATCH: as in the no-commutator case above, we now know there + * are Vars on both sides, so it's no good.) + */ + if (contain_var_clause((Node *) expr)) + return PARTCLAUSE_UNSUPPORTED; + + /* And we must reject anything containing a volatile function. */ + if (contain_volatile_functions((Node *) expr)) + return PARTCLAUSE_UNSUPPORTED; + } /* * Only allow strict operators. This will guarantee nulls are @@ -1499,10 +1547,6 @@ match_clause_to_partition_key(RelOptInfo *rel, if (!op_strict(opno)) return PARTCLAUSE_UNSUPPORTED; - /* We can't use any volatile expressions to prune partitions. */ - if (contain_volatile_functions((Node *) expr)) - return PARTCLAUSE_UNSUPPORTED; - /* * See if the operator is relevant to the partitioning opfamily. * @@ -2781,15 +2825,18 @@ analyze_partkey_exprs(PartitionPruneInfo *pinfo, List *steps, int partnatts) { PartitionPruneStepOp *step = (PartitionPruneStepOp *) lfirst(lc); ListCell *lc2; + ListCell *lc3; int keyno; if (!IsA(step, PartitionPruneStepOp)) continue; keyno = 0; - foreach(lc2, step->exprs) + forboth(lc2, step->exprs, lc3, step->cmpfns) { Expr *expr = lfirst(lc2); + Oid fnoid = lfirst_oid(lc3); + if (!IsA(expr, Const)) { @@ -2812,6 +2859,18 @@ analyze_partkey_exprs(PartitionPruneInfo *pinfo, List *steps, int partnatts) doruntimeprune = true; } + + /* + * Pruning done during planning won't have pruned using quals with + * a non-immutable comparison functions, so we'll switch on + * run-time pruning for these. + */ + else if (func_volatile(fnoid) != PROVOLATILE_IMMUTABLE) + { + /* No need to check for exec params inside a const */ + doruntimeprune = true; + pinfo->do_initial_prune = true; + } keyno++; } } diff --git a/src/test/regress/expected/partition_prune.out b/src/test/regress/expected/partition_prune.out index 022b7c55c7..97c2504fff 100644 --- a/src/test/regress/expected/partition_prune.out +++ b/src/test/regress/expected/partition_prune.out @@ -2787,6 +2787,24 @@ select * from listp where a = (select null::int); (7 rows) drop table listp; +-- +-- check that stable query clauses are only used in run-time pruning +-- +create table stable_qual_pruning (a timestamp) partition by range (a); +create table stable_qual_pruning1 partition of stable_qual_pruning for values from ('2019-01-01') to ('2019-02-01'); +create table stable_qual_pruning2 partition of stable_qual_pruning for values from ('2019-02-01') to ('2019-03-01'); +-- timestamp < timestamptz comparison is only stable, not immutable +explain (analyze, costs off, summary off, timing off) +select * from stable_qual_pruning where a < '2019-02-01'::timestamptz; + QUERY PLAN +-------------------------------------------------------------------------------- + Append (actual rows=0 loops=1) + Subplans Removed: 1 + -> Seq Scan on stable_qual_pruning1 (actual rows=0 loops=1) + Filter: (a < 'Fri Feb 01 00:00:00 2019 PST'::timestamp with time zone) +(4 rows) + +drop table stable_qual_pruning; -- Ensure runtime pruning works with initplans params with boolean types create table boolvalues (value bool not null); insert into boolvalues values('t'),('f'); diff --git a/src/test/regress/sql/partition_prune.sql b/src/test/regress/sql/partition_prune.sql index 2357f02cde..b03916d673 100644 --- a/src/test/regress/sql/partition_prune.sql +++ b/src/test/regress/sql/partition_prune.sql @@ -698,6 +698,18 @@ select * from listp where a = (select null::int); drop table listp; +-- +-- check that stable query clauses are only used in run-time pruning +-- +create table stable_qual_pruning (a timestamp) partition by range (a); +create table stable_qual_pruning1 partition of stable_qual_pruning for values from ('2019-01-01') to ('2019-02-01'); +create table stable_qual_pruning2 partition of stable_qual_pruning for values from ('2019-02-01') to ('2019-03-01'); +-- timestamp < timestamptz comparison is only stable, not immutable +explain (analyze, costs off, summary off, timing off) +select * from stable_qual_pruning where a < '2019-02-01'::timestamptz; + +drop table stable_qual_pruning; + -- Ensure runtime pruning works with initplans params with boolean types create table boolvalues (value bool not null); insert into boolvalues values('t'),('f');

view thread (41+ messages)  latest in thread

Message-ID: <588f56cb-aaed-14b0-8a21-13486bd1c706@lab.ntt.co.jp>
Permalink:  ../588f56cb-aaed-14b0-8a21-13486bd1c706@lab.ntt.co.jp/
Also on:    postgresql.org/message-id/588f56cb-aaed-14b0-8a21-13486bd1c706@lab.ntt.co.jp

 ·  · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-bugs@postgresql.org
  Cc: Langote_Amit_f8@lab.ntt.co.jp, david.rowley@2ndquadrant.com, tgl@sss.pgh.pa.us, horiguchi.kyotaro@lab.ntt.co.jp
  Subject: Re: inconsistent results querying table partitioned by date
  In-Reply-To: <588f56cb-aaed-14b0-8a21-13486bd1c706@lab.ntt.co.jp>
  References: <FAD28A83-AC73-489E-A058-2681FA31D648@tvsquared.com> <24525.1557444159@sss.pgh.pa.us> <49cd5235-cbe6-e686-8014-85c1e45efe56@lab.ntt.co.jp> <20190510.153337.236910404.horiguchi.kyotaro@lab.ntt.co.jp> <90aeaf38-270a-7e45-6b7d-af2e3d1e3719@lab.ntt.co.jp> <20307.1557522309@sss.pgh.pa.us> <a0bca4f7-b493-4d0a-8080-8dad3748c5ae@lab.ntt.co.jp> <CAKJS1f92Uq+SV+WKKa+B5Fd9PcrwhYFsvxUudm_9F8egi4paXQ@mail.gmail.com> <d7878f1f-f7c5-4f23-127e-ced79a64ddf1@lab.ntt.co.jp> <CAKJS1f-xHgnr0QVfGtt9BU38kB8a5fp4Y=CYbChV8xSqw6pZ9w@mail.gmail.com> <e903adfc-c7a5-58f9-6b7f-16ab6f48be5c@lab.ntt.co.jp> <28453.1557867500@sss.pgh.pa.us> <CAKJS1f82n-WNsu6G5WNXGFV4MsnosydiouRvTNnZYmQz0tciuQ@mail.gmail.com> <588f56cb-aaed-14b0-8a21-13486bd1c706@lab.ntt.co.jp>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox