diff --git a/age--1.8.0--y.y.y.sql b/age--1.8.0--y.y.y.sql index c5fa679d9..cce356dc4 100644 --- a/age--1.8.0--y.y.y.sql +++ b/age--1.8.0--y.y.y.sql @@ -111,3 +111,16 @@ $$; ALTER FUNCTION ag_catalog.agtype_string_match_starts_with(agtype, agtype) IMMUTABLE; ALTER FUNCTION ag_catalog.agtype_string_match_ends_with(agtype, agtype) IMMUTABLE; + +CREATE FUNCTION ag_catalog.agtype_in_predicate_support(internal) + RETURNS internal + LANGUAGE c +AS 'MODULE_PATHNAME'; + +CREATE FUNCTION ag_catalog.agtype_in_predicate(agtype, agtype) + RETURNS boolean + LANGUAGE c + IMMUTABLE +SUPPORT ag_catalog.agtype_in_predicate_support +PARALLEL SAFE +AS 'MODULE_PATHNAME'; diff --git a/regress/expected/index.out b/regress/expected/index.out index ed7363dd4..dd07e195c 100644 --- a/regress/expected/index.out +++ b/regress/expected/index.out @@ -848,17 +848,83 @@ SELECT value FROM agtype_btree_test WHERE value = '2'::agtype ORDER BY value; DROP TABLE agtype_btree_test; COMMIT; +-- A list parameter can use a property index in a custom plan (issue #2582). +\pset format unaligned +SET enable_seqscan = on; +SET plan_cache_mode = force_custom_plan; +SELECT * FROM cypher('cypher_index', $$ + UNWIND range(1, 2000) AS i + CREATE (:Item {pid: i}) +$$) AS (v agtype); +v +(0 rows) +SELECT * FROM cypher('cypher_index', $$ + CREATE (:Item {pid: 16.0}), (:Item) +$$) AS (v agtype); +v +(0 rows) +CREATE INDEX item_pid_idx ON cypher_index."Item" + (agtype_access_operator(properties, '"pid"'::agtype)); +ANALYZE cypher_index."Item"; +PREPARE bound_in(agtype) AS +SELECT * FROM cypher('cypher_index', $$ + MATCH (a:Item) + WHERE a.pid IN $pids + RETURN a.pid ORDER BY a.pid +$$, $1) AS (pid agtype); +EXPLAIN (COSTS OFF) EXECUTE bound_in('{"pids": [16, 42, 900]}'); +QUERY PLAN +Index Scan using item_pid_idx on "Item" a + Index Cond: (agtype_access_operator(VARIADIC ARRAY[properties, '"pid"'::agtype]) = ANY ('{16,42,900}'::agtype[])) + Filter: agtype_in_predicate('[16, 42, 900]'::agtype, agtype_access_operator(VARIADIC ARRAY[properties, '"pid"'::agtype])) +(3 rows) +-- The B-tree can also find 16.0 for 16. Rechecking IN must reject it. +EXECUTE bound_in('{"pids": [16, 16, null, 42, 900]}'); +pid +16 +42 +900 +(3 rows) +EXECUTE bound_in('{"pids": [16.0, 42]}'); +pid +16.0 +42 +(2 rows) +EXECUTE bound_in('{"pids": []}'); +pid +(0 rows) +EXECUTE bound_in('{"pids": null}'); +pid +(0 rows) +EXECUTE bound_in('{"pids": 16}'); +ERROR: object of IN must be a list +-- A generic plan still evaluates IN with the supplied list on each call. +SET plan_cache_mode = force_generic_plan; +EXECUTE bound_in('{"pids": [16, 42, 900]}'); +pid +16 +42 +900 +(3 rows) +EXECUTE bound_in('{"pids": [17]}'); +pid +17 +(1 row) +DEALLOCATE bound_in; +RESET plan_cache_mode; +\pset format aligned -- -- General Cleanup -- SELECT drop_graph('cypher_index', true); -NOTICE: drop cascades to 6 other objects +NOTICE: drop cascades to 7 other objects DETAIL: drop cascades to table cypher_index._ag_label_vertex drop cascades to table cypher_index._ag_label_edge drop cascades to table cypher_index.idx drop cascades to table cypher_index."Country" drop cascades to table cypher_index.has_city drop cascades to table cypher_index."City" +drop cascades to table cypher_index."Item" NOTICE: graph "cypher_index" has been dropped drop_graph ------------ diff --git a/regress/sql/index.sql b/regress/sql/index.sql index 1dd475d30..c3fbd474d 100644 --- a/regress/sql/index.sql +++ b/regress/sql/index.sql @@ -468,6 +468,46 @@ SELECT value FROM agtype_btree_test WHERE value = '2'::agtype ORDER BY value; DROP TABLE agtype_btree_test; COMMIT; +-- A list parameter can use a property index in a custom plan (issue #2582). +\pset format unaligned +SET enable_seqscan = on; +SET plan_cache_mode = force_custom_plan; + +SELECT * FROM cypher('cypher_index', $$ + UNWIND range(1, 2000) AS i + CREATE (:Item {pid: i}) +$$) AS (v agtype); +SELECT * FROM cypher('cypher_index', $$ + CREATE (:Item {pid: 16.0}), (:Item) +$$) AS (v agtype); + +CREATE INDEX item_pid_idx ON cypher_index."Item" + (agtype_access_operator(properties, '"pid"'::agtype)); +ANALYZE cypher_index."Item"; + +PREPARE bound_in(agtype) AS +SELECT * FROM cypher('cypher_index', $$ + MATCH (a:Item) + WHERE a.pid IN $pids + RETURN a.pid ORDER BY a.pid +$$, $1) AS (pid agtype); + +EXPLAIN (COSTS OFF) EXECUTE bound_in('{"pids": [16, 42, 900]}'); +-- The B-tree can also find 16.0 for 16. Rechecking IN must reject it. +EXECUTE bound_in('{"pids": [16, 16, null, 42, 900]}'); +EXECUTE bound_in('{"pids": [16.0, 42]}'); +EXECUTE bound_in('{"pids": []}'); +EXECUTE bound_in('{"pids": null}'); +EXECUTE bound_in('{"pids": 16}'); + +-- A generic plan still evaluates IN with the supplied list on each call. +SET plan_cache_mode = force_generic_plan; +EXECUTE bound_in('{"pids": [16, 42, 900]}'); +EXECUTE bound_in('{"pids": [17]}'); +DEALLOCATE bound_in; +RESET plan_cache_mode; +\pset format aligned + -- -- General Cleanup -- diff --git a/sql/agtype_access.sql b/sql/agtype_access.sql index 509cf5a70..53710f232 100644 --- a/sql/agtype_access.sql +++ b/sql/agtype_access.sql @@ -168,3 +168,15 @@ CREATE FUNCTION ag_catalog.agtype_in_operator(agtype, agtype) PARALLEL SAFE AS 'MODULE_PATHNAME'; +CREATE FUNCTION ag_catalog.agtype_in_predicate_support(internal) + RETURNS internal + LANGUAGE c +AS 'MODULE_PATHNAME'; + +CREATE FUNCTION ag_catalog.agtype_in_predicate(agtype, agtype) + RETURNS boolean + LANGUAGE c + IMMUTABLE +SUPPORT ag_catalog.agtype_in_predicate_support +PARALLEL SAFE +AS 'MODULE_PATHNAME'; diff --git a/src/backend/parser/cypher_clause.c b/src/backend/parser/cypher_clause.c index 147e3e74e..516f0a88e 100644 --- a/src/backend/parser/cypher_clause.c +++ b/src/backend/parser/cypher_clause.c @@ -1676,12 +1676,7 @@ static Query *transform_cypher_list_comprehension(cypher_parsestate *cpstate, (AttrNumber) child_pstate->p_next_resno++, list_comp->varname, false); - qual = transform_cypher_expr(child_cpstate, list_comp->where, - EXPR_KIND_WHERE); - if (qual) - { - qual = coerce_to_boolean(child_pstate, qual, "WHERE"); - } + qual = transform_cypher_where(child_cpstate, list_comp->where); query->targetList = lappend(query->targetList, te); query->jointree = makeFromExpr(child_pstate->p_joinlist, (Node *) qual); @@ -2032,12 +2027,7 @@ static Query *transform_cypher_predicate_function(cypher_parsestate *cpstate, setNamespaceLateralState(child_pstate->p_namespace, false, true); /* Transform the predicate expression */ - pred = transform_cypher_expr(child_cpstate, pred_func->where, - EXPR_KIND_WHERE); - if (pred) - { - pred = coerce_to_boolean(child_pstate, pred, "WHERE"); - } + pred = transform_cypher_where(child_cpstate, pred_func->where); /* * Build a CASE expression that preserves three-valued NULL semantics. @@ -3812,8 +3802,7 @@ static Query *transform_cypher_clause_with_where(cypher_parsestate *cpstate, query->rtable = pstate->p_rtable; query->rteperminfos = pstate->p_rteperminfos; - where_qual = transform_cypher_expr(cpstate, where, EXPR_KIND_WHERE); - where_qual = coerce_to_boolean(pstate, where_qual, "WHERE"); + where_qual = transform_cypher_where(cpstate, where); query->jointree = makeFromExpr(pstate->p_joinlist, where_qual); assign_query_collations(pstate, query); @@ -4067,9 +4056,7 @@ static RangeTblEntry *transform_cypher_optional_match_clause(cypher_parsestate * { Node *where_qual; - where_qual = transform_cypher_expr(cpstate, saved_where, - EXPR_KIND_WHERE); - where_qual = coerce_to_boolean(pstate, where_qual, "WHERE"); + where_qual = transform_cypher_where(cpstate, saved_where); j->quals = where_qual; } @@ -4673,21 +4660,13 @@ static void transform_match_pattern(cypher_parsestate *cpstate, Query *query, { Expr *where_qual; - where_qual = (Expr *)transform_cypher_expr(cpstate, where, - EXPR_KIND_WHERE); + where_qual = (Expr *)transform_cypher_where(cpstate, where); if (expr == NULL) { expr = where_qual; } else { - /* - * coerce the WHERE clause to a boolean before AND with the property - * constraints, otherwise there could be evaluation issues. - */ - where_qual = (Expr *)coerce_to_boolean(pstate, (Node *)where_qual, - "WHERE"); - expr = makeBoolExpr(AND_EXPR, list_make2(expr, where_qual), -1); } } diff --git a/src/backend/parser/cypher_expr.c b/src/backend/parser/cypher_expr.c index 7e4f44600..0ec08dce8 100644 --- a/src/backend/parser/cypher_expr.c +++ b/src/backend/parser/cypher_expr.c @@ -75,7 +75,10 @@ static Node *transform_cypher_bool_const(cypher_parsestate *cpstate, cypher_bool_const *bc); static Node *transform_cypher_integer_const(cypher_parsestate *cpstate, cypher_integer_const *ic); -static Node *transform_AEXPR_IN(cypher_parsestate *cpstate, A_Expr *a); +static Node *transform_AEXPR_IN(cypher_parsestate *cpstate, A_Expr *a, + bool as_predicate); +static Node *transform_cypher_bool_arg(cypher_parsestate *cpstate, Node *expr, + const char *construct_name); static Node *transform_cypher_param(cypher_parsestate *cpstate, cypher_param *cp); static Node *transform_cypher_map(cypher_parsestate *cpstate, cypher_map *cm); @@ -138,6 +141,41 @@ Node *transform_cypher_expr(cypher_parsestate *cpstate, Node *expr, return result; } +/* Transform WHERE expressions in a context that requires a SQL boolean. */ +Node *transform_cypher_where(cypher_parsestate *cpstate, Node *expr) +{ + ParseState *pstate = (ParseState *)cpstate; + ParseExprKind old_expr_kind = pstate->p_expr_kind; + Node *result; + + pstate->p_expr_kind = EXPR_KIND_WHERE; + result = transform_cypher_bool_arg(cpstate, expr, "WHERE"); + pstate->p_expr_kind = old_expr_kind; + + return result; +} + +static Node *transform_cypher_bool_arg(cypher_parsestate *cpstate, Node *expr, + const char *construct_name) +{ + Node *result; + + if (expr == NULL) + return NULL; + + /* + * Use the boolean form only where a boolean is required. In other + * expressions, a parameterized IN must still return agtype. + */ + if (IsA(expr, A_Expr) && ((A_Expr *)expr)->kind == AEXPR_IN && + is_ag_node(((A_Expr *)expr)->rexpr, cypher_param)) + result = transform_AEXPR_IN(cpstate, (A_Expr *)expr, true); + else + result = transform_cypher_expr_recurse(cpstate, expr); + + return coerce_to_boolean((ParseState *)cpstate, result, construct_name); +} + static Node *transform_cypher_expr_recurse(cypher_parsestate *cpstate, Node *expr) { @@ -164,7 +202,7 @@ static Node *transform_cypher_expr_recurse(cypher_parsestate *cpstate, case AEXPR_OP: return transform_AEXPR_OP(cpstate, a); case AEXPR_IN: - return transform_AEXPR_IN(cpstate, a); + return transform_AEXPR_IN(cpstate, a, false); default: ereport(ERROR, (errmsg_internal("unrecognized A_Expr kind: %d", a->kind))); @@ -581,7 +619,8 @@ static Node *transform_cypher_comparison_aexpr_OP(cypher_parsestate *cpstate, } -static Node *transform_AEXPR_IN(cypher_parsestate *cpstate, A_Expr *a) +static Node *transform_AEXPR_IN(cypher_parsestate *cpstate, A_Expr *a, + bool as_predicate) { ParseState *pstate = (ParseState *)cpstate; cypher_list *rexpr; @@ -606,12 +645,14 @@ static Node *transform_AEXPR_IN(cypher_parsestate *cpstate, A_Expr *a) args = lappend(args, transform_cypher_expr_recurse(cpstate, a->rexpr)); args = lappend(args, transform_cypher_expr_recurse(cpstate, a->lexpr)); - /* get the agtype_in_operator function */ - func_in_oid = get_ag_func_oid("agtype_in_operator", 2, AGTYPEOID, - AGTYPEOID); + func_in_oid = get_ag_func_oid(as_predicate ? "agtype_in_predicate" : + "agtype_in_operator", + 2, AGTYPEOID, AGTYPEOID); - func_in_expr = makeFuncExpr(func_in_oid, AGTYPEOID, args, InvalidOid, - InvalidOid, COERCE_EXPLICIT_CALL); + func_in_expr = makeFuncExpr(func_in_oid, + as_predicate ? BOOLOID : AGTYPEOID, + args, InvalidOid, InvalidOid, + COERCE_EXPLICIT_CALL); func_in_expr->location = exprLocation(a->lexpr); @@ -753,7 +794,6 @@ static Node *transform_AEXPR_IN(cypher_parsestate *cpstate, A_Expr *a) static Node *transform_BoolExpr(cypher_parsestate *cpstate, BoolExpr *expr) { - ParseState *pstate = (ParseState *)cpstate; List *args = NIL; const char *opname; ListCell *la; @@ -779,8 +819,7 @@ static Node *transform_BoolExpr(cypher_parsestate *cpstate, BoolExpr *expr) { Node *arg = lfirst(la); - arg = transform_cypher_expr_recurse(cpstate, arg); - arg = coerce_to_boolean(pstate, arg, opname); + arg = transform_cypher_bool_arg(cpstate, arg, opname); args = lappend(args, arg); } diff --git a/src/backend/utils/adt/agtype.c b/src/backend/utils/adt/agtype.c index 36ca8b36d..56197ceda 100644 --- a/src/backend/utils/adt/agtype.c +++ b/src/backend/utils/adt/agtype.c @@ -42,14 +42,20 @@ #include "catalog/pg_am_d.h" #include "catalog/pg_collation_d.h" #include "catalog/pg_operator_d.h" +#include "commands/defrem.h" #include "funcapi.h" #include "libpq/pqformat.h" #include "miscadmin.h" #include "parser/parse_coerce.h" +#include "parser/parse_oper.h" +#include "nodes/makefuncs.h" #include "nodes/nodes.h" #include "nodes/nodeFuncs.h" +#include "nodes/supportnodes.h" +#include "optimizer/optimizer.h" #include "executor/executor.h" #include "utils/acl.h" +#include "utils/array.h" #include "utils/builtins.h" #include "utils/datum.h" #include "executor/cypher_utils.h" @@ -4943,11 +4949,11 @@ Datum agtype_access_slice(PG_FUNCTION_ARGS) PG_RETURN_POINTER(agt_result); } -PG_FUNCTION_INFO_V1(agtype_in_operator); /* - * Execute function for IN operator + * Evaluate IN with SQL boolean and NULL results. The agtype variant below + * uses the same comparison and NULL handling as the predicate variant. */ -Datum agtype_in_operator(PG_FUNCTION_ARGS) +static Datum agtype_in_bool(FunctionCallInfo fcinfo) { agtype *agt_arg, *agt_item; agtype_iterator *it_array, *it_item; @@ -5088,7 +5094,136 @@ Datum agtype_in_operator(PG_FUNCTION_ARGS) } } - return boolean_to_agtype(result); + PG_RETURN_BOOL(result); +} + +PG_FUNCTION_INFO_V1(agtype_in_operator); + +Datum agtype_in_operator(PG_FUNCTION_ARGS) +{ + Datum result = agtype_in_bool(fcinfo); + + if (fcinfo->isnull) + PG_RETURN_NULL(); + + return boolean_to_agtype(DatumGetBool(result)); +} + +PG_FUNCTION_INFO_V1(agtype_in_predicate); + +Datum agtype_in_predicate(PG_FUNCTION_ARGS) +{ + return agtype_in_bool(fcinfo); +} + +/* + * Build an index condition for a list that was folded to a constant. + * Keep this limited to simple scalar search keys. In particular, mixed + * numeric representations can compare equal in the B-tree, even though IN + * distinguishes them. Do not put them together in a B-tree search array. + */ +static ScalarArrayOpExpr *agtype_in_index_clause(List *args) +{ + Node *list = linitial(args); + Node *item = lsecond(args); + Const *list_const; + agtype *list_value; + agtype_iterator *iter; + agtype_value elem; + Datum *values; + int count = 0; + Oid agtype_oid = AGTYPEOID; + ArrayType *array; + Const *array_const; + + if (!IsA(list, Const) || exprType(item) != agtype_oid) + return NULL; + + list_const = (Const *) list; + if (list_const->consttype != agtype_oid || list_const->constisnull) + return NULL; + + list_value = DATUM_GET_AGTYPE_P(list_const->constvalue); + if (AGT_ROOT_IS_BINARY(list_value) || !AGT_ROOT_IS_ARRAY(list_value) || + AGT_ROOT_IS_SCALAR(list_value) || AGT_ROOT_COUNT(list_value) == 0) + return NULL; + + values = palloc_array(Datum, AGT_ROOT_COUNT(list_value)); + iter = agtype_iterator_init(&list_value->root); + agtype_iterator_next(&iter, &elem, true); + while (agtype_iterator_next(&iter, &elem, true) == WAGT_ELEM) + { + if (elem.type == AGTV_NULL) + continue; + + if (elem.type != AGTV_INTEGER && elem.type != AGTV_STRING && + elem.type != AGTV_BOOL) + return NULL; + + values[count++] = PointerGetDatum(agtype_value_to_agtype(&elem)); + } + if (count == 0) + return NULL; + + array = construct_array(values, count, agtype_oid, -1, false, TYPALIGN_INT); + array_const = makeConst(AGTYPEARRAYOID, -1, InvalidOid, -1, + PointerGetDatum(array), false, false); + + return (ScalarArrayOpExpr *) make_scalar_array_op(NULL, + list_make2(makeString("ag_catalog"), makeString("=")), true, + item, (Node *) array_const, -1); +} + +PG_FUNCTION_INFO_V1(agtype_in_predicate_support); + +Datum agtype_in_predicate_support(PG_FUNCTION_ARGS) +{ + Node *request = (Node *) PG_GETARG_POINTER(0); + + if (IsA(request, SupportRequestIndexCondition)) + { + SupportRequestIndexCondition *req = + (SupportRequestIndexCondition *) request; + FuncExpr *call = castNode(FuncExpr, req->node); + ScalarArrayOpExpr *clause; + Oid opfamily; + + if (req->indexarg != 1 || req->index->relam != BTREE_AM_OID) + PG_RETURN_POINTER(NULL); + + opfamily = get_opfamily_oid(BTREE_AM_OID, + list_make2(makeString("ag_catalog"), + makeString("agtype_ops_btree")), true); + if (req->opfamily != opfamily) + PG_RETURN_POINTER(NULL); + + clause = agtype_in_index_clause(call->args); + if (clause == NULL || !op_in_opfamily(clause->opno, req->opfamily)) + PG_RETURN_POINTER(NULL); + + /* + * For example, the B-tree can find a float key when looking up an + * integer. The original IN must still check the candidate's type. + */ + req->lossy = true; + PG_RETURN_POINTER(list_make1(clause)); + } + if (IsA(request, SupportRequestSelectivity)) + { + SupportRequestSelectivity *req = (SupportRequestSelectivity *) request; + ScalarArrayOpExpr *clause = agtype_in_index_clause(req->args); + + if (clause == NULL) + PG_RETURN_POINTER(NULL); + + /* Use the indexable predicate's selectivity as an upper estimate. */ + req->selectivity = clause_selectivity(req->root, (Node *) clause, + req->varRelid, req->jointype, + req->sjinfo); + PG_RETURN_POINTER(req); + } + + PG_RETURN_POINTER(NULL); } PG_FUNCTION_INFO_V1(agtype_string_match_starts_with); diff --git a/src/include/parser/cypher_expr.h b/src/include/parser/cypher_expr.h index e069abc6d..33b74bd1e 100644 --- a/src/include/parser/cypher_expr.h +++ b/src/include/parser/cypher_expr.h @@ -29,6 +29,7 @@ Node *transform_cypher_expr(cypher_parsestate *cpstate, Node *expr, ParseExprKind expr_kind); +Node *transform_cypher_where(cypher_parsestate *cpstate, Node *expr); Node *make_properties_expr(Node *prop_var); bool is_vertex_or_edge(Node *node); Node *extract_field_from_record(Node *node, char *field_name);