Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-gql/tests/lists.rs

//! A list property read with `UNWIND n.c AS x` (a node's) or `UNWIND e.c AS x` (an edge's):
//! each row before once per element of the list, `x` the element, through the catalog's
//! list relation (`Catalog::list_property`, `list_edge_property`: (id, position, value) and
//! (from, to, position, value) rows), the one Datalog reads by name. An empty or null list
//! gives no row, a null element is null, equal elements each a row. Each answer against a
//! plain loop over the same lists.

use std::sync::Arc;

use arrow_array::{ArrayRef, Int64Array, StringArray, UInt64Array};
use kleene_gql::{Catalog, Params, lower_rows, parse};
use kleene_plan::{Datum, Engine, Facts, Rows, Source, Type};
use kleene_sparse::{CpuBackend, CpuDevice};

/// `N.tags` per node 0..4: node 2's list null (no row, as an empty one).
fn tags() -> Vec<Vec<Option<&'static str>>> {
    vec![
        vec![Some("a"), Some("b"), Some("a")],
        vec![],
        vec![],
        vec![Some("c"), None],
    ]
}

/// `N.w` per node 0..4.
fn w() -> Vec<Vec<i64>> {
    vec![vec![-1, 2], vec![], vec![5], vec![]]
}

/// `N.nums` per node 0..4: unsigned elements, some null (no row: an unsigned value has none).
fn nums() -> Vec<Vec<Option<u64>>> {
    vec![
        vec![Some(7), None, Some(9)],
        vec![],
        vec![None],
        vec![Some(2)],
    ]
}

const EDGES: [(u64, u64); 3] = [(0, 1), (1, 2), (3, 3)];

/// `E.hops` per edge of `EDGES`.
fn hops() -> Vec<Vec<u64>> {
    vec![vec![7], vec![], vec![8, 9, 8]]
}

/// Edges of label F by their rows: two edges 0->1 (rows 0 and 1), one 2->3 (row 2).
const F_EDGES: [(u64, u64); 3] = [(0, 1), (0, 1), (2, 3)];

/// `F.hops` per row of `F_EDGES`.
fn f_hops() -> Vec<Vec<u64>> {
    vec![vec![1, 2], vec![3], vec![4]]
}

fn col(v: Vec<u64>) -> ArrayRef {
    Arc::new(UInt64Array::from(v))
}

/// (row, position) of each element of `lists`.
fn at<T>(lists: &[Vec<T>]) -> (Vec<u64>, Vec<u64>) {
    let mut rows = Vec::new();
    let mut pos = Vec::new();
    for (r, l) in lists.iter().enumerate() {
        for k in 0..l.len() {
            rows.push(r as u64);
            pos.push(k as u64);
        }
    }
    (rows, pos)
}

fn catalog() -> Catalog {
    let mut c = Catalog::new();
    c.label("N", Source::Columns(vec![col((0..4).collect())]))
        .edge(
            "E",
            Source::Facts(Facts::from_rows(2, EDGES.iter().map(|&(a, b)| [a, b])).unwrap()),
        );
    let (ids, pos) = at(&tags());
    let values: StringArray = tags().into_iter().flatten().collect();
    c.list_property(
        "N",
        "tags",
        Source::Columns(vec![col(ids), col(pos), Arc::new(values)]),
        Type::Str,
    );
    let (ids, pos) = at(&w());
    let values: Int64Array = w().into_iter().flatten().collect();
    c.list_property(
        "N",
        "w",
        Source::Columns(vec![col(ids), col(pos), Arc::new(values)]),
        Type::I64,
    );
    let (nodes, pos) = at(&nums());
    let values: UInt64Array = nums().into_iter().flatten().collect();
    c.list_property(
        "N",
        "nums",
        Source::Columns(vec![col(nodes), col(pos), Arc::new(values)]),
        Type::U64,
    );
    let (es, pos) = at(&hops());
    let from = es.iter().map(|&e| EDGES[e as usize].0).collect();
    let to = es.iter().map(|&e| EDGES[e as usize].1).collect();
    let values = hops().into_iter().flatten().collect();
    c.list_edge_property(
        "E",
        "hops",
        Source::Columns(vec![col(from), col(to), col(pos), col(values)]),
        Type::U64,
    );
    // F: by rows (E@row, E@row.hops) and by pairs (the pair 0->1 once)
    let rows: Vec<u64> = (0..F_EDGES.len() as u64).collect();
    let (from, to): (Vec<u64>, Vec<u64>) = F_EDGES.iter().copied().unzip();
    c.edge(
        "F",
        Source::Facts(Facts::from_rows(2, [[0u64, 1], [2, 3]]).unwrap()),
    )
    .edge_rows("F", Source::Columns(vec![col(rows), col(from), col(to)]));
    let (es, pos) = at(&f_hops());
    let from = es.iter().map(|&e| F_EDGES[e as usize].0).collect();
    let to = es.iter().map(|&e| F_EDGES[e as usize].1).collect();
    let values: Vec<u64> = f_hops().into_iter().flatten().collect();
    // (by pairs each value plus 100: an answer read by pairs, not by rows, shows)
    c.list_edge_property(
        "F",
        "hops",
        Source::Columns(vec![
            col(from),
            col(to),
            col(pos.clone()),
            col(values.iter().map(|v| v + 100).collect()),
        ]),
        Type::U64,
    )
    .list_edge_row_property(
        "F",
        "hops",
        Source::Columns(vec![col(es), col(pos), col(values)]),
        Type::U64,
    );
    c
}

async fn rows(q: &str, mode: Rows) -> Vec<Vec<Datum>> {
    let c = catalog();
    let l = lower_rows(
        &parse(q).unwrap_or_else(|e| panic!("{q}: {e}")),
        &c,
        &Params::new(),
        mode,
    )
    .unwrap_or_else(|e| panic!("{q}: {e}"));
    let mut out = Vec::new();
    for threads in [1, 2, 4] {
        let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(threads));
        let r = sorted(
            l.run_typed(&e)
                .await
                .unwrap_or_else(|e| panic!("{q}: {e}"))
                .rows,
        );
        if threads > 1 {
            assert_eq!(r, out, "{q}: {threads} threads");
        }
        out = r;
    }
    out
}

fn sorted(mut r: Vec<Vec<Datum>>) -> Vec<Vec<Datum>> {
    r.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}")));
    r
}

fn u(x: u64) -> Datum {
    Datum::U64(x)
}

#[tokio::test]
async fn unwind_a_node_list_property() {
    let q = "MATCH (n:N) UNWIND n.tags AS x RETURN n, x";
    let mut want = Vec::new();
    for (n, l) in tags().iter().enumerate() {
        for x in l {
            want.push(vec![
                u(n as u64),
                x.map_or(Datum::Null, |s| Datum::Str(s.into())),
            ]);
        }
    }
    let want = sorted(want);
    assert_eq!(want.len(), 5);
    assert_eq!(rows(q, Rows::Bag).await, want);
    // the distinct rows: node 0's two "a" one row
    let mut distinct = want.clone();
    distinct.dedup();
    assert_eq!(rows(q, Rows::Distinct).await, distinct);

    let q = "MATCH (n:N) UNWIND n.w AS x RETURN n, x";
    let mut want = Vec::new();
    for (n, l) in w().iter().enumerate() {
        for &x in l {
            want.push(vec![u(n as u64), Datum::I64(x)]);
        }
    }
    assert_eq!(rows(q, Rows::Bag).await, sorted(want));
}

#[tokio::test]
async fn unwind_an_edge_list_property() {
    let mut want = Vec::new();
    for (e, l) in hops().iter().enumerate() {
        let (a, b) = EDGES[e];
        for &h in l {
            want.push(vec![u(a), u(b), u(h)]);
        }
    }
    let want = sorted(want);
    let q = "MATCH (a:N)-[e:E]->(b:N) UNWIND e.hops AS h RETURN a, b, h";
    assert_eq!(rows(q, Rows::Bag).await, want);
    // ends with no name
    let q = "MATCH ()-[e:E]->() UNWIND e.hops AS h RETURN h";
    let only: Vec<Vec<Datum>> = sorted(want.iter().map(|r| vec![r[2].clone()]).collect());
    assert_eq!(rows(q, Rows::Bag).await, only);
}

/// Two edges between the same two nodes, read by their rows (`F@row.hops`): each edge's
/// list once, not each list once per edge.
#[tokio::test]
async fn unwind_the_lists_of_parallel_edges_by_row() {
    let mut want = Vec::new();
    for (e, l) in f_hops().iter().enumerate() {
        let (a, b) = F_EDGES[e];
        for &h in l {
            want.push(vec![u(a), u(b), u(h)]);
        }
    }
    let q = "MATCH (a:N)-[e:F]->(b:N) UNWIND e.hops AS h RETURN a, b, h";
    assert_eq!(rows(q, Rows::Bag).await, sorted(want));
}

#[test]
fn a_list_property_as_one_value_is_refused_by_name() {
    let c = catalog();
    for q in [
        "MATCH (n:N) RETURN n.tags",
        "MATCH (a:N)-[e:E]->(b:N) RETURN e.hops",
    ] {
        let err = lower_rows(&parse(q).unwrap(), &c, &Params::new(), Rows::Bag)
            .err()
            .unwrap_or_else(|| panic!("{q}: not refused"))
            .to_string();
        assert!(
            err.contains("a list") && err.contains("UNWIND"),
            "{q}: {err}"
        );
    }
}

/// An unsigned list with null elements: `UNWIND n.nums AS x` gives a row per element that
/// has a value, a null one none (an unsigned value has no null).
#[tokio::test]
async fn unwind_an_unsigned_list_with_null_elements() {
    let q = "MATCH (n:N) UNWIND n.nums AS x RETURN n, x";
    let mut want = Vec::new();
    for (n, l) in nums().iter().enumerate() {
        for x in l.iter().flatten() {
            want.push(vec![u(n as u64), u(*x)]);
        }
    }
    let want = sorted(want);
    assert_eq!(want.len(), 3);
    assert_eq!(rows(q, Rows::Bag).await, want);
}