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

//! `id(n)`, nodes with no label, and whole nodes and edges in `RETURN`, on a small library:
//! three vertex tables numbered one after the other (Book 0..5, Reader 5..7, Shelf 7..10),
//! each answer checked against a plain loop over the same rows.

use std::collections::BTreeSet;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

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

/// Books: (pages, title); row = index.
const BOOKS: [(u64, Option<&str>); 5] = [
    (120, Some("Moss")),
    (340, Some("Tide")),
    (90, None),
    (210, Some("Ash")),
    (500, Some("Tide")),
];
/// Readers: (age).
const READERS: [u64; 2] = [31, 47];
/// Shelves: (floor, title).
const SHELVES: [(u64, &str); 3] = [(1, "Tide"), (2, "North"), (2, "South")];
/// Book row -> Shelf row.
const ON: [(u64, u64); 5] = [(0, 0), (1, 0), (2, 1), (3, 2), (4, 2)];
/// Reader row -> Book row, minutes.
const READ: [(u64, u64, u64); 4] = [(0, 1, 30), (0, 3, 12), (1, 1, 45), (1, 4, 60)];

const BASE: [(&str, u64, u64); 3] = [("Book", 0, 5), ("Reader", 5, 2), ("Shelf", 7, 3)];

fn col(a: impl Array + 'static) -> ArrayRef {
    Arc::new(a)
}

fn rows(n: u32) -> ArrayRef {
    col(UInt32Array::from_iter_values(0..n))
}

fn catalog() -> Catalog {
    let mut c = Catalog::new();
    c.label("Book", Source::Columns(vec![rows(5)]))
        .label("Reader", Source::Columns(vec![rows(2)]))
        .label("Shelf", Source::Columns(vec![rows(3)]));
    for (l, b, n) in BASE {
        c.vertex_table(l, b, n);
    }
    c.property(
        "Book",
        "pages",
        Source::Columns(vec![
            rows(5),
            col(UInt64Array::from_iter_values(BOOKS.iter().map(|b| b.0))),
        ]),
    )
    .typed_property(
        "Book",
        "title",
        Source::Columns(vec![
            rows(5),
            col(StringArray::from(
                BOOKS.iter().map(|b| b.1).collect::<Vec<_>>(),
            )),
        ]),
        Type::Str,
    )
    .property(
        "Reader",
        "age",
        Source::Columns(vec![rows(2), col(UInt64Array::from_iter_values(READERS))]),
    )
    .property(
        "Shelf",
        "floor",
        Source::Columns(vec![
            rows(3),
            col(UInt64Array::from_iter_values(SHELVES.iter().map(|s| s.0))),
        ]),
    )
    .typed_property(
        "Shelf",
        "title",
        Source::Columns(vec![
            rows(3),
            col(StringArray::from(
                SHELVES.iter().map(|s| Some(s.1)).collect::<Vec<_>>(),
            )),
        ]),
        Type::Str,
    )
    .edge(
        "on",
        Source::Facts(Facts::from_rows(2, ON.iter().map(|&(a, b)| [a, b])).unwrap()),
    )
    .edge_ends("on", "Book", "Shelf")
    .edge(
        "read",
        Source::Facts(Facts::from_rows(2, READ.iter().map(|&(a, b, _)| [a, b])).unwrap()),
    )
    .edge_ends("read", "Reader", "Book")
    .edge_property(
        "read",
        "minutes",
        Source::Facts(Facts::from_rows(3, READ.iter().map(|&(a, b, m)| [a, b, m])).unwrap()),
    );
    c
}

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

/// The table of `(label, row)` of each id, by the plain numbering.
fn table_of(id: u64) -> Option<(&'static str, u64)> {
    BASE.iter()
        .find(|(_, b, n)| id >= *b && id < b + n)
        .map(|(l, b, _)| (*l, id - b))
}

fn params(ps: &[(&str, u64)]) -> Params {
    ps.iter().map(|&(k, v)| (k.to_string(), v.into())).collect()
}

async fn run(text: &str, ps: &[(&str, u64)]) -> Vec<Vec<u64>> {
    let l = lower_with(&parse(text).unwrap(), &catalog(), &params(ps)).unwrap();
    l.run(&engine()).await.unwrap().rows
}

fn refused(text: &str) -> GqlError {
    let q = parse(text).unwrap();
    lower_with(&q, &catalog(), &Params::new()).unwrap_err()
}

#[tokio::test]
async fn id_equality_finds_one_node_of_any_table() {
    for id in 0..12 {
        let got = run("MATCH (n) WHERE id(n) = $id RETURN id(n)", &[("id", id)]).await;
        let want: Vec<Vec<u64>> = table_of(id).map(|_| vec![id]).into_iter().collect();
        assert_eq!(got, want, "id {id}");
        // With a label: the row of that table only.
        let got = run("MATCH (s:Shelf) WHERE id(s) = $id RETURN s", &[("id", id)]).await;
        let want: Vec<Vec<u64>> = match table_of(id) {
            Some(("Shelf", r)) => vec![vec![r]],
            _ => vec![],
        };
        assert_eq!(got, want, "Shelf id {id}");
    }
}

#[tokio::test]
async fn id_range_lists_rows_with_no_scan() {
    for (start, end) in [(0, 10), (3, 8), (6, 7), (9, 40), (8, 2)] {
        let q = "MATCH (n) WHERE id(n) >= $start AND id(n) < $end RETURN id(n)";
        let got = run(q, &[("start", start), ("end", end)]).await;
        let want: Vec<Vec<u64>> = (start..end.min(10)).map(|i| vec![i]).collect();
        assert_eq!(got, want, "{start}..{end}");
        let l = lower_with(
            &parse(q).unwrap(),
            &catalog(),
            &params(&[("start", start), ("end", end)]),
        )
        .unwrap();
        assert!(
            l.explain().unwrap().contains("(n): id range"),
            "{start}..{end}"
        );
        // A labelled node: its table's rows in the range, with a property.
        let q = "MATCH (s:Shelf) WHERE id(s) >= $start AND id(s) < $end \
                 RETURN id(s), s.floor";
        let got = run(q, &[("start", start), ("end", end)]).await;
        let want: Vec<Vec<u64>> = (start..end)
            .filter_map(|i| match table_of(i) {
                Some(("Shelf", r)) => Some(vec![i, SHELVES[r as usize].0]),
                _ => None,
            })
            .collect();
        assert_eq!(got, want, "Shelf {start}..{end}");
    }
}

#[tokio::test]
async fn id_in_return_and_order_by_over_every_table() {
    let got = run("MATCH (n) RETURN id(n) ORDER BY id(n) DESC LIMIT 4", &[]).await;
    assert_eq!(got, vec![vec![9], vec![8], vec![7], vec![6]]);
    let got = run("MATCH (n) RETURN count(*)", &[]).await;
    assert_eq!(got, vec![vec![10]]);
    let got = run("MATCH (b:Book) RETURN id(b), b.pages ORDER BY b.pages", &[]).await;
    let mut want: Vec<Vec<u64>> = (0..5).map(|r| vec![r, BOOKS[r as usize].0]).collect();
    want.sort_by_key(|r| r[1]);
    assert_eq!(got, want);
    let got = run("MATCH (r:Reader) RETURN id(r) ORDER BY id(r)", &[]).await;
    assert_eq!(got, vec![vec![5], vec![6]]);
}

#[tokio::test]
async fn a_node_with_no_label_reads_a_property_only_some_tables_have() {
    // `pages`: books only.
    let got = run("MATCH (n) WHERE n.pages > 150 RETURN id(n), n.pages", &[]).await;
    let want: Vec<Vec<u64>> = (0..5u64)
        .filter(|&r| BOOKS[r as usize].0 > 150)
        .map(|r| vec![r, BOOKS[r as usize].0])
        .collect();
    assert_eq!(got, want);
    // `title`: books and shelves (a property map on a node with no label).
    let q = parse(r#"MATCH (n {title: "Tide"}) RETURN id(n)"#).unwrap();
    let l = lower_with(&q, &catalog(), &Params::new()).unwrap();
    let got = l.run(&engine()).await.unwrap().rows;
    let mut want: Vec<Vec<u64>> = Vec::new();
    for (r, b) in BOOKS.iter().enumerate() {
        if b.1 == Some("Tide") {
            want.push(vec![r as u64]);
        }
    }
    for (r, s) in SHELVES.iter().enumerate() {
        if s.1 == "Tide" {
            want.push(vec![7 + r as u64]);
        }
    }
    assert_eq!(got, want);
    // `MATCH (n {floor: $f})`: shelves only.
    let got = run("MATCH (n {floor: $f}) RETURN id(n)", &[("f", 2)]).await;
    assert_eq!(got, vec![vec![8], vec![9]]);
}

#[tokio::test]
async fn id_of_a_node_with_no_label_at_an_edge_end() {
    let got = run(
        "MATCH (r:Reader)-[:read]->(b) RETURN id(r), id(b) ORDER BY id(r), id(b)",
        &[],
    )
    .await;
    let want: Vec<Vec<u64>> = READ.iter().map(|&(a, b, _)| vec![5 + a, b]).collect();
    assert_eq!(got, want);
    let got = run("MATCH (b)-[:on]->(s) WHERE id(s) = 9 RETURN id(b)", &[]).await;
    let want: Vec<Vec<u64>> = ON
        .iter()
        .filter(|e| e.1 + 7 == 9)
        .map(|e| vec![e.0])
        .collect();
    assert_eq!(got, want);
}

#[tokio::test]
async fn id_refusals_are_named() {
    let e = refused("MATCH (a:Reader)-[r:read]->(b) RETURN id(r)");
    assert!(e.to_string().contains("id(r) of an edge"), "{e}");
    let e = refused("MATCH (n:Book|Shelf) RETURN id(n)");
    assert!(e.to_string().contains("labels of two vertex tables"), "{e}");
}

#[tokio::test]
async fn one_id_space_reads_every_label_once() {
    // No vertex tables: ids are one space, `id(n)` is the node, `(n)` any node of a label.
    let mut c = Catalog::new();
    let ones = |xs: &[u64]| Source::Facts(Facts::from_rows(1, xs.iter().map(|&x| [x])).unwrap());
    c.label("A", ones(&[1, 2, 3])).label("B", ones(&[3, 4]));
    let q = parse("MATCH (n) WHERE id(n) >= 2 RETURN id(n)").unwrap();
    let l = lower_with(&q, &c, &Params::new()).unwrap();
    let got: BTreeSet<u64> = l
        .run(&engine())
        .await
        .unwrap()
        .rows
        .iter()
        .map(|r| r[0])
        .collect();
    assert_eq!(got, BTreeSet::from([2, 3, 4]));
    let q = parse("MATCH (n) RETURN count(*)").unwrap();
    let l = lower_with(&q, &c, &Params::new()).unwrap();
    assert_eq!(l.run(&engine()).await.unwrap().rows, vec![vec![4]]);
}

/// The whole node of `id`, by the plain tables.
fn node_of(id: u64) -> Entity {
    let s = |x: &str| Datum::Str(x.to_string());
    let (label, r) = table_of(id).unwrap();
    let r = r as usize;
    let properties = match label {
        "Book" => vec![
            ("pages".to_string(), Datum::U64(BOOKS[r].0)),
            ("title".to_string(), BOOKS[r].1.map_or(Datum::Null, s)),
        ],
        "Reader" => vec![("age".to_string(), Datum::U64(READERS[r]))],
        _ => vec![
            ("floor".to_string(), Datum::U64(SHELVES[r].0)),
            ("title".to_string(), s(SHELVES[r].1)),
        ],
    };
    Entity::Node {
        id,
        labels: vec![label.to_string()],
        properties,
    }
}

async fn table(text: &str) -> Table {
    let l = lower_with(&parse(text).unwrap(), &catalog(), &Params::new()).unwrap();
    l.run(&engine()).await.unwrap()
}

/// Column `c`'s whole values, row by row.
fn wholes(t: &Table, c: usize) -> Vec<Entity> {
    (0..t.rows.len())
        .map(|r| t.entity(r, c).expect("a whole value").clone())
        .collect()
}

#[tokio::test]
async fn return_n_gives_the_whole_node() {
    let t = table("MATCH (n) RETURN n").await;
    assert_eq!(wholes(&t, 0), (0..10).map(node_of).collect::<Vec<_>>());
    let t = table("MATCH (b:Book) WHERE b.pages > 100 RETURN b, b.pages").await;
    let want: Vec<Entity> = (0..5u64)
        .filter(|&r| BOOKS[r as usize].0 > 100)
        .map(node_of)
        .collect();
    assert_eq!(wholes(&t, 0), want);
    // The cell keeps the node's value (its row).
    assert_eq!(t.rows[0], vec![0, 120]);
    // An edge end with no label: a row of the table the edge names.
    let t = table("MATCH (b)-[:on]->(s) WHERE id(b) = 3 RETURN s").await;
    assert_eq!(wholes(&t, 0), vec![node_of(7 + ON[3].1)]);
    // Printed whole, nulls as null.
    let t = table("MATCH (b:Book) WHERE id(b) = 2 RETURN b").await;
    assert!(
        t.to_string().contains("(2:Book {pages: 90, title: null})"),
        "{t}"
    );
}

#[tokio::test]
async fn return_r_gives_the_whole_edge() {
    let t = table("MATCH (r:Reader)-[e:read]->(b:Book) RETURN e").await;
    let want: Vec<Entity> = READ
        .iter()
        .map(|&(a, b, m)| Entity::Edge {
            label: "read".into(),
            start: 5 + a,
            end: b,
            properties: vec![("minutes".into(), Datum::U64(m))],
        })
        .collect();
    assert_eq!(wholes(&t, 0), want);
    // Against the edge: the ends as stored.
    let t = table("MATCH (b:Book)<-[e:read]-(r:Reader) WHERE id(b) = 1 RETURN e").await;
    assert_eq!(
        wholes(&t, 0),
        want.iter()
            .filter(|e| matches!(e, Entity::Edge { end: 1, .. }))
            .cloned()
            .collect::<Vec<_>>()
    );
    // Either way between two vertex tables: refused by row (tests/tables.rs runs it in one
    // id space).
    let e = refused("MATCH (r:Reader)-[e:read]-(b:Book) WHERE id(b) = 4 RETURN type(e), e");
    assert!(e.to_string().contains("two vertex tables meet"), "{e}");
}

#[tokio::test]
async fn labels_type_properties_and_a_paths_parts() {
    let t = table("MATCH (n) WHERE id(n) IN [1, 6, 8] RETURN labels(n), properties(n)").await;
    let want: Vec<(Entity, Entity)> = [1, 6, 8]
        .map(|id| match node_of(id) {
            Entity::Node {
                labels, properties, ..
            } => (Entity::Labels(labels), Entity::Properties(properties)),
            _ => unreachable!(),
        })
        .to_vec();
    let got: Vec<(Entity, Entity)> = wholes(&t, 0).into_iter().zip(wholes(&t, 1)).collect();
    assert_eq!(got, want);
    let t =
        table("MATCH (r:Reader)-[e:read]->(b) WHERE id(r) = 6 RETURN type(e), properties(e)").await;
    let want: Vec<(Entity, Entity)> = READ
        .iter()
        .filter(|x| x.0 == 1)
        .map(|x| {
            (
                Entity::Type("read".into()),
                Entity::Properties(vec![("minutes".into(), Datum::U64(x.2))]),
            )
        })
        .collect();
    let got: Vec<(Entity, Entity)> = wholes(&t, 0).into_iter().zip(wholes(&t, 1)).collect();
    assert_eq!(got, want);
    // A path: its nodes' ids and its edges in order.
    let t = table(
        "MATCH p = (r:Reader)-[:read]->(b:Book)-[:on]->(s:Shelf) RETURN nodes(p), relationships(p)",
    )
    .await;
    let mut want: Vec<(Vec<u64>, Entity)> = Vec::new();
    for &(a, b, m) in &READ {
        for &(b2, s) in &ON {
            if b2 == b {
                let read = Entity::Edge {
                    label: "read".into(),
                    start: 5 + a,
                    end: b,
                    properties: vec![("minutes".into(), Datum::U64(m))],
                };
                let on = Entity::Edge {
                    label: "on".into(),
                    start: b,
                    end: 7 + s,
                    properties: vec![],
                };
                want.push((vec![5 + a, b, 7 + s], Entity::Edges(vec![read, on])));
            }
        }
    }
    let got: Vec<(Vec<u64>, Entity)> = (0..t.rows.len())
        .map(|r| {
            (
                t.list(r, 0).unwrap().to_vec(),
                t.entity(r, 1).unwrap().clone(),
            )
        })
        .collect();
    let mut want_sorted = want.clone();
    want_sorted.sort_by_key(|x| x.0.clone());
    let mut got_sorted = got.clone();
    got_sorted.sort_by_key(|x| x.0.clone());
    assert_eq!(got_sorted, want_sorted);
}

/// `Book.pages` answered one node at a time, counting the keys asked.
#[derive(Debug)]
struct Pages(Arc<AtomicUsize>);

impl External for Pages {
    fn arity(&self) -> usize {
        2
    }

    fn can(&self, bound: u64) -> bool {
        bound & 1 == 1
    }

    fn lookup(
        &self,
        _bound: u64,
        keys: &[&[u64]],
        n: usize,
        out: &mut dyn FnMut(usize, &[u64]),
    ) -> kleene_plan::Result<()> {
        self.0.fetch_add(n, Ordering::Relaxed);
        for (k, &r) in keys[0].iter().take(n).enumerate() {
            if let Some(b) = BOOKS.get(r as usize) {
                out(k, &[r, b.0]);
            }
        }
        Ok(())
    }
}

#[tokio::test]
async fn return_n_limit_1_reads_one_node() {
    let asked = Arc::new(AtomicUsize::new(0));
    let mut c = catalog();
    c.property(
        "Book",
        "pages",
        Source::External(Arc::new(Pages(asked.clone()))),
    );
    let q = parse("MATCH (b:Book) RETURN b ORDER BY id(b) DESC LIMIT 1").unwrap();
    let l = lower_with(&q, &c, &Params::new()).unwrap();
    let t = l.run(&engine()).await.unwrap();
    assert_eq!(wholes(&t, 0), vec![node_of(4)]);
    assert_eq!(asked.load(Ordering::Relaxed), 1);
    // Typed: the same whole node.
    let t = l.run_typed(&engine()).await.unwrap();
    assert_eq!(t.entity(0, 0), Some(&node_of(4)));
}

#[tokio::test]
async fn one_id_space_lists_every_label_of_a_node() {
    let mut c = Catalog::new();
    let ones = |xs: &[u64]| Source::Facts(Facts::from_rows(1, xs.iter().map(|&x| [x])).unwrap());
    c.label("A", ones(&[1, 2]))
        .label("B", ones(&[2, 3]))
        .property(
            "B",
            "w",
            Source::Facts(Facts::from_rows(2, [[2u64, 20], [3, 30]]).unwrap()),
        );
    let q = parse("MATCH (n:A) RETURN n").unwrap();
    let t = lower_with(&q, &c, &Params::new())
        .unwrap()
        .run(&engine())
        .await
        .unwrap();
    let want = vec![
        Entity::Node {
            id: 1,
            labels: vec!["A".into()],
            properties: vec![],
        },
        Entity::Node {
            id: 2,
            labels: vec!["A".into(), "B".into()],
            properties: vec![("w".into(), Datum::U64(20))],
        },
    ];
    assert_eq!(wholes(&t, 0), want);
}

#[tokio::test]
async fn whole_value_refusals_are_named() {
    let e = refused("MATCH (r:Reader)-[e:read]->(b) RETURN type(e), count(*)");
    assert!(e.to_string().contains("group"), "{e}");
    let e = refused("MATCH (r:Reader) OPTIONAL MATCH p = (r)-[:read]->(b) RETURN relationships(p)");
    assert!(e.to_string().contains("OPTIONAL"), "{e}");
    let e = refused("MATCH (n:Book) RETURN type(n)");
    assert!(e.to_string().contains("is no edge"), "{e}");
    // (a variable-length edge through two vertex tables is refused before that)
    let e = refused("MATCH (r:Reader)-[e:read]->*(b) RETURN e");
    assert!(matches!(e, GqlError::Unsupported(_)), "{e}");
}