diesel_ltree icon indicating copy to clipboard operation
diesel_ltree copied to clipboard

Contains_any with subquery as input is not possible

Open mlesin opened this issue 2 years ago • 0 comments

I'm trying to implement query like this:

SELECT *
FROM my_tree mt
WHERE  mt."path" @> ANY
    (
        SELECT mt2."path"
        FROM my_tree mt2
        WHERE mt2."path" <@ 'root.archaea.thermoprotei' 
    )

(example is based on test scheme of ltree_diesel, please ignore it's meaningless by itself in this case)

The main thing is I need ability to pass a subquery into contains_any() operator for path, which is correct SQL, but I'm failing to do so with diesel.

Here is rust code which fails to compile:

    let mt2 = diesel::alias!(my_tree as mt2);
    let subquery = mt2
        .filter(
            mt2.field(my_tree::path)
                .contained_by(text2ltree("root.archaea.thermoprotei")),
        )
        .select(mt2.field(my_tree::path))
        .into_boxed();

    let results = my_tree::table
        .select((my_tree::id, ltree2text(my_tree::path)))
        .filter(my_tree::path.contains_any(subquery)) // <-- Here I need to add subquery
        .order(my_tree::id)
        .load::<MyTree>(&mut connection)
        .unwrap()
        .into_iter()
        .map(|t| t.path)
        .collect::<Vec<_>>();

Similar thing working fine in diesel with regular types, for example, if subquery selects from 'id', it's working correctly with something like .filter(my_tree::id.eq_any(subquery))

I've tried to dive into details of implementation to create pull request but it seems I'm too incompetent in how to make it right.

mlesin avatar Nov 05 '22 19:11 mlesin