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/edge_rows.rs

//! An edge variable's properties read per edge, by the edge's row (the catalog's `E@row`
//! and `E@row.p`): two edges of one label between the same two nodes are two matches, each
//! with its own values, against a plain loop over the same edges.

use std::sync::Arc;

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

/// Calls (from, to, address, kind): three from 0 to 1, a self loop on 2.
const CALLS: [(u64, u64, u64, &str); 5] = [
    (0, 1, 100, "direct"),
    (1, 2, 300, "direct"),
    (0, 1, 200, "virtual"),
    (2, 2, 500, "tail"),
    (0, 1, 400, "direct"),
];

/// The one `JUMPS` edge, from 0 to 1: (address, kind).
const JUMP: (u64, &str) = (700, "jump");

/// The catalog of a set: `CALLS` as pairs (each pair once) with its properties as (from,
/// to, value), and by its rows.
fn catalog() -> Catalog {
    let mut pairs: Vec<[u64; 2]> = CALLS.iter().map(|c| [c.0, c.1]).collect();
    pairs.sort_unstable();
    pairs.dedup();
    let col = |a: ArrayRef| a;
    let rows = || {
        col(Arc::new(UInt64Array::from_iter_values(
            0..CALLS.len() as u64,
        )))
    };
    let mut c = Catalog::new();
    c.label(
        "Func",
        Source::Facts(Facts::from_rows(1, (0..3u64).map(|x| [x])).unwrap()),
    )
    .edge("CALLS", Source::Facts(Facts::from_rows(2, pairs).unwrap()))
    .edge_property(
        "CALLS",
        "addr",
        Source::Facts(Facts::from_rows(3, CALLS.iter().map(|c| [c.0, c.1, c.2])).unwrap()),
    )
    .typed_edge_property(
        "CALLS",
        "kind",
        Source::Columns(vec![
            col(Arc::new(UInt64Array::from_iter_values(
                CALLS.iter().map(|c| c.0),
            ))),
            col(Arc::new(UInt64Array::from_iter_values(
                CALLS.iter().map(|c| c.1),
            ))),
            col(Arc::new(StringArray::from_iter_values(
                CALLS.iter().map(|c| c.3),
            ))),
        ]),
        Type::Str,
    )
    .edge_rows(
        "CALLS",
        Source::Facts(
            Facts::from_rows(
                3,
                CALLS.iter().enumerate().map(|(r, c)| [r as u64, c.0, c.1]),
            )
            .unwrap(),
        ),
    )
    .edge_row_property(
        "CALLS",
        "addr",
        Source::Facts(
            Facts::from_rows(2, CALLS.iter().enumerate().map(|(r, c)| [r as u64, c.2])).unwrap(),
        ),
        Type::U64,
    )
    .edge_row_property(
        "CALLS",
        "kind",
        Source::Columns(vec![
            rows(),
            col(Arc::new(StringArray::from_iter_values(
                CALLS.iter().map(|c| c.3),
            ))),
        ]),
        Type::Str,
    );
    // JUMPS: one edge, from 0 to 1 as three of CALLS, its row 0 as CALLS's row 0
    c.edge(
        "JUMPS",
        Source::Facts(Facts::from_rows(2, [[0u64, 1]]).unwrap()),
    )
    .edge_property(
        "JUMPS",
        "addr",
        Source::Facts(Facts::from_rows(3, [[0u64, 1, JUMP.0]]).unwrap()),
    )
    .typed_edge_property(
        "JUMPS",
        "kind",
        Source::Columns(vec![
            col(Arc::new(UInt64Array::from(vec![0u64]))),
            col(Arc::new(UInt64Array::from(vec![1u64]))),
            col(Arc::new(StringArray::from(vec![JUMP.1]))),
        ]),
        Type::Str,
    )
    .edge_rows(
        "JUMPS",
        Source::Facts(Facts::from_rows(3, [[0u64, 0, 1]]).unwrap()),
    )
    .edge_row_property(
        "JUMPS",
        "addr",
        Source::Facts(Facts::from_rows(2, [[0u64, JUMP.0]]).unwrap()),
        Type::U64,
    )
    .edge_row_property(
        "JUMPS",
        "kind",
        Source::Columns(vec![
            col(Arc::new(UInt64Array::from(vec![0u64]))),
            col(Arc::new(StringArray::from(vec![JUMP.1]))),
        ]),
        Type::Str,
    );
    c
}

fn engine() -> Engine<CpuBackend> {
    Engine::new(CpuDevice::new(2))
}

/// The rows of `q`, each as text, sorted.
async fn rows(q: &str) -> Vec<String> {
    let l = lower(&parse(q).unwrap(), &catalog()).unwrap_or_else(|e| panic!("{q}: {e}"));
    let t = l
        .run_typed(&engine())
        .await
        .unwrap_or_else(|e| panic!("{q}: {e}"));
    let mut out: Vec<String> = t.rows.iter().map(|r| format!("{r:?}")).collect();
    out.sort();
    out
}

fn text(rows: impl IntoIterator<Item = Vec<Datum>>) -> Vec<String> {
    let mut out: Vec<String> = rows.into_iter().map(|r| format!("{r:?}")).collect();
    out.sort();
    out
}

/// `RETURN r.addr, r.kind`: one row per edge, each address with its own kind (before: the
/// three calls from 0 to 1 gave each of their addresses with each of their kinds).
#[tokio::test]
async fn each_edge_returns_its_own_values() {
    let got = rows("MATCH (a:Func)-[r:CALLS]->(b:Func) RETURN id(a), id(b), r.addr, r.kind").await;
    let want = text(CALLS.iter().map(|c| {
        vec![
            Datum::U64(c.0),
            Datum::U64(c.1),
            Datum::U64(c.2),
            Datum::Str(c.3.into()),
        ]
    }));
    assert_eq!(got, want);
}

/// `count(*)` by an edge property counts edges (before: one per pair of nodes).
#[tokio::test]
async fn each_edge_is_a_match_of_its_own() {
    let got = rows("MATCH (a:Func)-[r:CALLS]->(b:Func) RETURN r.kind, count(*)").await;
    let kinds = ["direct", "tail", "virtual"];
    let want = text(kinds.iter().map(|k| {
        let n = CALLS.iter().filter(|c| c.3 == *k).count() as u64;
        vec![Datum::Str((*k).into()), Datum::U64(n)]
    }));
    assert_eq!(got, want);
    let got = rows("MATCH (a:Func)-[r:CALLS]->(b:Func) WHERE r.addr > 150 RETURN count(*)").await;
    let n = CALLS.iter().filter(|c| c.2 > 150).count() as u64;
    assert_eq!(got, text([vec![Datum::U64(n)]]));
}

/// Either way: each edge once each way it is read, a self loop once, its own values.
#[tokio::test]
async fn either_way_each_edge_returns_its_own_values() {
    let got = rows("MATCH (a:Func)-[r:CALLS]-(b:Func) RETURN id(a), id(b), r.addr, r.kind").await;
    let mut want: Vec<Vec<Datum>> = Vec::new();
    for c in CALLS {
        let vals = [Datum::U64(c.2), Datum::Str(c.3.into())];
        want.push([vec![Datum::U64(c.0), Datum::U64(c.1)], vals.to_vec()].concat());
        if c.0 != c.1 {
            want.push([vec![Datum::U64(c.1), Datum::U64(c.0)], vals.to_vec()].concat());
        }
    }
    assert_eq!(got, text(want));
}

/// Label alternatives: each edge of each label once, its own values (rows of two labels
/// count from 0 each, told apart by their label).
#[tokio::test]
async fn label_alternatives_each_edge_returns_its_own_values() {
    let q = "MATCH (a:Func)-[r:CALLS|JUMPS]->(b:Func) RETURN id(a), id(b), r.addr, r.kind";
    let got = rows(q).await;
    let mut want: Vec<Vec<Datum>> = CALLS
        .iter()
        .map(|c| {
            vec![
                Datum::U64(c.0),
                Datum::U64(c.1),
                Datum::U64(c.2),
                Datum::Str(c.3.into()),
            ]
        })
        .collect();
    want.push(vec![
        Datum::U64(0),
        Datum::U64(1),
        Datum::U64(JUMP.0),
        Datum::Str(JUMP.1.into()),
    ]);
    assert_eq!(got, text(want));
    let got = rows("MATCH (a:Func)-[r:CALLS|JUMPS]-(b:Func) RETURN count(r.addr)").await;
    let n = CALLS
        .iter()
        .map(|c| if c.0 == c.1 { 1 } else { 2 })
        .sum::<u64>()
        + 2;
    assert_eq!(got, text([vec![Datum::U64(n)]]));
}