1 /*-------------------------------------------------------------------------
4 * Routines to attempt to prove logical implications between predicate
7 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 * src/backend/optimizer/util/predtest.c
14 *-------------------------------------------------------------------------
18 #include "catalog/pg_proc.h"
19 #include "catalog/pg_type.h"
20 #include "executor/executor.h"
21 #include "miscadmin.h"
22 #include "nodes/makefuncs.h"
23 #include "nodes/nodeFuncs.h"
24 #include "nodes/pathnodes.h"
25 #include "optimizer/optimizer.h"
26 #include "utils/array.h"
27 #include "utils/inval.h"
28 #include "utils/lsyscache.h"
29 #include "utils/syscache.h"
33 * Proof attempts involving large arrays in ScalarArrayOpExpr nodes are
34 * likely to require O(N^2) time, and more often than not fail anyway.
35 * So we set an arbitrary limit on the number of array elements that
36 * we will allow to be treated as an AND or OR clause.
37 * XXX is it worth exposing this as a GUC knob?
39 #define MAX_SAOP_ARRAY_SIZE 100
42 * To avoid redundant coding in predicate_implied_by_recurse and
43 * predicate_refuted_by_recurse, we need to abstract out the notion of
44 * iterating over the components of an expression that is logically an AND
45 * or OR structure. There are multiple sorts of expression nodes that can
46 * be treated as ANDs or ORs, and we don't want to code each one separately.
47 * Hence, these types and support routines.
51 CLASS_ATOM, /* expression that's not AND or OR */
52 CLASS_AND, /* expression with AND semantics */
53 CLASS_OR /* expression with OR semantics */
56 typedef struct PredIterInfoData *PredIterInfo;
58 typedef struct PredIterInfoData
60 /* node-type-specific iteration state */
63 /* initialize to do the iteration */
64 void (*startup_fn) (Node *clause, PredIterInfo info);
65 /* next-component iteration function */
66 Node *(*next_fn) (PredIterInfo info);
67 /* release resources when done with iteration */
68 void (*cleanup_fn) (PredIterInfo info);
71 #define iterate_begin(item, clause, info) \
74 (info).startup_fn((clause), &(info)); \
75 while ((item = (info).next_fn(&(info))) != NULL)
77 #define iterate_end(info) \
78 (info).cleanup_fn(&(info)); \
82 static bool predicate_implied_by_recurse(Node *clause, Node *predicate,
84 static bool predicate_refuted_by_recurse(Node *clause, Node *predicate,
86 static PredClass predicate_classify(Node *clause, PredIterInfo info);
87 static void list_startup_fn(Node *clause, PredIterInfo info);
88 static Node *list_next_fn(PredIterInfo info);
89 static void list_cleanup_fn(PredIterInfo info);
90 static void boolexpr_startup_fn(Node *clause, PredIterInfo info);
91 static void arrayconst_startup_fn(Node *clause, PredIterInfo info);
92 static Node *arrayconst_next_fn(PredIterInfo info);
93 static void arrayconst_cleanup_fn(PredIterInfo info);
94 static void arrayexpr_startup_fn(Node *clause, PredIterInfo info);
95 static Node *arrayexpr_next_fn(PredIterInfo info);
96 static void arrayexpr_cleanup_fn(PredIterInfo info);
97 static bool predicate_implied_by_simple_clause(Expr *predicate, Node *clause,
99 static bool predicate_refuted_by_simple_clause(Expr *predicate, Node *clause,
101 static Node *extract_not_arg(Node *clause);
102 static Node *extract_strong_not_arg(Node *clause);
103 static bool clause_is_strict_for(Node *clause, Node *subexpr, bool allow_false);
104 static bool operator_predicate_proof(Expr *predicate, Node *clause,
105 bool refute_it, bool weak);
106 static bool operator_same_subexprs_proof(Oid pred_op, Oid clause_op,
108 static bool operator_same_subexprs_lookup(Oid pred_op, Oid clause_op,
110 static Oid get_btree_test_op(Oid pred_op, Oid clause_op, bool refute_it);
111 static void InvalidateOprProofCacheCallBack(Datum arg, int cacheid, uint32 hashvalue);
115 * predicate_implied_by
116 * Recursively checks whether the clauses in clause_list imply that the
117 * given predicate is true.
119 * We support two definitions of implication:
121 * "Strong" implication: A implies B means that truth of A implies truth of B.
122 * We use this to prove that a row satisfying one WHERE clause or index
123 * predicate must satisfy another one.
125 * "Weak" implication: A implies B means that non-falsity of A implies
126 * non-falsity of B ("non-false" means "either true or NULL"). We use this to
127 * prove that a row satisfying one CHECK constraint must satisfy another one.
129 * Strong implication can also be used to prove that a WHERE clause implies a
130 * CHECK constraint, although it will fail to prove a few cases where we could
131 * safely conclude that the implication holds. There's no support for proving
132 * the converse case, since only a few kinds of CHECK constraint would allow
135 * The top-level List structure of each list corresponds to an AND list.
136 * We assume that eval_const_expressions() has been applied and so there
137 * are no un-flattened ANDs or ORs (e.g., no AND immediately within an AND,
138 * including AND just below the top-level List structure).
139 * If this is not true we might fail to prove an implication that is
140 * valid, but no worse consequences will ensue.
142 * We assume the predicate has already been checked to contain only
143 * immutable functions and operators. (In many current uses this is known
144 * true because the predicate is part of an index predicate that has passed
145 * CheckPredicate(); otherwise, the caller must check it.) We dare not make
146 * deductions based on non-immutable functions, because they might change
147 * answers between the time we make the plan and the time we execute the plan.
148 * Immutability of functions in the clause_list is checked here, if necessary.
151 predicate_implied_by(List *predicate_list, List *clause_list,
157 if (predicate_list == NIL)
158 return true; /* no predicate: implication is vacuous */
159 if (clause_list == NIL)
160 return false; /* no restriction: implication must fail */
163 * If either input is a single-element list, replace it with its lone
164 * member; this avoids one useless level of AND-recursion. We only need
165 * to worry about this at top level, since eval_const_expressions should
166 * have gotten rid of any trivial ANDs or ORs below that.
168 if (list_length(predicate_list) == 1)
169 p = (Node *) linitial(predicate_list);
171 p = (Node *) predicate_list;
172 if (list_length(clause_list) == 1)
173 c = (Node *) linitial(clause_list);
175 c = (Node *) clause_list;
177 /* And away we go ... */
178 return predicate_implied_by_recurse(c, p, weak);
182 * predicate_refuted_by
183 * Recursively checks whether the clauses in clause_list refute the given
184 * predicate (that is, prove it false).
186 * This is NOT the same as !(predicate_implied_by), though it is similar
187 * in the technique and structure of the code.
189 * We support two definitions of refutation:
191 * "Strong" refutation: A refutes B means truth of A implies falsity of B.
192 * We use this to disprove a CHECK constraint given a WHERE clause, i.e.,
193 * prove that any row satisfying the WHERE clause would violate the CHECK
194 * constraint. (Observe we must prove B yields false, not just not-true.)
196 * "Weak" refutation: A refutes B means truth of A implies non-truth of B
197 * (i.e., B must yield false or NULL). We use this to detect mutually
198 * contradictory WHERE clauses.
200 * Weak refutation can be proven in some cases where strong refutation doesn't
201 * hold, so it's useful to use it when possible. We don't currently have
202 * support for disproving one CHECK constraint based on another one, nor for
203 * disproving WHERE based on CHECK. (As with implication, the last case
204 * doesn't seem very practical. CHECK-vs-CHECK might be useful, but isn't
205 * currently needed anywhere.)
207 * The top-level List structure of each list corresponds to an AND list.
208 * We assume that eval_const_expressions() has been applied and so there
209 * are no un-flattened ANDs or ORs (e.g., no AND immediately within an AND,
210 * including AND just below the top-level List structure).
211 * If this is not true we might fail to prove an implication that is
212 * valid, but no worse consequences will ensue.
214 * We assume the predicate has already been checked to contain only
215 * immutable functions and operators. We dare not make deductions based on
216 * non-immutable functions, because they might change answers between the
217 * time we make the plan and the time we execute the plan.
218 * Immutability of functions in the clause_list is checked here, if necessary.
221 predicate_refuted_by(List *predicate_list, List *clause_list,
227 if (predicate_list == NIL)
228 return false; /* no predicate: no refutation is possible */
229 if (clause_list == NIL)
230 return false; /* no restriction: refutation must fail */
233 * If either input is a single-element list, replace it with its lone
234 * member; this avoids one useless level of AND-recursion. We only need
235 * to worry about this at top level, since eval_const_expressions should
236 * have gotten rid of any trivial ANDs or ORs below that.
238 if (list_length(predicate_list) == 1)
239 p = (Node *) linitial(predicate_list);
241 p = (Node *) predicate_list;
242 if (list_length(clause_list) == 1)
243 c = (Node *) linitial(clause_list);
245 c = (Node *) clause_list;
247 /* And away we go ... */
248 return predicate_refuted_by_recurse(c, p, weak);
252 * predicate_implied_by_recurse
253 * Does the predicate implication test for non-NULL restriction and
256 * The logic followed here is ("=>" means "implies"):
257 * atom A => atom B iff: predicate_implied_by_simple_clause says so
258 * atom A => AND-expr B iff: A => each of B's components
259 * atom A => OR-expr B iff: A => any of B's components
260 * AND-expr A => atom B iff: any of A's components => B
261 * AND-expr A => AND-expr B iff: A => each of B's components
262 * AND-expr A => OR-expr B iff: A => any of B's components,
263 * *or* any of A's components => B
264 * OR-expr A => atom B iff: each of A's components => B
265 * OR-expr A => AND-expr B iff: A => each of B's components
266 * OR-expr A => OR-expr B iff: each of A's components => any of B's
268 * An "atom" is anything other than an AND or OR node. Notice that we don't
269 * have any special logic to handle NOT nodes; these should have been pushed
270 * down or eliminated where feasible during eval_const_expressions().
272 * All of these rules apply equally to strong or weak implication.
274 * We can't recursively expand either side first, but have to interleave
275 * the expansions per the above rules, to be sure we handle all of these
277 * (x OR y) => (x OR y OR z)
278 * (x AND y AND z) => (x AND y)
279 * (x AND y) => ((x AND y) OR z)
280 * ((x OR y) AND z) => (x OR y)
281 * This is still not an exhaustive test, but it handles most normal cases
282 * under the assumption that both inputs have been AND/OR flattened.
284 * We have to be prepared to handle RestrictInfo nodes in the restrictinfo
285 * tree, though not in the predicate tree.
289 predicate_implied_by_recurse(Node *clause, Node *predicate,
292 PredIterInfoData clause_info;
293 PredIterInfoData pred_info;
297 /* skip through RestrictInfo */
298 Assert(clause != NULL);
299 if (IsA(clause, RestrictInfo))
300 clause = (Node *) ((RestrictInfo *) clause)->clause;
302 pclass = predicate_classify(predicate, &pred_info);
304 switch (predicate_classify(clause, &clause_info))
312 * AND-clause => AND-clause if A implies each of B's items
315 iterate_begin(pitem, predicate, pred_info)
317 if (!predicate_implied_by_recurse(clause, pitem,
324 iterate_end(pred_info);
330 * AND-clause => OR-clause if A implies any of B's items
332 * Needed to handle (x AND y) => ((x AND y) OR z)
335 iterate_begin(pitem, predicate, pred_info)
337 if (predicate_implied_by_recurse(clause, pitem,
344 iterate_end(pred_info);
349 * Also check if any of A's items implies B
351 * Needed to handle ((x OR y) AND z) => (x OR y)
353 iterate_begin(citem, clause, clause_info)
355 if (predicate_implied_by_recurse(citem, predicate,
362 iterate_end(clause_info);
368 * AND-clause => atom if any of A's items implies B
371 iterate_begin(citem, clause, clause_info)
373 if (predicate_implied_by_recurse(citem, predicate,
380 iterate_end(clause_info);
391 * OR-clause => OR-clause if each of A's items implies any
392 * of B's items. Messy but can't do it any more simply.
395 iterate_begin(citem, clause, clause_info)
397 bool presult = false;
399 iterate_begin(pitem, predicate, pred_info)
401 if (predicate_implied_by_recurse(citem, pitem,
408 iterate_end(pred_info);
411 result = false; /* doesn't imply any of B's */
415 iterate_end(clause_info);
422 * OR-clause => AND-clause if each of A's items implies B
424 * OR-clause => atom if each of A's items implies B
427 iterate_begin(citem, clause, clause_info)
429 if (!predicate_implied_by_recurse(citem, predicate,
436 iterate_end(clause_info);
447 * atom => AND-clause if A implies each of B's items
450 iterate_begin(pitem, predicate, pred_info)
452 if (!predicate_implied_by_recurse(clause, pitem,
459 iterate_end(pred_info);
465 * atom => OR-clause if A implies any of B's items
468 iterate_begin(pitem, predicate, pred_info)
470 if (predicate_implied_by_recurse(clause, pitem,
477 iterate_end(pred_info);
483 * atom => atom is the base case
486 predicate_implied_by_simple_clause((Expr *) predicate,
494 elog(ERROR, "predicate_classify returned a bogus value");
499 * predicate_refuted_by_recurse
500 * Does the predicate refutation test for non-NULL restriction and
503 * The logic followed here is ("R=>" means "refutes"):
504 * atom A R=> atom B iff: predicate_refuted_by_simple_clause says so
505 * atom A R=> AND-expr B iff: A R=> any of B's components
506 * atom A R=> OR-expr B iff: A R=> each of B's components
507 * AND-expr A R=> atom B iff: any of A's components R=> B
508 * AND-expr A R=> AND-expr B iff: A R=> any of B's components,
509 * *or* any of A's components R=> B
510 * AND-expr A R=> OR-expr B iff: A R=> each of B's components
511 * OR-expr A R=> atom B iff: each of A's components R=> B
512 * OR-expr A R=> AND-expr B iff: each of A's components R=> any of B's
513 * OR-expr A R=> OR-expr B iff: A R=> each of B's components
515 * All of the above rules apply equally to strong or weak refutation.
517 * In addition, if the predicate is a NOT-clause then we can use
518 * A R=> NOT B if: A => B
519 * This works for several different SQL constructs that assert the non-truth
520 * of their argument, ie NOT, IS FALSE, IS NOT TRUE, IS UNKNOWN, although some
521 * of them require that we prove strong implication. Likewise, we can use
522 * NOT A R=> B if: B => A
523 * but here we must be careful about strong vs. weak refutation and make
524 * the appropriate type of implication proof (weak or strong respectively).
526 * Other comments are as for predicate_implied_by_recurse().
530 predicate_refuted_by_recurse(Node *clause, Node *predicate,
533 PredIterInfoData clause_info;
534 PredIterInfoData pred_info;
539 /* skip through RestrictInfo */
540 Assert(clause != NULL);
541 if (IsA(clause, RestrictInfo))
542 clause = (Node *) ((RestrictInfo *) clause)->clause;
544 pclass = predicate_classify(predicate, &pred_info);
546 switch (predicate_classify(clause, &clause_info))
554 * AND-clause R=> AND-clause if A refutes any of B's items
556 * Needed to handle (x AND y) R=> ((!x OR !y) AND z)
559 iterate_begin(pitem, predicate, pred_info)
561 if (predicate_refuted_by_recurse(clause, pitem,
568 iterate_end(pred_info);
573 * Also check if any of A's items refutes B
575 * Needed to handle ((x OR y) AND z) R=> (!x AND !y)
577 iterate_begin(citem, clause, clause_info)
579 if (predicate_refuted_by_recurse(citem, predicate,
586 iterate_end(clause_info);
592 * AND-clause R=> OR-clause if A refutes each of B's items
595 iterate_begin(pitem, predicate, pred_info)
597 if (!predicate_refuted_by_recurse(clause, pitem,
604 iterate_end(pred_info);
610 * If B is a NOT-type clause, A R=> B if A => B's arg
612 * Since, for either type of refutation, we are starting
613 * with the premise that A is true, we can use a strong
614 * implication test in all cases. That proves B's arg is
615 * true, which is more than we need for weak refutation if
616 * B is a simple NOT, but it allows not worrying about
617 * exactly which kind of negation clause we have.
619 not_arg = extract_not_arg(predicate);
621 predicate_implied_by_recurse(clause, not_arg,
626 * AND-clause R=> atom if any of A's items refutes B
629 iterate_begin(citem, clause, clause_info)
631 if (predicate_refuted_by_recurse(citem, predicate,
638 iterate_end(clause_info);
649 * OR-clause R=> OR-clause if A refutes each of B's items
652 iterate_begin(pitem, predicate, pred_info)
654 if (!predicate_refuted_by_recurse(clause, pitem,
661 iterate_end(pred_info);
667 * OR-clause R=> AND-clause if each of A's items refutes
671 iterate_begin(citem, clause, clause_info)
673 bool presult = false;
675 iterate_begin(pitem, predicate, pred_info)
677 if (predicate_refuted_by_recurse(citem, pitem,
684 iterate_end(pred_info);
687 result = false; /* citem refutes nothing */
691 iterate_end(clause_info);
697 * If B is a NOT-type clause, A R=> B if A => B's arg
699 * Same logic as for the AND-clause case above.
701 not_arg = extract_not_arg(predicate);
703 predicate_implied_by_recurse(clause, not_arg,
708 * OR-clause R=> atom if each of A's items refutes B
711 iterate_begin(citem, clause, clause_info)
713 if (!predicate_refuted_by_recurse(citem, predicate,
720 iterate_end(clause_info);
728 * If A is a strong NOT-clause, A R=> B if B => A's arg
730 * Since A is strong, we may assume A's arg is false (not just
731 * not-true). If B weakly implies A's arg, then B can be neither
732 * true nor null, so that strong refutation is proven. If B
733 * strongly implies A's arg, then B cannot be true, so that weak
734 * refutation is proven.
736 not_arg = extract_strong_not_arg(clause);
738 predicate_implied_by_recurse(predicate, not_arg,
747 * atom R=> AND-clause if A refutes any of B's items
750 iterate_begin(pitem, predicate, pred_info)
752 if (predicate_refuted_by_recurse(clause, pitem,
759 iterate_end(pred_info);
765 * atom R=> OR-clause if A refutes each of B's items
768 iterate_begin(pitem, predicate, pred_info)
770 if (!predicate_refuted_by_recurse(clause, pitem,
777 iterate_end(pred_info);
783 * If B is a NOT-type clause, A R=> B if A => B's arg
785 * Same logic as for the AND-clause case above.
787 not_arg = extract_not_arg(predicate);
789 predicate_implied_by_recurse(clause, not_arg,
794 * atom R=> atom is the base case
797 predicate_refuted_by_simple_clause((Expr *) predicate,
805 elog(ERROR, "predicate_classify returned a bogus value");
812 * Classify an expression node as AND-type, OR-type, or neither (an atom).
814 * If the expression is classified as AND- or OR-type, then *info is filled
815 * in with the functions needed to iterate over its components.
817 * This function also implements enforcement of MAX_SAOP_ARRAY_SIZE: if a
818 * ScalarArrayOpExpr's array has too many elements, we just classify it as an
819 * atom. (This will result in its being passed as-is to the simple_clause
820 * functions, many of which will fail to prove anything about it.) Note that we
821 * cannot just stop after considering MAX_SAOP_ARRAY_SIZE elements; in general
822 * that would result in wrong proofs, rather than failing to prove anything.
825 predicate_classify(Node *clause, PredIterInfo info)
827 /* Caller should not pass us NULL, nor a RestrictInfo clause */
828 Assert(clause != NULL);
829 Assert(!IsA(clause, RestrictInfo));
832 * If we see a List, assume it's an implicit-AND list; this is the correct
833 * semantics for lists of RestrictInfo nodes.
835 if (IsA(clause, List))
837 info->startup_fn = list_startup_fn;
838 info->next_fn = list_next_fn;
839 info->cleanup_fn = list_cleanup_fn;
843 /* Handle normal AND and OR boolean clauses */
844 if (is_andclause(clause))
846 info->startup_fn = boolexpr_startup_fn;
847 info->next_fn = list_next_fn;
848 info->cleanup_fn = list_cleanup_fn;
851 if (is_orclause(clause))
853 info->startup_fn = boolexpr_startup_fn;
854 info->next_fn = list_next_fn;
855 info->cleanup_fn = list_cleanup_fn;
859 /* Handle ScalarArrayOpExpr */
860 if (IsA(clause, ScalarArrayOpExpr))
862 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
863 Node *arraynode = (Node *) lsecond(saop->args);
866 * We can break this down into an AND or OR structure, but only if we
867 * know how to iterate through expressions for the array's elements.
868 * We can do that if the array operand is a non-null constant or a
871 if (arraynode && IsA(arraynode, Const) &&
872 !((Const *) arraynode)->constisnull)
877 arrayval = DatumGetArrayTypeP(((Const *) arraynode)->constvalue);
878 nelems = ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
879 if (nelems <= MAX_SAOP_ARRAY_SIZE)
881 info->startup_fn = arrayconst_startup_fn;
882 info->next_fn = arrayconst_next_fn;
883 info->cleanup_fn = arrayconst_cleanup_fn;
884 return saop->useOr ? CLASS_OR : CLASS_AND;
887 else if (arraynode && IsA(arraynode, ArrayExpr) &&
888 !((ArrayExpr *) arraynode)->multidims &&
889 list_length(((ArrayExpr *) arraynode)->elements) <= MAX_SAOP_ARRAY_SIZE)
891 info->startup_fn = arrayexpr_startup_fn;
892 info->next_fn = arrayexpr_next_fn;
893 info->cleanup_fn = arrayexpr_cleanup_fn;
894 return saop->useOr ? CLASS_OR : CLASS_AND;
898 /* None of the above, so it's an atom */
903 * PredIterInfo routines for iterating over regular Lists. The iteration
904 * state variable is the next ListCell to visit.
907 list_startup_fn(Node *clause, PredIterInfo info)
909 info->state_list = (List *) clause;
910 info->state = (void *) list_head(info->state_list);
914 list_next_fn(PredIterInfo info)
916 ListCell *l = (ListCell *) info->state;
922 info->state = (void *) lnext(info->state_list, l);
927 list_cleanup_fn(PredIterInfo info)
929 /* Nothing to clean up */
933 * BoolExpr needs its own startup function, but can use list_next_fn and
937 boolexpr_startup_fn(Node *clause, PredIterInfo info)
939 info->state_list = ((BoolExpr *) clause)->args;
940 info->state = (void *) list_head(info->state_list);
944 * PredIterInfo routines for iterating over a ScalarArrayOpExpr with a
945 * constant array operand.
955 } ArrayConstIterState;
958 arrayconst_startup_fn(Node *clause, PredIterInfo info)
960 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
961 ArrayConstIterState *state;
968 /* Create working state struct */
969 state = (ArrayConstIterState *) palloc(sizeof(ArrayConstIterState));
970 info->state = (void *) state;
972 /* Deconstruct the array literal */
973 arrayconst = (Const *) lsecond(saop->args);
974 arrayval = DatumGetArrayTypeP(arrayconst->constvalue);
975 get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
976 &elmlen, &elmbyval, &elmalign);
977 deconstruct_array(arrayval,
978 ARR_ELEMTYPE(arrayval),
979 elmlen, elmbyval, elmalign,
980 &state->elem_values, &state->elem_nulls,
983 /* Set up a dummy OpExpr to return as the per-item node */
984 state->opexpr.xpr.type = T_OpExpr;
985 state->opexpr.opno = saop->opno;
986 state->opexpr.opfuncid = saop->opfuncid;
987 state->opexpr.opresulttype = BOOLOID;
988 state->opexpr.opretset = false;
989 state->opexpr.opcollid = InvalidOid;
990 state->opexpr.inputcollid = saop->inputcollid;
991 state->opexpr.args = list_copy(saop->args);
993 /* Set up a dummy Const node to hold the per-element values */
994 state->constexpr.xpr.type = T_Const;
995 state->constexpr.consttype = ARR_ELEMTYPE(arrayval);
996 state->constexpr.consttypmod = -1;
997 state->constexpr.constcollid = arrayconst->constcollid;
998 state->constexpr.constlen = elmlen;
999 state->constexpr.constbyval = elmbyval;
1000 lsecond(state->opexpr.args) = &state->constexpr;
1002 /* Initialize iteration state */
1003 state->next_elem = 0;
1007 arrayconst_next_fn(PredIterInfo info)
1009 ArrayConstIterState *state = (ArrayConstIterState *) info->state;
1011 if (state->next_elem >= state->num_elems)
1013 state->constexpr.constvalue = state->elem_values[state->next_elem];
1014 state->constexpr.constisnull = state->elem_nulls[state->next_elem];
1016 return (Node *) &(state->opexpr);
1020 arrayconst_cleanup_fn(PredIterInfo info)
1022 ArrayConstIterState *state = (ArrayConstIterState *) info->state;
1024 pfree(state->elem_values);
1025 pfree(state->elem_nulls);
1026 list_free(state->opexpr.args);
1031 * PredIterInfo routines for iterating over a ScalarArrayOpExpr with a
1032 * one-dimensional ArrayExpr array operand.
1038 } ArrayExprIterState;
1041 arrayexpr_startup_fn(Node *clause, PredIterInfo info)
1043 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
1044 ArrayExprIterState *state;
1045 ArrayExpr *arrayexpr;
1047 /* Create working state struct */
1048 state = (ArrayExprIterState *) palloc(sizeof(ArrayExprIterState));
1049 info->state = (void *) state;
1051 /* Set up a dummy OpExpr to return as the per-item node */
1052 state->opexpr.xpr.type = T_OpExpr;
1053 state->opexpr.opno = saop->opno;
1054 state->opexpr.opfuncid = saop->opfuncid;
1055 state->opexpr.opresulttype = BOOLOID;
1056 state->opexpr.opretset = false;
1057 state->opexpr.opcollid = InvalidOid;
1058 state->opexpr.inputcollid = saop->inputcollid;
1059 state->opexpr.args = list_copy(saop->args);
1061 /* Initialize iteration variable to first member of ArrayExpr */
1062 arrayexpr = (ArrayExpr *) lsecond(saop->args);
1063 info->state_list = arrayexpr->elements;
1064 state->next = list_head(arrayexpr->elements);
1068 arrayexpr_next_fn(PredIterInfo info)
1070 ArrayExprIterState *state = (ArrayExprIterState *) info->state;
1072 if (state->next == NULL)
1074 lsecond(state->opexpr.args) = lfirst(state->next);
1075 state->next = lnext(info->state_list, state->next);
1076 return (Node *) &(state->opexpr);
1080 arrayexpr_cleanup_fn(PredIterInfo info)
1082 ArrayExprIterState *state = (ArrayExprIterState *) info->state;
1084 list_free(state->opexpr.args);
1090 * predicate_implied_by_simple_clause
1091 * Does the predicate implication test for a "simple clause" predicate
1092 * and a "simple clause" restriction.
1094 * We return true if able to prove the implication, false if not.
1096 * We have three strategies for determining whether one simple clause
1099 * A simple and general way is to see if they are equal(); this works for any
1100 * kind of expression, and for either implication definition. (Actually,
1101 * there is an implied assumption that the functions in the expression are
1102 * immutable --- but this was checked for the predicate by the caller.)
1104 * If the predicate is of the form "foo IS NOT NULL", and we are considering
1105 * strong implication, we can conclude that the predicate is implied if the
1106 * clause is strict for "foo", i.e., it must yield false or NULL when "foo"
1107 * is NULL. In that case truth of the clause ensures that "foo" isn't NULL.
1108 * (Again, this is a safe conclusion because "foo" must be immutable.)
1109 * This doesn't work for weak implication, though.
1111 * Finally, if both clauses are binary operator expressions, we may be able
1112 * to prove something using the system's knowledge about operators; those
1113 * proof rules are encapsulated in operator_predicate_proof().
1117 predicate_implied_by_simple_clause(Expr *predicate, Node *clause,
1120 /* Allow interrupting long proof attempts */
1121 CHECK_FOR_INTERRUPTS();
1123 /* First try the equal() test */
1124 if (equal((Node *) predicate, clause))
1127 /* Next try the IS NOT NULL case */
1129 predicate && IsA(predicate, NullTest))
1131 NullTest *ntest = (NullTest *) predicate;
1133 /* row IS NOT NULL does not act in the simple way we have in mind */
1134 if (ntest->nulltesttype == IS_NOT_NULL &&
1137 /* strictness of clause for foo implies foo IS NOT NULL */
1138 if (clause_is_strict_for(clause, (Node *) ntest->arg, true))
1141 return false; /* we can't succeed below... */
1144 /* Else try operator-related knowledge */
1145 return operator_predicate_proof(predicate, clause, false, weak);
1149 * predicate_refuted_by_simple_clause
1150 * Does the predicate refutation test for a "simple clause" predicate
1151 * and a "simple clause" restriction.
1153 * We return true if able to prove the refutation, false if not.
1155 * Unlike the implication case, checking for equal() clauses isn't helpful.
1156 * But relation_excluded_by_constraints() checks for self-contradictions in a
1157 * list of clauses, so that we may get here with predicate and clause being
1158 * actually pointer-equal, and that is worth eliminating quickly.
1160 * When the predicate is of the form "foo IS NULL", we can conclude that
1161 * the predicate is refuted if the clause is strict for "foo" (see notes for
1162 * implication case), or is "foo IS NOT NULL". That works for either strong
1163 * or weak refutation.
1165 * A clause "foo IS NULL" refutes a predicate "foo IS NOT NULL" in all cases.
1166 * If we are considering weak refutation, it also refutes a predicate that
1167 * is strict for "foo", since then the predicate must yield false or NULL
1168 * (and since "foo" appears in the predicate, it's known immutable).
1170 * (The main motivation for covering these IS [NOT] NULL cases is to support
1171 * using IS NULL/IS NOT NULL as partition-defining constraints.)
1173 * Finally, if both clauses are binary operator expressions, we may be able
1174 * to prove something using the system's knowledge about operators; those
1175 * proof rules are encapsulated in operator_predicate_proof().
1179 predicate_refuted_by_simple_clause(Expr *predicate, Node *clause,
1182 /* Allow interrupting long proof attempts */
1183 CHECK_FOR_INTERRUPTS();
1185 /* A simple clause can't refute itself */
1186 /* Worth checking because of relation_excluded_by_constraints() */
1187 if ((Node *) predicate == clause)
1190 /* Try the predicate-IS-NULL case */
1191 if (predicate && IsA(predicate, NullTest) &&
1192 ((NullTest *) predicate)->nulltesttype == IS_NULL)
1194 Expr *isnullarg = ((NullTest *) predicate)->arg;
1196 /* row IS NULL does not act in the simple way we have in mind */
1197 if (((NullTest *) predicate)->argisrow)
1200 /* strictness of clause for foo refutes foo IS NULL */
1201 if (clause_is_strict_for(clause, (Node *) isnullarg, true))
1204 /* foo IS NOT NULL refutes foo IS NULL */
1205 if (clause && IsA(clause, NullTest) &&
1206 ((NullTest *) clause)->nulltesttype == IS_NOT_NULL &&
1207 !((NullTest *) clause)->argisrow &&
1208 equal(((NullTest *) clause)->arg, isnullarg))
1211 return false; /* we can't succeed below... */
1214 /* Try the clause-IS-NULL case */
1215 if (clause && IsA(clause, NullTest) &&
1216 ((NullTest *) clause)->nulltesttype == IS_NULL)
1218 Expr *isnullarg = ((NullTest *) clause)->arg;
1220 /* row IS NULL does not act in the simple way we have in mind */
1221 if (((NullTest *) clause)->argisrow)
1224 /* foo IS NULL refutes foo IS NOT NULL */
1225 if (predicate && IsA(predicate, NullTest) &&
1226 ((NullTest *) predicate)->nulltesttype == IS_NOT_NULL &&
1227 !((NullTest *) predicate)->argisrow &&
1228 equal(((NullTest *) predicate)->arg, isnullarg))
1231 /* foo IS NULL weakly refutes any predicate that is strict for foo */
1233 clause_is_strict_for((Node *) predicate, (Node *) isnullarg, true))
1236 return false; /* we can't succeed below... */
1239 /* Else try operator-related knowledge */
1240 return operator_predicate_proof(predicate, clause, true, weak);
1245 * If clause asserts the non-truth of a subclause, return that subclause;
1246 * otherwise return NULL.
1249 extract_not_arg(Node *clause)
1253 if (IsA(clause, BoolExpr))
1255 BoolExpr *bexpr = (BoolExpr *) clause;
1257 if (bexpr->boolop == NOT_EXPR)
1258 return (Node *) linitial(bexpr->args);
1260 else if (IsA(clause, BooleanTest))
1262 BooleanTest *btest = (BooleanTest *) clause;
1264 if (btest->booltesttype == IS_NOT_TRUE ||
1265 btest->booltesttype == IS_FALSE ||
1266 btest->booltesttype == IS_UNKNOWN)
1267 return (Node *) btest->arg;
1273 * If clause asserts the falsity of a subclause, return that subclause;
1274 * otherwise return NULL.
1277 extract_strong_not_arg(Node *clause)
1281 if (IsA(clause, BoolExpr))
1283 BoolExpr *bexpr = (BoolExpr *) clause;
1285 if (bexpr->boolop == NOT_EXPR)
1286 return (Node *) linitial(bexpr->args);
1288 else if (IsA(clause, BooleanTest))
1290 BooleanTest *btest = (BooleanTest *) clause;
1292 if (btest->booltesttype == IS_FALSE)
1293 return (Node *) btest->arg;
1300 * Can we prove that "clause" returns NULL (or FALSE) if "subexpr" is
1301 * assumed to yield NULL?
1303 * In most places in the planner, "strictness" refers to a guarantee that
1304 * an expression yields NULL output for a NULL input, and that's mostly what
1305 * we're looking for here. However, at top level where the clause is known
1306 * to yield boolean, it may be sufficient to prove that it cannot return TRUE
1307 * when "subexpr" is NULL. The caller should pass allow_false = true when
1308 * this weaker property is acceptable. (When this function recurses
1309 * internally, we pass down allow_false = false since we need to prove actual
1310 * nullness of the subexpression.)
1312 * We assume that the caller checked that least one of the input expressions
1313 * is immutable. All of the proof rules here involve matching "subexpr" to
1314 * some portion of "clause", so that this allows assuming that "subexpr" is
1315 * immutable without a separate check.
1317 * The base case is that clause and subexpr are equal().
1319 * We can also report success if the subexpr appears as a subexpression
1320 * of "clause" in a place where it'd force nullness of the overall result.
1323 clause_is_strict_for(Node *clause, Node *subexpr, bool allow_false)
1328 if (clause == NULL || subexpr == NULL)
1332 * Look through any RelabelType nodes, so that we can match, say,
1333 * varcharcol with lower(varcharcol::text). (In general we could recurse
1334 * through any nullness-preserving, immutable operation.) We should not
1335 * see stacked RelabelTypes here.
1337 if (IsA(clause, RelabelType))
1338 clause = (Node *) ((RelabelType *) clause)->arg;
1339 if (IsA(subexpr, RelabelType))
1340 subexpr = (Node *) ((RelabelType *) subexpr)->arg;
1343 if (equal(clause, subexpr))
1347 * If we have a strict operator or function, a NULL result is guaranteed
1348 * if any input is forced NULL by subexpr. This is OK even if the op or
1349 * func isn't immutable, since it won't even be called on NULL input.
1351 if (is_opclause(clause) &&
1352 op_strict(((OpExpr *) clause)->opno))
1354 foreach(lc, ((OpExpr *) clause)->args)
1356 if (clause_is_strict_for((Node *) lfirst(lc), subexpr, false))
1361 if (is_funcclause(clause) &&
1362 func_strict(((FuncExpr *) clause)->funcid))
1364 foreach(lc, ((FuncExpr *) clause)->args)
1366 if (clause_is_strict_for((Node *) lfirst(lc), subexpr, false))
1373 * CoerceViaIO is strict (whether or not the I/O functions it calls are).
1374 * Likewise, ArrayCoerceExpr is strict for its array argument (regardless
1375 * of what the per-element expression is), ConvertRowtypeExpr is strict at
1376 * the row level, and CoerceToDomain is strict too. These are worth
1377 * checking mainly because it saves us having to explain to users why some
1378 * type coercions are known strict and others aren't.
1380 if (IsA(clause, CoerceViaIO))
1381 return clause_is_strict_for((Node *) ((CoerceViaIO *) clause)->arg,
1383 if (IsA(clause, ArrayCoerceExpr))
1384 return clause_is_strict_for((Node *) ((ArrayCoerceExpr *) clause)->arg,
1386 if (IsA(clause, ConvertRowtypeExpr))
1387 return clause_is_strict_for((Node *) ((ConvertRowtypeExpr *) clause)->arg,
1389 if (IsA(clause, CoerceToDomain))
1390 return clause_is_strict_for((Node *) ((CoerceToDomain *) clause)->arg,
1394 * ScalarArrayOpExpr is a special case. Note that we'd only reach here
1395 * with a ScalarArrayOpExpr clause if we failed to deconstruct it into an
1396 * AND or OR tree, as for example if it has too many array elements.
1398 if (IsA(clause, ScalarArrayOpExpr))
1400 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
1401 Node *scalarnode = (Node *) linitial(saop->args);
1402 Node *arraynode = (Node *) lsecond(saop->args);
1405 * If we can prove the scalar input to be null, and the operator is
1406 * strict, then the SAOP result has to be null --- unless the array is
1407 * empty. For an empty array, we'd get either false (for ANY) or true
1408 * (for ALL). So if allow_false = true then the proof succeeds anyway
1409 * for the ANY case; otherwise we can only make the proof if we can
1410 * prove the array non-empty.
1412 if (clause_is_strict_for(scalarnode, subexpr, false) &&
1413 op_strict(saop->opno))
1417 if (allow_false && saop->useOr)
1418 return true; /* can succeed even if array is empty */
1420 if (arraynode && IsA(arraynode, Const))
1422 Const *arrayconst = (Const *) arraynode;
1426 * If array is constant NULL then we can succeed, as in the
1429 if (arrayconst->constisnull)
1432 /* Otherwise, we can compute the number of elements. */
1433 arrval = DatumGetArrayTypeP(arrayconst->constvalue);
1434 nelems = ArrayGetNItems(ARR_NDIM(arrval), ARR_DIMS(arrval));
1436 else if (arraynode && IsA(arraynode, ArrayExpr) &&
1437 !((ArrayExpr *) arraynode)->multidims)
1440 * We can also reliably count the number of array elements if
1441 * the input is a non-multidim ARRAY[] expression.
1443 nelems = list_length(((ArrayExpr *) arraynode)->elements);
1446 /* Proof succeeds if array is definitely non-empty */
1452 * If we can prove the array input to be null, the proof succeeds in
1453 * all cases, since ScalarArrayOpExpr will always return NULL for a
1454 * NULL array. Otherwise, we're done here.
1456 return clause_is_strict_for(arraynode, subexpr, false);
1460 * When recursing into an expression, we might find a NULL constant.
1461 * That's certainly NULL, whether it matches subexpr or not.
1463 if (IsA(clause, Const))
1464 return ((Const *) clause)->constisnull;
1471 * Define "operator implication tables" for btree operators ("strategies"),
1472 * and similar tables for refutation.
1474 * The strategy numbers defined by btree indexes (see access/stratnum.h) are:
1475 * 1 < 2 <= 3 = 4 >= 5 >
1476 * and in addition we use 6 to represent <>. <> is not a btree-indexable
1477 * operator, but we assume here that if an equality operator of a btree
1478 * opfamily has a negator operator, the negator behaves as <> for the opfamily.
1479 * (This convention is also known to get_op_btree_interpretation().)
1481 * BT_implies_table[] and BT_refutes_table[] are used for cases where we have
1482 * two identical subexpressions and we want to know whether one operator
1483 * expression implies or refutes the other. That is, if the "clause" is
1484 * EXPR1 clause_op EXPR2 and the "predicate" is EXPR1 pred_op EXPR2 for the
1485 * same two (immutable) subexpressions:
1486 * BT_implies_table[clause_op-1][pred_op-1]
1487 * is true if the clause implies the predicate
1488 * BT_refutes_table[clause_op-1][pred_op-1]
1489 * is true if the clause refutes the predicate
1490 * where clause_op and pred_op are strategy numbers (from 1 to 6) in the
1491 * same btree opfamily. For example, "x < y" implies "x <= y" and refutes
1494 * BT_implic_table[] and BT_refute_table[] are used where we have two
1495 * constants that we need to compare. The interpretation of:
1497 * test_op = BT_implic_table[clause_op-1][pred_op-1]
1499 * where test_op, clause_op and pred_op are strategy numbers (from 1 to 6)
1500 * of btree operators, is as follows:
1502 * If you know, for some EXPR, that "EXPR clause_op CONST1" is true, and you
1503 * want to determine whether "EXPR pred_op CONST2" must also be true, then
1504 * you can use "CONST2 test_op CONST1" as a test. If this test returns true,
1505 * then the predicate expression must be true; if the test returns false,
1506 * then the predicate expression may be false.
1508 * For example, if clause is "Quantity > 10" and pred is "Quantity > 5"
1509 * then we test "5 <= 10" which evals to true, so clause implies pred.
1511 * Similarly, the interpretation of a BT_refute_table entry is:
1513 * If you know, for some EXPR, that "EXPR clause_op CONST1" is true, and you
1514 * want to determine whether "EXPR pred_op CONST2" must be false, then
1515 * you can use "CONST2 test_op CONST1" as a test. If this test returns true,
1516 * then the predicate expression must be false; if the test returns false,
1517 * then the predicate expression may be true.
1519 * For example, if clause is "Quantity > 10" and pred is "Quantity < 5"
1520 * then we test "5 <= 10" which evals to true, so clause refutes pred.
1522 * An entry where test_op == 0 means the implication cannot be determined.
1525 #define BTLT BTLessStrategyNumber
1526 #define BTLE BTLessEqualStrategyNumber
1527 #define BTEQ BTEqualStrategyNumber
1528 #define BTGE BTGreaterEqualStrategyNumber
1529 #define BTGT BTGreaterStrategyNumber
1530 #define BTNE ROWCOMPARE_NE
1532 /* We use "none" for 0/false to make the tables align nicely */
1535 static const bool BT_implies_table[6][6] = {
1537 * The predicate operator:
1540 {true, true, none, none, none, true}, /* LT */
1541 {none, true, none, none, none, none}, /* LE */
1542 {none, true, true, true, none, none}, /* EQ */
1543 {none, none, none, true, none, none}, /* GE */
1544 {none, none, none, true, true, true}, /* GT */
1545 {none, none, none, none, none, true} /* NE */
1548 static const bool BT_refutes_table[6][6] = {
1550 * The predicate operator:
1553 {none, none, true, true, true, none}, /* LT */
1554 {none, none, none, none, true, none}, /* LE */
1555 {true, none, none, none, true, true}, /* EQ */
1556 {true, none, none, none, none, none}, /* GE */
1557 {true, true, true, none, none, none}, /* GT */
1558 {none, none, true, none, none, none} /* NE */
1561 static const StrategyNumber BT_implic_table[6][6] = {
1563 * The predicate operator:
1566 {BTGE, BTGE, none, none, none, BTGE}, /* LT */
1567 {BTGT, BTGE, none, none, none, BTGT}, /* LE */
1568 {BTGT, BTGE, BTEQ, BTLE, BTLT, BTNE}, /* EQ */
1569 {none, none, none, BTLE, BTLT, BTLT}, /* GE */
1570 {none, none, none, BTLE, BTLE, BTLE}, /* GT */
1571 {none, none, none, none, none, BTEQ} /* NE */
1574 static const StrategyNumber BT_refute_table[6][6] = {
1576 * The predicate operator:
1579 {none, none, BTGE, BTGE, BTGE, none}, /* LT */
1580 {none, none, BTGT, BTGT, BTGE, none}, /* LE */
1581 {BTLE, BTLT, BTNE, BTGT, BTGE, BTEQ}, /* EQ */
1582 {BTLE, BTLT, BTLT, none, none, none}, /* GE */
1583 {BTLE, BTLE, BTLE, none, none, none}, /* GT */
1584 {none, none, BTEQ, none, none, none} /* NE */
1589 * operator_predicate_proof
1590 * Does the predicate implication or refutation test for a "simple clause"
1591 * predicate and a "simple clause" restriction, when both are operator
1592 * clauses using related operators and identical input expressions.
1594 * When refute_it == false, we want to prove the predicate true;
1595 * when refute_it == true, we want to prove the predicate false.
1596 * (There is enough common code to justify handling these two cases
1597 * in one routine.) We return true if able to make the proof, false
1598 * if not able to prove it.
1600 * We mostly need not distinguish strong vs. weak implication/refutation here.
1601 * This depends on the assumption that a pair of related operators (i.e.,
1602 * commutators, negators, or btree opfamily siblings) will not return one NULL
1603 * and one non-NULL result for the same inputs. Then, for the proof types
1604 * where we start with an assumption of truth of the clause, the predicate
1605 * operator could not return NULL either, so it doesn't matter whether we are
1606 * trying to make a strong or weak proof. For weak implication, it could be
1607 * that the clause operator returned NULL, but then the predicate operator
1608 * would as well, so that the weak implication still holds. This argument
1609 * doesn't apply in the case where we are considering two different constant
1610 * values, since then the operators aren't being given identical inputs. But
1611 * we only support that for btree operators, for which we can assume that all
1612 * non-null inputs result in non-null outputs, so that it doesn't matter which
1613 * two non-null constants we consider. If either constant is NULL, we have
1614 * to think harder, but sometimes the proof still works, as explained below.
1616 * We can make proofs involving several expression forms (here "foo" and "bar"
1617 * represent subexpressions that are identical according to equal()):
1618 * "foo op1 bar" refutes "foo op2 bar" if op1 is op2's negator
1619 * "foo op1 bar" implies "bar op2 foo" if op1 is op2's commutator
1620 * "foo op1 bar" refutes "bar op2 foo" if op1 is negator of op2's commutator
1621 * "foo op1 bar" can imply/refute "foo op2 bar" based on btree semantics
1622 * "foo op1 bar" can imply/refute "bar op2 foo" based on btree semantics
1623 * "foo op1 const1" can imply/refute "foo op2 const2" based on btree semantics
1625 * For the last three cases, op1 and op2 have to be members of the same btree
1626 * operator family. When both subexpressions are identical, the idea is that,
1627 * for instance, x < y implies x <= y, independently of exactly what x and y
1628 * are. If we have two different constants compared to the same expression
1629 * foo, we have to execute a comparison between the two constant values
1630 * in order to determine the result; for instance, foo < c1 implies foo < c2
1631 * if c1 <= c2. We assume it's safe to compare the constants at plan time
1632 * if the comparison operator is immutable.
1634 * Note: all the operators and subexpressions have to be immutable for the
1635 * proof to be safe. We assume the predicate expression is entirely immutable,
1636 * so no explicit check on the subexpressions is needed here, but in some
1637 * cases we need an extra check of operator immutability. In particular,
1638 * btree opfamilies can contain cross-type operators that are merely stable,
1639 * and we dare not make deductions with those.
1642 operator_predicate_proof(Expr *predicate, Node *clause,
1643 bool refute_it, bool weak)
1645 OpExpr *pred_opexpr,
1659 ExprState *test_exprstate;
1663 MemoryContext oldcontext;
1666 * Both expressions must be binary opclauses, else we can't do anything.
1668 * Note: in future we might extend this logic to other operator-based
1669 * constructs such as DistinctExpr. But the planner isn't very smart
1670 * about DistinctExpr in general, and this probably isn't the first place
1671 * to fix if you want to improve that.
1673 if (!is_opclause(predicate))
1675 pred_opexpr = (OpExpr *) predicate;
1676 if (list_length(pred_opexpr->args) != 2)
1678 if (!is_opclause(clause))
1680 clause_opexpr = (OpExpr *) clause;
1681 if (list_length(clause_opexpr->args) != 2)
1685 * If they're marked with different collations then we can't do anything.
1686 * This is a cheap test so let's get it out of the way early.
1688 pred_collation = pred_opexpr->inputcollid;
1689 clause_collation = clause_opexpr->inputcollid;
1690 if (pred_collation != clause_collation)
1693 /* Grab the operator OIDs now too. We may commute these below. */
1694 pred_op = pred_opexpr->opno;
1695 clause_op = clause_opexpr->opno;
1698 * We have to match up at least one pair of input expressions.
1700 pred_leftop = (Node *) linitial(pred_opexpr->args);
1701 pred_rightop = (Node *) lsecond(pred_opexpr->args);
1702 clause_leftop = (Node *) linitial(clause_opexpr->args);
1703 clause_rightop = (Node *) lsecond(clause_opexpr->args);
1705 if (equal(pred_leftop, clause_leftop))
1707 if (equal(pred_rightop, clause_rightop))
1709 /* We have x op1 y and x op2 y */
1710 return operator_same_subexprs_proof(pred_op, clause_op, refute_it);
1714 /* Fail unless rightops are both Consts */
1715 if (pred_rightop == NULL || !IsA(pred_rightop, Const))
1717 pred_const = (Const *) pred_rightop;
1718 if (clause_rightop == NULL || !IsA(clause_rightop, Const))
1720 clause_const = (Const *) clause_rightop;
1723 else if (equal(pred_rightop, clause_rightop))
1725 /* Fail unless leftops are both Consts */
1726 if (pred_leftop == NULL || !IsA(pred_leftop, Const))
1728 pred_const = (Const *) pred_leftop;
1729 if (clause_leftop == NULL || !IsA(clause_leftop, Const))
1731 clause_const = (Const *) clause_leftop;
1732 /* Commute both operators so we can assume Consts are on the right */
1733 pred_op = get_commutator(pred_op);
1734 if (!OidIsValid(pred_op))
1736 clause_op = get_commutator(clause_op);
1737 if (!OidIsValid(clause_op))
1740 else if (equal(pred_leftop, clause_rightop))
1742 if (equal(pred_rightop, clause_leftop))
1744 /* We have x op1 y and y op2 x */
1745 /* Commute pred_op that we can treat this like a straight match */
1746 pred_op = get_commutator(pred_op);
1747 if (!OidIsValid(pred_op))
1749 return operator_same_subexprs_proof(pred_op, clause_op, refute_it);
1753 /* Fail unless pred_rightop/clause_leftop are both Consts */
1754 if (pred_rightop == NULL || !IsA(pred_rightop, Const))
1756 pred_const = (Const *) pred_rightop;
1757 if (clause_leftop == NULL || !IsA(clause_leftop, Const))
1759 clause_const = (Const *) clause_leftop;
1760 /* Commute clause_op so we can assume Consts are on the right */
1761 clause_op = get_commutator(clause_op);
1762 if (!OidIsValid(clause_op))
1766 else if (equal(pred_rightop, clause_leftop))
1768 /* Fail unless pred_leftop/clause_rightop are both Consts */
1769 if (pred_leftop == NULL || !IsA(pred_leftop, Const))
1771 pred_const = (Const *) pred_leftop;
1772 if (clause_rightop == NULL || !IsA(clause_rightop, Const))
1774 clause_const = (Const *) clause_rightop;
1775 /* Commute pred_op so we can assume Consts are on the right */
1776 pred_op = get_commutator(pred_op);
1777 if (!OidIsValid(pred_op))
1782 /* Failed to match up any of the subexpressions, so we lose */
1787 * We have two identical subexpressions, and two other subexpressions that
1788 * are not identical but are both Consts; and we have commuted the
1789 * operators if necessary so that the Consts are on the right. We'll need
1790 * to compare the Consts' values. If either is NULL, we can't do that, so
1791 * usually the proof fails ... but in some cases we can claim success.
1793 if (clause_const->constisnull)
1795 /* If clause_op isn't strict, we can't prove anything */
1796 if (!op_strict(clause_op))
1800 * At this point we know that the clause returns NULL. For proof
1801 * types that assume truth of the clause, this means the proof is
1802 * vacuously true (a/k/a "false implies anything"). That's all proof
1803 * types except weak implication.
1805 if (!(weak && !refute_it))
1809 * For weak implication, it's still possible for the proof to succeed,
1810 * if the predicate can also be proven NULL. In that case we've got
1811 * NULL => NULL which is valid for this proof type.
1813 if (pred_const->constisnull && op_strict(pred_op))
1815 /* Else the proof fails */
1818 if (pred_const->constisnull)
1821 * If the pred_op is strict, we know the predicate yields NULL, which
1822 * means the proof succeeds for either weak implication or weak
1825 if (weak && op_strict(pred_op))
1827 /* Else the proof fails */
1832 * Lookup the constant-comparison operator using the system catalogs and
1833 * the operator implication tables.
1835 test_op = get_btree_test_op(pred_op, clause_op, refute_it);
1837 if (!OidIsValid(test_op))
1839 /* couldn't find a suitable comparison operator */
1844 * Evaluate the test. For this we need an EState.
1846 estate = CreateExecutorState();
1848 /* We can use the estate's working context to avoid memory leaks. */
1849 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1851 /* Build expression tree */
1852 test_expr = make_opclause(test_op,
1855 (Expr *) pred_const,
1856 (Expr *) clause_const,
1860 /* Fill in opfuncids */
1861 fix_opfuncids((Node *) test_expr);
1863 /* Prepare it for execution */
1864 test_exprstate = ExecInitExpr(test_expr, NULL);
1866 /* And execute it. */
1867 test_result = ExecEvalExprSwitchContext(test_exprstate,
1868 GetPerTupleExprContext(estate),
1871 /* Get back to outer memory context */
1872 MemoryContextSwitchTo(oldcontext);
1874 /* Release all the junk we just created */
1875 FreeExecutorState(estate);
1879 /* Treat a null result as non-proof ... but it's a tad fishy ... */
1880 elog(DEBUG2, "null predicate test result");
1883 return DatumGetBool(test_result);
1888 * operator_same_subexprs_proof
1889 * Assuming that EXPR1 clause_op EXPR2 is true, try to prove or refute
1890 * EXPR1 pred_op EXPR2.
1892 * Return true if able to make the proof, false if not able to prove it.
1895 operator_same_subexprs_proof(Oid pred_op, Oid clause_op, bool refute_it)
1898 * A simple and general rule is that the predicate is proven if clause_op
1899 * and pred_op are the same, or refuted if they are each other's negators.
1900 * We need not check immutability since the pred_op is already known
1901 * immutable. (Actually, by this point we may have the commutator of a
1902 * known-immutable pred_op, but that should certainly be immutable too.
1903 * Likewise we don't worry whether the pred_op's negator is immutable.)
1905 * Note: the "same" case won't get here if we actually had EXPR1 clause_op
1906 * EXPR2 and EXPR1 pred_op EXPR2, because the overall-expression-equality
1907 * test in predicate_implied_by_simple_clause would have caught it. But
1908 * we can see the same operator after having commuted the pred_op.
1912 if (get_negator(pred_op) == clause_op)
1917 if (pred_op == clause_op)
1922 * Otherwise, see if we can determine the implication by finding the
1923 * operators' relationship via some btree opfamily.
1925 return operator_same_subexprs_lookup(pred_op, clause_op, refute_it);
1930 * We use a lookaside table to cache the result of btree proof operator
1931 * lookups, since the actual lookup is pretty expensive and doesn't change
1932 * for any given pair of operators (at least as long as pg_amop doesn't
1933 * change). A single hash entry stores both implication and refutation
1934 * results for a given pair of operators; but note we may have determined
1935 * only one of those sets of results as yet.
1937 typedef struct OprProofCacheKey
1939 Oid pred_op; /* predicate operator */
1940 Oid clause_op; /* clause operator */
1943 typedef struct OprProofCacheEntry
1945 /* the hash lookup key MUST BE FIRST */
1946 OprProofCacheKey key;
1948 bool have_implic; /* do we know the implication result? */
1949 bool have_refute; /* do we know the refutation result? */
1950 bool same_subexprs_implies; /* X clause_op Y implies X pred_op Y? */
1951 bool same_subexprs_refutes; /* X clause_op Y refutes X pred_op Y? */
1952 Oid implic_test_op; /* OID of the test operator, or 0 if none */
1953 Oid refute_test_op; /* OID of the test operator, or 0 if none */
1954 } OprProofCacheEntry;
1956 static HTAB *OprProofCacheHash = NULL;
1960 * lookup_proof_cache
1961 * Get, and fill in if necessary, the appropriate cache entry.
1963 static OprProofCacheEntry *
1964 lookup_proof_cache(Oid pred_op, Oid clause_op, bool refute_it)
1966 OprProofCacheKey key;
1967 OprProofCacheEntry *cache_entry;
1969 bool same_subexprs = false;
1970 Oid test_op = InvalidOid;
1972 List *pred_op_infos,
1978 * Find or make a cache entry for this pair of operators.
1980 if (OprProofCacheHash == NULL)
1982 /* First time through: initialize the hash table */
1985 MemSet(&ctl, 0, sizeof(ctl));
1986 ctl.keysize = sizeof(OprProofCacheKey);
1987 ctl.entrysize = sizeof(OprProofCacheEntry);
1988 OprProofCacheHash = hash_create("Btree proof lookup cache", 256,
1989 &ctl, HASH_ELEM | HASH_BLOBS);
1991 /* Arrange to flush cache on pg_amop changes */
1992 CacheRegisterSyscacheCallback(AMOPOPID,
1993 InvalidateOprProofCacheCallBack,
1997 key.pred_op = pred_op;
1998 key.clause_op = clause_op;
1999 cache_entry = (OprProofCacheEntry *) hash_search(OprProofCacheHash,
2001 HASH_ENTER, &cfound);
2004 /* new cache entry, set it invalid */
2005 cache_entry->have_implic = false;
2006 cache_entry->have_refute = false;
2010 /* pre-existing cache entry, see if we know the answer yet */
2011 if (refute_it ? cache_entry->have_refute : cache_entry->have_implic)
2016 * Try to find a btree opfamily containing the given operators.
2018 * We must find a btree opfamily that contains both operators, else the
2019 * implication can't be determined. Also, the opfamily must contain a
2020 * suitable test operator taking the operators' righthand datatypes.
2022 * If there are multiple matching opfamilies, assume we can use any one to
2023 * determine the logical relationship of the two operators and the correct
2024 * corresponding test operator. This should work for any logically
2025 * consistent opfamilies.
2027 * Note that we can determine the operators' relationship for
2028 * same-subexprs cases even from an opfamily that lacks a usable test
2029 * operator. This can happen in cases with incomplete sets of cross-type
2030 * comparison operators.
2032 clause_op_infos = get_op_btree_interpretation(clause_op);
2033 if (clause_op_infos)
2034 pred_op_infos = get_op_btree_interpretation(pred_op);
2035 else /* no point in looking */
2036 pred_op_infos = NIL;
2038 foreach(lcp, pred_op_infos)
2040 OpBtreeInterpretation *pred_op_info = lfirst(lcp);
2041 Oid opfamily_id = pred_op_info->opfamily_id;
2043 foreach(lcc, clause_op_infos)
2045 OpBtreeInterpretation *clause_op_info = lfirst(lcc);
2046 StrategyNumber pred_strategy,
2050 /* Must find them in same opfamily */
2051 if (opfamily_id != clause_op_info->opfamily_id)
2053 /* Lefttypes should match */
2054 Assert(clause_op_info->oplefttype == pred_op_info->oplefttype);
2056 pred_strategy = pred_op_info->strategy;
2057 clause_strategy = clause_op_info->strategy;
2060 * Check to see if we can make a proof for same-subexpressions
2061 * cases based on the operators' relationship in this opfamily.
2064 same_subexprs |= BT_refutes_table[clause_strategy - 1][pred_strategy - 1];
2066 same_subexprs |= BT_implies_table[clause_strategy - 1][pred_strategy - 1];
2069 * Look up the "test" strategy number in the implication table
2072 test_strategy = BT_refute_table[clause_strategy - 1][pred_strategy - 1];
2074 test_strategy = BT_implic_table[clause_strategy - 1][pred_strategy - 1];
2076 if (test_strategy == 0)
2078 /* Can't determine implication using this interpretation */
2083 * See if opfamily has an operator for the test strategy and the
2086 if (test_strategy == BTNE)
2088 test_op = get_opfamily_member(opfamily_id,
2089 pred_op_info->oprighttype,
2090 clause_op_info->oprighttype,
2091 BTEqualStrategyNumber);
2092 if (OidIsValid(test_op))
2093 test_op = get_negator(test_op);
2097 test_op = get_opfamily_member(opfamily_id,
2098 pred_op_info->oprighttype,
2099 clause_op_info->oprighttype,
2103 if (!OidIsValid(test_op))
2107 * Last check: test_op must be immutable.
2109 * Note that we require only the test_op to be immutable, not the
2110 * original clause_op. (pred_op is assumed to have been checked
2111 * immutable by the caller.) Essentially we are assuming that the
2112 * opfamily is consistent even if it contains operators that are
2115 if (op_volatile(test_op) == PROVOLATILE_IMMUTABLE)
2126 list_free_deep(pred_op_infos);
2127 list_free_deep(clause_op_infos);
2131 /* couldn't find a suitable comparison operator */
2132 test_op = InvalidOid;
2136 * If we think we were able to prove something about same-subexpressions
2137 * cases, check to make sure the clause_op is immutable before believing
2138 * it completely. (Usually, the clause_op would be immutable if the
2139 * pred_op is, but it's not entirely clear that this must be true in all
2140 * cases, so let's check.)
2142 if (same_subexprs &&
2143 op_volatile(clause_op) != PROVOLATILE_IMMUTABLE)
2144 same_subexprs = false;
2146 /* Cache the results, whether positive or negative */
2149 cache_entry->refute_test_op = test_op;
2150 cache_entry->same_subexprs_refutes = same_subexprs;
2151 cache_entry->have_refute = true;
2155 cache_entry->implic_test_op = test_op;
2156 cache_entry->same_subexprs_implies = same_subexprs;
2157 cache_entry->have_implic = true;
2164 * operator_same_subexprs_lookup
2165 * Convenience subroutine to look up the cached answer for
2166 * same-subexpressions cases.
2169 operator_same_subexprs_lookup(Oid pred_op, Oid clause_op, bool refute_it)
2171 OprProofCacheEntry *cache_entry;
2173 cache_entry = lookup_proof_cache(pred_op, clause_op, refute_it);
2175 return cache_entry->same_subexprs_refutes;
2177 return cache_entry->same_subexprs_implies;
2182 * Identify the comparison operator needed for a btree-operator
2183 * proof or refutation involving comparison of constants.
2185 * Given the truth of a clause "var clause_op const1", we are attempting to
2186 * prove or refute a predicate "var pred_op const2". The identities of the
2187 * two operators are sufficient to determine the operator (if any) to compare
2188 * const2 to const1 with.
2190 * Returns the OID of the operator to use, or InvalidOid if no proof is
2194 get_btree_test_op(Oid pred_op, Oid clause_op, bool refute_it)
2196 OprProofCacheEntry *cache_entry;
2198 cache_entry = lookup_proof_cache(pred_op, clause_op, refute_it);
2200 return cache_entry->refute_test_op;
2202 return cache_entry->implic_test_op;
2207 * Callback for pg_amop inval events
2210 InvalidateOprProofCacheCallBack(Datum arg, int cacheid, uint32 hashvalue)
2212 HASH_SEQ_STATUS status;
2213 OprProofCacheEntry *hentry;
2215 Assert(OprProofCacheHash != NULL);
2217 /* Currently we just reset all entries; hard to be smarter ... */
2218 hash_seq_init(&status, OprProofCacheHash);
2220 while ((hentry = (OprProofCacheEntry *) hash_seq_search(&status)) != NULL)
2222 hentry->have_implic = false;
2223 hentry->have_refute = false;