Skip to content

Commit 912fb29

Browse files
committed
Be more careful about the shape of hashable subplan clauses.
nodeSubplan.c expects that the testexpr for a hashable ANY SubPlan has the form of one or more OpExprs whose LHS is an expression of the outer query's, while the RHS is an expression over Params representing output columns of the subquery. However, the planner only went as far as verifying that the clauses were all binary OpExprs. This works 99.99% of the time, because the clauses have the right shape when emitted by the parser --- but it's possible for function inlining to break that, as reported by PegoraroF10. To fix, teach the planner to check that the LHS and RHS contain the right things, or more accurately don't contain the wrong things. Given that this has been broken for years without anyone noticing, it seems sufficient to just give up hashing when it happens, rather than go to the trouble of commuting the clauses back again (which wouldn't necessarily work anyway). While poking at that, I also noticed that nodeSubplan.c had a baked-in assumption that the number of hash clauses is identical to the number of subquery output columns. Again, that's fine as far as parser output goes, but it's not hard to break it via function inlining. There seems little reason for that assumption though --- AFAICS, the only thing it's buying us is not having to store the number of hash clauses explicitly. Adding code to the planner to reject such cases would take more code than getting nodeSubplan.c to cope, so I fixed it that way. This has been broken for as long as we've had hashable SubPlans, so back-patch to all supported branches. Discussion: https://postgr.es/m/1549209182255-0.post@n3.nabble.com
1 parent 3dadcb2 commit 912fb29

File tree

7 files changed

+219
-30
lines changed

7 files changed

+219
-30
lines changed

src/backend/executor/nodeSubplan.c

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -472,7 +472,7 @@ buildSubPlanHash(SubPlanState *node, ExprContext *econtext)
472472
{
473473
SubPlan *subplan = node->subplan;
474474
PlanState *planstate = node->planstate;
475-
int ncols = list_length(subplan->paramIds);
475+
int ncols = node->numCols;
476476
ExprContext *innerecontext = node->innerecontext;
477477
MemoryContext oldcontext;
478478
long nbuckets;
@@ -879,11 +879,6 @@ ExecInitSubPlan(SubPlan *subplan, PlanState *parent)
879879
ALLOCSET_SMALL_SIZES);
880880
/* and a short-lived exprcontext for function evaluation */
881881
sstate->innerecontext = CreateExprContext(estate);
882-
/* Silly little array of column numbers 1..n */
883-
ncols = list_length(subplan->paramIds);
884-
sstate->keyColIdx = (AttrNumber *) palloc(ncols * sizeof(AttrNumber));
885-
for (i = 0; i < ncols; i++)
886-
sstate->keyColIdx[i] = i + 1;
887882

888883
/*
889884
* We use ExecProject to evaluate the lefthand and righthand
@@ -915,13 +910,15 @@ ExecInitSubPlan(SubPlan *subplan, PlanState *parent)
915910
(int) nodeTag(subplan->testexpr));
916911
oplist = NIL; /* keep compiler quiet */
917912
}
918-
Assert(list_length(oplist) == ncols);
913+
ncols = list_length(oplist);
919914

920915
lefttlist = righttlist = NIL;
916+
sstate->numCols = ncols;
917+
sstate->keyColIdx = (AttrNumber *) palloc(ncols * sizeof(AttrNumber));
921918
sstate->tab_eq_funcoids = (Oid *) palloc(ncols * sizeof(Oid));
919+
sstate->tab_collations = (Oid *) palloc(ncols * sizeof(Oid));
922920
sstate->tab_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
923921
sstate->tab_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
924-
sstate->tab_collations = (Oid *) palloc(ncols * sizeof(Oid));
925922
sstate->lhs_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
926923
sstate->cur_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
927924
/* we'll need the cross-type equality fns below, but not in sstate */
@@ -980,6 +977,9 @@ ExecInitSubPlan(SubPlan *subplan, PlanState *parent)
980977
/* Set collation */
981978
sstate->tab_collations[i - 1] = opexpr->inputcollid;
982979

980+
/* keyColIdx is just column numbers 1..n */
981+
sstate->keyColIdx[i - 1] = i;
982+
983983
i++;
984984
}
985985

src/backend/optimizer/plan/subselect.c

Lines changed: 55 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ typedef struct inline_cte_walker_context
6969
static Node *build_subplan(PlannerInfo *root, Plan *plan, PlannerInfo *subroot,
7070
List *plan_params,
7171
SubLinkType subLinkType, int subLinkId,
72-
Node *testexpr, bool adjust_testexpr,
72+
Node *testexpr, List *testexpr_paramids,
7373
bool unknownEqFalse);
7474
static List *generate_subquery_params(PlannerInfo *root, List *tlist,
7575
List **paramIds);
@@ -81,7 +81,8 @@ static Node *convert_testexpr(PlannerInfo *root,
8181
static Node *convert_testexpr_mutator(Node *node,
8282
convert_testexpr_context *context);
8383
static bool subplan_is_hashable(Plan *plan);
84-
static bool testexpr_is_hashable(Node *testexpr);
84+
static bool testexpr_is_hashable(Node *testexpr, List *param_ids);
85+
static bool test_opexpr_is_hashable(OpExpr *testexpr, List *param_ids);
8586
static bool hash_ok_operator(OpExpr *expr);
8687
static bool contain_dml(Node *node);
8788
static bool contain_dml_walker(Node *node, void *context);
@@ -237,7 +238,7 @@ make_subplan(PlannerInfo *root, Query *orig_subquery,
237238
/* And convert to SubPlan or InitPlan format. */
238239
result = build_subplan(root, plan, subroot, plan_params,
239240
subLinkType, subLinkId,
240-
testexpr, true, isTopQual);
241+
testexpr, NIL, isTopQual);
241242

242243
/*
243244
* If it's a correlated EXISTS with an unimportant targetlist, we might be
@@ -291,12 +292,11 @@ make_subplan(PlannerInfo *root, Query *orig_subquery,
291292
plan_params,
292293
ANY_SUBLINK, 0,
293294
newtestexpr,
294-
false, true));
295+
paramIds,
296+
true));
295297
/* Check we got what we expected */
296298
Assert(hashplan->parParam == NIL);
297299
Assert(hashplan->useHashTable);
298-
/* build_subplan won't have filled in paramIds */
299-
hashplan->paramIds = paramIds;
300300

301301
/* Leave it to the executor to decide which plan to use */
302302
asplan = makeNode(AlternativeSubPlan);
@@ -319,7 +319,7 @@ static Node *
319319
build_subplan(PlannerInfo *root, Plan *plan, PlannerInfo *subroot,
320320
List *plan_params,
321321
SubLinkType subLinkType, int subLinkId,
322-
Node *testexpr, bool adjust_testexpr,
322+
Node *testexpr, List *testexpr_paramids,
323323
bool unknownEqFalse)
324324
{
325325
Node *result;
@@ -484,10 +484,10 @@ build_subplan(PlannerInfo *root, Plan *plan, PlannerInfo *subroot,
484484
else
485485
{
486486
/*
487-
* Adjust the Params in the testexpr, unless caller said it's not
488-
* needed.
487+
* Adjust the Params in the testexpr, unless caller already took care
488+
* of it (as indicated by passing a list of Param IDs).
489489
*/
490-
if (testexpr && adjust_testexpr)
490+
if (testexpr && testexpr_paramids == NIL)
491491
{
492492
List *params;
493493

@@ -499,7 +499,10 @@ build_subplan(PlannerInfo *root, Plan *plan, PlannerInfo *subroot,
499499
params);
500500
}
501501
else
502+
{
502503
splan->testexpr = testexpr;
504+
splan->paramIds = testexpr_paramids;
505+
}
503506

504507
/*
505508
* We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types to
@@ -511,7 +514,7 @@ build_subplan(PlannerInfo *root, Plan *plan, PlannerInfo *subroot,
511514
if (subLinkType == ANY_SUBLINK &&
512515
splan->parParam == NIL &&
513516
subplan_is_hashable(plan) &&
514-
testexpr_is_hashable(splan->testexpr))
517+
testexpr_is_hashable(splan->testexpr, splan->paramIds))
515518
splan->useHashTable = true;
516519

517520
/*
@@ -733,24 +736,20 @@ subplan_is_hashable(Plan *plan)
733736

734737
/*
735738
* testexpr_is_hashable: is an ANY SubLink's test expression hashable?
739+
*
740+
* To identify LHS vs RHS of the hash expression, we must be given the
741+
* list of output Param IDs of the SubLink's subquery.
736742
*/
737743
static bool
738-
testexpr_is_hashable(Node *testexpr)
744+
testexpr_is_hashable(Node *testexpr, List *param_ids)
739745
{
740746
/*
741747
* The testexpr must be a single OpExpr, or an AND-clause containing only
742-
* OpExprs.
743-
*
744-
* The combining operators must be hashable and strict. The need for
745-
* hashability is obvious, since we want to use hashing. Without
746-
* strictness, behavior in the presence of nulls is too unpredictable. We
747-
* actually must assume even more than plain strictness: they can't yield
748-
* NULL for non-null inputs, either (see nodeSubplan.c). However, hash
749-
* indexes and hash joins assume that too.
748+
* OpExprs, each of which satisfy test_opexpr_is_hashable().
750749
*/
751750
if (testexpr && IsA(testexpr, OpExpr))
752751
{
753-
if (hash_ok_operator((OpExpr *) testexpr))
752+
if (test_opexpr_is_hashable((OpExpr *) testexpr, param_ids))
754753
return true;
755754
}
756755
else if (is_andclause(testexpr))
@@ -763,7 +762,7 @@ testexpr_is_hashable(Node *testexpr)
763762

764763
if (!IsA(andarg, OpExpr))
765764
return false;
766-
if (!hash_ok_operator((OpExpr *) andarg))
765+
if (!test_opexpr_is_hashable((OpExpr *) andarg, param_ids))
767766
return false;
768767
}
769768
return true;
@@ -772,6 +771,40 @@ testexpr_is_hashable(Node *testexpr)
772771
return false;
773772
}
774773

774+
static bool
775+
test_opexpr_is_hashable(OpExpr *testexpr, List *param_ids)
776+
{
777+
/*
778+
* The combining operator must be hashable and strict. The need for
779+
* hashability is obvious, since we want to use hashing. Without
780+
* strictness, behavior in the presence of nulls is too unpredictable. We
781+
* actually must assume even more than plain strictness: it can't yield
782+
* NULL for non-null inputs, either (see nodeSubplan.c). However, hash
783+
* indexes and hash joins assume that too.
784+
*/
785+
if (!hash_ok_operator(testexpr))
786+
return false;
787+
788+
/*
789+
* The left and right inputs must belong to the outer and inner queries
790+
* respectively; hence Params that will be supplied by the subquery must
791+
* not appear in the LHS, and Vars of the outer query must not appear in
792+
* the RHS. (Ordinarily, this must be true because of the way that the
793+
* parser builds an ANY SubLink's testexpr ... but inlining of functions
794+
* could have changed the expression's structure, so we have to check.
795+
* Such cases do not occur often enough to be worth trying to optimize, so
796+
* we don't worry about trying to commute the clause or anything like
797+
* that; we just need to be sure not to build an invalid plan.)
798+
*/
799+
if (list_length(testexpr->args) != 2)
800+
return false;
801+
if (contain_exec_param((Node *) linitial(testexpr->args), param_ids))
802+
return false;
803+
if (contain_var_clause((Node *) lsecond(testexpr->args)))
804+
return false;
805+
return true;
806+
}
807+
775808
/*
776809
* Check expression is hashable + strict
777810
*

src/backend/optimizer/util/clauses.c

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ static bool contain_volatile_functions_not_nextval_walker(Node *node, void *cont
108108
static bool max_parallel_hazard_walker(Node *node,
109109
max_parallel_hazard_context *context);
110110
static bool contain_nonstrict_functions_walker(Node *node, void *context);
111+
static bool contain_exec_param_walker(Node *node, List *param_ids);
111112
static bool contain_context_dependent_node(Node *clause);
112113
static bool contain_context_dependent_node_walker(Node *node, int *flags);
113114
static bool contain_leaked_vars_walker(Node *node, void *context);
@@ -1223,6 +1224,40 @@ contain_nonstrict_functions_walker(Node *node, void *context)
12231224
context);
12241225
}
12251226

1227+
/*****************************************************************************
1228+
* Check clauses for Params
1229+
*****************************************************************************/
1230+
1231+
/*
1232+
* contain_exec_param
1233+
* Recursively search for PARAM_EXEC Params within a clause.
1234+
*
1235+
* Returns true if the clause contains any PARAM_EXEC Param with a paramid
1236+
* appearing in the given list of Param IDs. Does not descend into
1237+
* subqueries!
1238+
*/
1239+
bool
1240+
contain_exec_param(Node *clause, List *param_ids)
1241+
{
1242+
return contain_exec_param_walker(clause, param_ids);
1243+
}
1244+
1245+
static bool
1246+
contain_exec_param_walker(Node *node, List *param_ids)
1247+
{
1248+
if (node == NULL)
1249+
return false;
1250+
if (IsA(node, Param))
1251+
{
1252+
Param *p = (Param *) node;
1253+
1254+
if (p->paramkind == PARAM_EXEC &&
1255+
list_member_int(param_ids, p->paramid))
1256+
return true;
1257+
}
1258+
return expression_tree_walker(node, contain_exec_param_walker, param_ids);
1259+
}
1260+
12261261
/*****************************************************************************
12271262
* Check clauses for context-dependent nodes
12281263
*****************************************************************************/

src/include/nodes/execnodes.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -862,6 +862,7 @@ typedef struct SubPlanState
862862
MemoryContext hashtablecxt; /* memory context containing hash tables */
863863
MemoryContext hashtempcxt; /* temp memory context for hash tables */
864864
ExprContext *innerecontext; /* econtext for computing inner tuples */
865+
/* each of the following fields is an array of length numCols: */
865866
AttrNumber *keyColIdx; /* control data for hash tables */
866867
Oid *tab_eq_funcoids; /* equality func oids for table
867868
* datatype(s) */
@@ -871,6 +872,7 @@ typedef struct SubPlanState
871872
FmgrInfo *lhs_hash_funcs; /* hash functions for lefthand datatype(s) */
872873
FmgrInfo *cur_eq_funcs; /* equality functions for LHS vs. table */
873874
ExprState *cur_eq_comp; /* equality comparator for LHS vs. table */
875+
int numCols; /* number of columns being hashed */
874876
} SubPlanState;
875877

876878
/* ----------------

src/include/optimizer/clauses.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ extern bool contain_subplans(Node *clause);
3838
extern char max_parallel_hazard(Query *parse);
3939
extern bool is_parallel_safe(PlannerInfo *root, Node *node);
4040
extern bool contain_nonstrict_functions(Node *clause);
41+
extern bool contain_exec_param(Node *clause, List *param_ids);
4142
extern bool contain_leaked_vars(Node *clause);
4243

4344
extern Relids find_nonnullable_rels(Node *clause);

src/test/regress/expected/subselect.out

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -757,6 +757,7 @@ insert into outer_text values ('a', null);
757757
insert into outer_text values ('b', null);
758758
create temp table inner_text (c1 text, c2 text);
759759
insert into inner_text values ('a', null);
760+
insert into inner_text values ('123', '456');
760761
select * from outer_text where (f1, f2) not in (select * from inner_text);
761762
f1 | f2
762763
----+----
@@ -797,6 +798,82 @@ select '1'::text in (select '1'::name union all select '1'::name);
797798
t
798799
(1 row)
799800

801+
--
802+
-- Test that we don't try to use a hashed subplan if the simplified
803+
-- testexpr isn't of the right shape
804+
--
805+
-- this fails by default, of course
806+
select * from int8_tbl where q1 in (select c1 from inner_text);
807+
ERROR: operator does not exist: bigint = text
808+
LINE 1: select * from int8_tbl where q1 in (select c1 from inner_tex...
809+
^
810+
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
811+
begin;
812+
-- make an operator to allow it to succeed
813+
create function bogus_int8_text_eq(int8, text) returns boolean
814+
language sql as 'select $1::text = $2';
815+
create operator = (procedure=bogus_int8_text_eq, leftarg=int8, rightarg=text);
816+
explain (costs off)
817+
select * from int8_tbl where q1 in (select c1 from inner_text);
818+
QUERY PLAN
819+
--------------------------------
820+
Seq Scan on int8_tbl
821+
Filter: (hashed SubPlan 1)
822+
SubPlan 1
823+
-> Seq Scan on inner_text
824+
(4 rows)
825+
826+
select * from int8_tbl where q1 in (select c1 from inner_text);
827+
q1 | q2
828+
-----+------------------
829+
123 | 456
830+
123 | 4567890123456789
831+
(2 rows)
832+
833+
-- inlining of this function results in unusual number of hash clauses,
834+
-- which we can still cope with
835+
create or replace function bogus_int8_text_eq(int8, text) returns boolean
836+
language sql as 'select $1::text = $2 and $1::text = $2';
837+
explain (costs off)
838+
select * from int8_tbl where q1 in (select c1 from inner_text);
839+
QUERY PLAN
840+
--------------------------------
841+
Seq Scan on int8_tbl
842+
Filter: (hashed SubPlan 1)
843+
SubPlan 1
844+
-> Seq Scan on inner_text
845+
(4 rows)
846+
847+
select * from int8_tbl where q1 in (select c1 from inner_text);
848+
q1 | q2
849+
-----+------------------
850+
123 | 456
851+
123 | 4567890123456789
852+
(2 rows)
853+
854+
-- inlining of this function causes LHS and RHS to be switched,
855+
-- which we can't cope with, so hashing should be abandoned
856+
create or replace function bogus_int8_text_eq(int8, text) returns boolean
857+
language sql as 'select $2 = $1::text';
858+
explain (costs off)
859+
select * from int8_tbl where q1 in (select c1 from inner_text);
860+
QUERY PLAN
861+
--------------------------------------
862+
Seq Scan on int8_tbl
863+
Filter: (SubPlan 1)
864+
SubPlan 1
865+
-> Materialize
866+
-> Seq Scan on inner_text
867+
(5 rows)
868+
869+
select * from int8_tbl where q1 in (select c1 from inner_text);
870+
q1 | q2
871+
-----+------------------
872+
123 | 456
873+
123 | 4567890123456789
874+
(2 rows)
875+
876+
rollback; -- to get rid of the bogus operator
800877
--
801878
-- Test case for planner bug with nested EXISTS handling
802879
--

0 commit comments

Comments
 (0)