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

//! Edges whose ends lie in two node types, on a small pet register in one id space (as a
//! set's id space hands it, kleene-gar's `IdSpace`): Person ids 0..3, Pet ids 3..6, though
//! each type's own rows are 0..3. Every answer is checked against a plain loop over the
//! edges by id. The same shapes in a catalog of vertex tables, where a node is its row, are
//! refused by name.

use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::sync::Arc;

use arrow_array::{ArrayRef, UInt32Array, UInt64Array};
use kleene_gql::{Catalog, Entity, Params, Table, lower_with, parse};
use kleene_plan::{Datum, Engine, Facts, Source};
use kleene_sparse::{CpuBackend, CpuDevice};

const PET_BASE: u64 = 3;
/// Person row -> Pet row, `since`.
const OWNS: [(u64, u64, u64); 5] = [
    (0, 0, 2019),
    (0, 1, 2021),
    (1, 0, 2020),
    (1, 2, 2018),
    (2, 2, 2022),
];
/// Person row -> Person row.
const KNOWS: [(u64, u64); 2] = [(0, 1), (1, 2)];
/// Pet row -> Person row.
const LIKES: [(u64, u64); 3] = [(0, 1), (1, 0), (2, 2)];

fn ids(xs: impl IntoIterator<Item = u64>) -> Source {
    Source::Facts(Facts::from_rows(1, xs.into_iter().map(|x| [x])).unwrap())
}

fn pairs(es: Vec<(u64, u64)>) -> Source {
    Source::Facts(Facts::from_rows(2, es.into_iter().map(|(a, b)| [a, b])).unwrap())
}

/// The register in one id space: every node and edge by id.
fn catalog() -> Catalog {
    let mut c = Catalog::new();
    c.label("Person", ids(0..3))
        .label("Pet", ids(PET_BASE..PET_BASE + 3))
        .property(
            "Person",
            "age",
            Source::Columns(vec![
                Arc::new(UInt64Array::from(vec![0, 1, 2])) as ArrayRef,
                Arc::new(UInt64Array::from(vec![40, 9, 66])),
            ]),
        )
        .edge("owns", pairs(by_id(&["owns"])))
        .edge_property(
            "owns",
            "since",
            Source::Facts(
                Facts::from_rows(3, OWNS.iter().map(|&(a, b, s)| [a, b + PET_BASE, s])).unwrap(),
            ),
        )
        .edge("knows", pairs(by_id(&["knows"])))
        .edge("likes", pairs(by_id(&["likes"])));
    c
}

/// The register as two vertex tables (each node its row in its table).
fn tables() -> Catalog {
    let rows =
        |n: u32| -> Source { Source::Columns(vec![Arc::new(UInt32Array::from_iter_values(0..n))]) };
    let mut c = Catalog::new();
    c.label("Person", rows(3))
        .label("Pet", rows(3))
        .vertex_table("Person", 0, 3)
        .vertex_table("Pet", PET_BASE, 3)
        .edge(
            "owns",
            pairs(OWNS.iter().map(|&(a, b, _)| (a, b)).collect()),
        )
        .edge_ends("owns", "Person", "Pet")
        .edge("knows", pairs(KNOWS.to_vec()))
        .edge_ends("knows", "Person", "Person")
        .edge("likes", pairs(LIKES.to_vec()))
        .edge_ends("likes", "Pet", "Person");
    c
}

/// The edges of `labels` by id: (from, to).
fn by_id(labels: &[&str]) -> Vec<(u64, u64)> {
    let mut out = Vec::new();
    for l in labels {
        match *l {
            "owns" => out.extend(OWNS.iter().map(|&(a, b, _)| (a, b + PET_BASE))),
            "knows" => out.extend(KNOWS.iter().copied()),
            "likes" => out.extend(LIKES.iter().map(|&(a, b)| (a + PET_BASE, b))),
            _ => unreachable!(),
        }
    }
    out
}

fn is_person(id: u64) -> bool {
    id < PET_BASE
}

/// Either way: each edge and its reverse.
fn both(es: &[(u64, u64)]) -> Vec<(u64, u64)> {
    es.iter().flat_map(|&(a, b)| [(a, b), (b, a)]).collect()
}

/// Rows as a sorted bag: one row per match (a pair by two labels, or either way both
/// ways, is two).
fn set(rows: impl IntoIterator<Item = Vec<u64>>) -> Vec<Vec<u64>> {
    let mut v: Vec<Vec<u64>> = rows.into_iter().collect();
    v.sort_unstable();
    v
}

async fn run(text: &str) -> Table {
    let l = lower_with(&parse(text).unwrap(), &catalog(), &Params::new()).unwrap();
    let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(2));
    l.run(&e).await.unwrap()
}

/// The rows as a sorted bag.
async fn rows_of(text: &str) -> Vec<Vec<u64>> {
    set(run(text).await.rows)
}

#[tokio::test]
async fn either_way_between_two_tables() {
    let want = |from_person: bool| {
        set(both(&by_id(&["owns"]))
            .into_iter()
            .filter(|&(a, _)| is_person(a) == from_person)
            .map(|(a, b)| vec![a, b]))
    };
    let got = rows_of("MATCH (a:Pet)-[:owns]-(b:Person) RETURN id(a), id(b)").await;
    assert_eq!(got, want(false));
    let got = rows_of("MATCH (a:Person)-[:owns]-(b) RETURN id(a), id(b)").await;
    assert_eq!(got, want(true));
    let got = rows_of("MATCH (a)-[:owns]-(b) RETURN id(a), id(b)").await;
    assert_eq!(
        got,
        set(both(&by_id(&["owns"])).into_iter().map(|(a, b)| vec![a, b]))
    );
    // Pets owned by a person who owns pet 0 (two edges either way through a pet).
    let got = rows_of(
        "MATCH (x:Pet)-[:owns]-(p:Person)-[:owns]-(y:Pet) WHERE id(x) = 3 RETURN DISTINCT id(y)",
    )
    .await;
    let owners: BTreeSet<u64> = OWNS.iter().filter(|o| o.1 == 0).map(|o| o.0).collect();
    let want = set(OWNS
        .iter()
        .filter(|o| owners.contains(&o.0))
        .map(|o| vec![o.1 + PET_BASE]));
    let mut want = want;
    want.dedup();
    assert_eq!(got, want);
}

#[tokio::test]
async fn a_union_of_edge_labels_with_ends_in_two_tables() {
    let es = by_id(&["owns", "knows"]);
    let got = rows_of("MATCH (a:Person)-[:owns|knows]->(b:Person) RETURN id(a), id(b)").await;
    let want = set(es
        .iter()
        .filter(|e| is_person(e.1))
        .map(|&(a, b)| vec![a, b]));
    assert_eq!(got, want);
    let got = rows_of("MATCH (a:Person)-[:owns|knows]->(b) RETURN id(a), id(b)").await;
    assert_eq!(got, set(es.iter().map(|&(a, b)| vec![a, b])));
    // No label on the edge: every edge label.
    let got = rows_of("MATCH (a)-[]->(b:Person) RETURN id(a), id(b)").await;
    let all = by_id(&["owns", "knows", "likes"]);
    assert_eq!(
        got,
        set(all
            .iter()
            .filter(|e| is_person(e.1))
            .map(|&(a, b)| vec![a, b]))
    );
}

#[tokio::test]
async fn either_way_and_a_union_together() {
    let es = both(&by_id(&["owns", "likes"]));
    let got = rows_of("MATCH (a)-[:owns|likes]-(b:Person) RETURN id(a), id(b)").await;
    let want = set(es
        .iter()
        .filter(|e| is_person(e.1))
        .map(|&(a, b)| vec![a, b]));
    assert_eq!(got, want);
    let got = rows_of("MATCH (a:Pet)-[:owns|likes]-(b) RETURN id(a), id(b)").await;
    let want = set(es
        .iter()
        .filter(|e| !is_person(e.0))
        .map(|&(a, b)| vec![a, b]));
    assert_eq!(got, want);
}

/// Breadth-first levels from `s` along `es` (`s` itself at 0).
fn levels(es: &[(u64, u64)], s: u64) -> BTreeMap<u64, u64> {
    let mut d = BTreeMap::from([(s, 0)]);
    let mut q = VecDeque::from([s]);
    while let Some(x) = q.pop_front() {
        for &(a, b) in es {
            if a == x && !d.contains_key(&b) {
                d.insert(b, d[&x] + 1);
                q.push_back(b);
            }
        }
    }
    d
}

/// The nodes `+` reaches from `s` (one edge or more).
fn reach(es: &[(u64, u64)], s: u64) -> BTreeSet<u64> {
    let mut seen = BTreeSet::new();
    let mut q: VecDeque<u64> = es.iter().filter(|e| e.0 == s).map(|e| e.1).collect();
    while let Some(x) = q.pop_front() {
        if seen.insert(x) {
            q.extend(es.iter().filter(|e| e.0 == x).map(|e| e.1));
        }
    }
    seen
}

#[tokio::test]
async fn a_variable_length_edge_across_two_tables() {
    let es = by_id(&["owns", "likes"]);
    for s in 0..3 {
        // Ends at a person only.
        let q = format!(
            "MATCH (a:Person)-[:owns|likes]->+(b:Person) WHERE id(a) = {s} RETURN DISTINCT id(b)"
        );
        let want = set(reach(&es, s)
            .into_iter()
            .filter(|&x| is_person(x))
            .map(|x| vec![x]));
        assert_eq!(rows_of(&q).await, want, "{s} to a person");
        let q =
            format!("MATCH (a:Person)-[:owns|likes]->+(b) WHERE id(a) = {s} RETURN DISTINCT id(b)");
        let got = rows_of(&q).await;
        assert_eq!(got, set(reach(&es, s).into_iter().map(|x| vec![x])), "{s}");
    }
    // One label whose ends differ: a second `owns` cannot follow the first.
    let got = rows_of("MATCH (a:Person)-[:owns]->+(b) RETURN DISTINCT id(a), id(b)").await;
    assert_eq!(
        got,
        set(by_id(&["owns"]).into_iter().map(|(a, b)| vec![a, b]))
    );
    // Two to three edges along owns then likes, round and round.
    let q = "MATCH (a:Person)-[:owns|likes]->{2,3}(b) WHERE id(a) = 0 RETURN DISTINCT id(b)";
    let mut want = BTreeSet::new();
    let mut front = BTreeSet::from([0u64]);
    for k in 1..=3 {
        front = front
            .iter()
            .flat_map(|&x| es.iter().filter(move |e| e.0 == x).map(|e| e.1))
            .collect();
        if k >= 2 {
            want.extend(front.iter().map(|&x| vec![x]));
        }
    }
    assert_eq!(rows_of(q).await, want.into_iter().collect::<Vec<_>>());
}

#[tokio::test]
async fn a_shortest_path_across_two_tables() {
    let es = by_id(&["owns", "likes"]);
    for s in 0..3 {
        let q = format!(
            "MATCH p = ANY SHORTEST (a:Person)-[:owns|likes]->+(b:Pet) WHERE id(a) = {s} \
             RETURN id(b), length(p)"
        );
        let want = set(levels(&es, s)
            .into_iter()
            .filter(|&(x, _)| !is_person(x))
            .map(|(x, d)| vec![x, d]));
        assert_eq!(rows_of(&q).await, want, "{s}");
    }
}

#[tokio::test]
async fn label_alternatives_and_two_labels_across_tables() {
    let got = rows_of("MATCH (n:Person|Pet) RETURN count(*)").await;
    assert_eq!(got, set([vec![6]]));
    let got = rows_of("MATCH (n:Person|Pet) RETURN id(n)").await;
    assert_eq!(got, set((0..6).map(|i| vec![i])));
    // No node is a person and a pet.
    let got = rows_of("MATCH (n:Person), (n:Pet) RETURN count(*)").await;
    assert_eq!(got, set([vec![0]]));
    // Alternatives at an edge end: only the pets like.
    let got = rows_of("MATCH (a:Person|Pet)-[:likes]->(b) RETURN id(a), id(b)").await;
    assert_eq!(
        got,
        set(by_id(&["likes"]).into_iter().map(|(a, b)| vec![a, b]))
    );
}

#[tokio::test]
async fn edge_properties_and_whole_edges_either_way() {
    // The pet's side: each ownership once, its own year.
    let t = run("MATCH (a:Pet)-[e:owns]-(b:Person) RETURN id(a), id(b), e.since").await;
    let got = set(t.rows.iter().cloned());
    assert_eq!(got.len(), t.rows.len());
    let want = set(OWNS.iter().map(|&(p, q, s)| vec![q + PET_BASE, p, s]));
    assert_eq!(got, want);
    // Whole edges as stored: from the person to the pet.
    let t = run("MATCH (a:Pet)-[e:owns]-(b:Person) WHERE id(a) = 3 RETURN id(b), e").await;
    let mut got: Vec<(u64, Entity)> = (0..t.rows.len())
        .map(|r| (t.rows[r][0], t.entity(r, 1).expect("a whole edge").clone()))
        .collect();
    got.sort_by_key(|g| g.0);
    let want: Vec<(u64, Entity)> = OWNS
        .iter()
        .filter(|o| o.1 == 0)
        .map(|&(p, q, s)| {
            (
                p,
                Entity::Edge {
                    label: "owns".into(),
                    start: p,
                    end: q + PET_BASE,
                    properties: vec![("since".into(), Datum::U64(s))],
                },
            )
        })
        .collect();
    assert_eq!(got, want);
    // A path's edges across the two tables.
    let t = run(
        "MATCH p = (a:Person)-[:owns]->(x:Pet)-[:likes]->(b:Person) WHERE id(a) = 1 \
         RETURN id(x), relationships(p)",
    )
    .await;
    let mut got: Vec<(u64, Entity)> = (0..t.rows.len())
        .map(|r| (t.rows[r][0], t.entity(r, 1).expect("edges").clone()))
        .collect();
    got.sort_by_key(|g| g.0);
    let want: Vec<(u64, Entity)> = OWNS
        .iter()
        .filter(|o| o.0 == 1)
        .flat_map(|&(_, q, s)| {
            LIKES.iter().filter(move |l| l.0 == q).map(move |&(_, b)| {
                (
                    q + PET_BASE,
                    Entity::Edges(vec![
                        Entity::Edge {
                            label: "owns".into(),
                            start: 1,
                            end: q + PET_BASE,
                            properties: vec![("since".into(), Datum::U64(s))],
                        },
                        Entity::Edge {
                            label: "likes".into(),
                            start: q + PET_BASE,
                            end: b,
                            properties: vec![],
                        },
                    ]),
                )
            })
        })
        .collect();
    assert_eq!(got, want);
}

#[tokio::test]
async fn nodes_of_two_tables_meet_by_id_elsewhere() {
    // A UNION of a person and a pet column: six nodes, though rows 0..3 of each.
    let got = rows_of("MATCH (a:Person) RETURN a UNION MATCH (a:Pet) RETURN a").await;
    assert_eq!(got, set((0..6).map(|i| vec![i])));
    let got = rows_of(
        "MATCH (a:Person) RETURN a, a.age AS g UNION ALL MATCH (a:Pet)-[:likes]->(c) RETURN a, c.age AS g",
    )
    .await;
    let ages = [40, 9, 66];
    let mut want = set((0..3).map(|i| vec![i, ages[i as usize]]));
    want.extend(
        LIKES
            .iter()
            .map(|&(p, q)| vec![p + PET_BASE, ages[q as usize]]),
    );
    assert_eq!(got, want);
    // Two nodes compared: no person is a pet.
    let got = rows_of("MATCH (a:Person), (b:Pet) WHERE a = b RETURN count(*)").await;
    assert_eq!(got, set([vec![0]]));
    let got = rows_of("MATCH (a:Person), (b:Pet) WHERE a <> b RETURN count(*)").await;
    assert_eq!(got, set([vec![9]]));
    // A node by id through a WITH, then at an edge.
    let got =
        rows_of("MATCH (n:Person|Pet) WITH n MATCH (n)-[:likes]->(b) RETURN id(n), id(b)").await;
    assert_eq!(
        got,
        set(by_id(&["likes"]).into_iter().map(|(a, b)| vec![a, b]))
    );
    // A node through a WITH, then at a union of edge labels.
    let got =
        rows_of("MATCH (a:Person) WITH a MATCH (a)-[:owns|knows]->(b) RETURN id(a), id(b)").await;
    assert_eq!(
        got,
        set(by_id(&["owns", "knows"])
            .into_iter()
            .map(|(a, b)| vec![a, b]))
    );
}

#[test]
fn where_two_vertex_tables_meet_by_row_it_is_refused_by_name() {
    let refused = |q: &str| {
        let e = lower_with(&parse(q).unwrap(), &tables(), &Params::new()).unwrap_err();
        assert!(
            e.to_string().contains("nodes of two vertex tables meet"),
            "{q}: {e}"
        );
    };
    for q in [
        "MATCH (a:Person)-[:owns]-(b) RETURN id(b)",
        "MATCH (a:Pet)-[:owns]-(b:Person) RETURN id(a)",
        "MATCH (a:Person)-[:owns|knows]->(b:Person) RETURN id(b)",
        "MATCH (a)-[]->(b:Person) RETURN id(b)",
        "MATCH (a:Person)-[:owns|likes]->+(b) RETURN DISTINCT id(b)",
        "MATCH (a:Person)-[:owns]->+(b) RETURN DISTINCT id(b)",
        "MATCH p = ANY SHORTEST (a:Person)-[:owns|likes]->+(b:Pet) RETURN id(b), length(p)",
        "MATCH (n:Person|Pet) RETURN count(*)",
        "MATCH (n:Person), (n:Pet) RETURN count(*)",
        "MATCH (a:Pet)-[:knows]->(b) RETURN id(b)",
        "MATCH (a:Person), (b:Pet) WHERE a = b RETURN count(*)",
        "MATCH (a:Person) RETURN a UNION MATCH (a:Pet) RETURN a",
        "MATCH (n) WITH n MATCH (n)-[:likes]->(b) RETURN id(b)",
    ] {
        refused(q);
    }
    // Within one table pair it runs, by row.
    let q = parse("MATCH (a:Person)-[:knows]-(b:Person) RETURN id(a), id(b)").unwrap();
    assert!(lower_with(&q, &tables(), &Params::new()).is_ok());
    let q = parse("MATCH (a:Person)-[:owns]->(b) RETURN id(b)").unwrap();
    assert!(lower_with(&q, &tables(), &Params::new()).is_ok());
}