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

nordisk/kleene

crates/kleene-datalog/tests/row_ids.rs

//! A label's row numbers and ids by name: `L@id`, `(row, id)` of every node label of a set's
//! catalog (kleene-plan's `Catalog::row_ids`, an `IdShift` answered by arithmetic), read with
//! `input_from` and bound by `Inputs::bind`, so a column that holds a ROW number of another
//! table joins that table's ids with no base taken from Rust. The answer checked against a
//! plain loop over the same rows.

use std::collections::BTreeSet;
use std::path::PathBuf;

use graphar::mapped::{IntColumn, IntGraphWriter};
use kleene_datalog::{Engine, Inputs, Program, Type};
use kleene_gar::GarGraph;
use kleene_sparse::{CpuBackend, CpuDevice};

/// Each person's pet, as a row number of `pet` (3 is no pet: past the table's 3 rows).
const PET_ROW: [u32; 5] = [2, 0, 3, 1, 2];
const PETS: u64 = 3;

struct TempDir(PathBuf);

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

fn set() -> TempDir {
    let dir = std::env::temp_dir().join(format!("kleene-datalog-row-ids-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let mut w = IntGraphWriter::new(&dir, "X").unwrap();
    w.vertices(
        "person",
        5,
        vec![("pet_row".to_string(), IntColumn::U32(PET_ROW.to_vec()))],
    )
    .unwrap();
    w.vertices("pet", PETS as u32, vec![]).unwrap();
    w.finish().unwrap();
    TempDir(dir)
}

/// `owner(P, X) :- person.pet_row(P, R), pet@id(R, X).`: the pet's id from its row, the
/// base never named.
#[tokio::test]
async fn a_row_column_joins_the_ids_of_its_table_by_name() {
    let dir = set();
    let g = GarGraph::open(&dir.0).unwrap();
    let catalog = g.catalog().unwrap();
    let space = g.id_space().unwrap();

    let mut p = Program::new();
    let pet_row = p.input_from::<2>(&catalog, "person.pet_row").unwrap();
    let pet_id = p.input_from::<2>(&catalog, "pet@id").unwrap();
    let person_id = p.input_from::<2>(&catalog, "person@id").unwrap();
    assert_eq!(p.types(pet_id.id()), [Type::U64, Type::U64]);
    // a width other than two, a label the set lacks, a property's name: refused by name
    assert!(p.input_from::<1>(&catalog, "pet@id").is_err());
    let e = p
        .input_from::<2>(&catalog, "cat@id")
        .unwrap_err()
        .to_string();
    assert!(e.contains("cat"), "{e}");
    assert!(p.input_from::<2>(&catalog, "person.pet_row@id").is_err());
    let owner = p.derived::<2>("owner");
    let rows = p.derived::<2>("rows");
    let [pv, r, x, i] = ["P", "R", "X", "I"].map(|n| p.var(n));
    p.rule(owner.at([pv, x]), [pet_row.at([pv, r]), pet_id.at([r, x])])
        .unwrap();
    // and back: the person's row from its id
    p.rule(rows.at([r, i]), [owner.at([i, x]), person_id.at([r, i])])
        .unwrap();

    let mut inputs = Inputs::new();
    inputs.bind(&p, &catalog).unwrap();
    for rel in [pet_row.id(), pet_id.id(), person_id.id()] {
        assert!(inputs.source(rel).is_some());
    }
    for threads in [1, 2, 4] {
        let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(threads));
        let out = e.run(&p, &inputs).await.unwrap();
        let got: BTreeSet<Vec<u64>> = out.get(&owner).unwrap().rows().collect();
        let back: BTreeSet<Vec<u64>> = out.get(&rows).unwrap().rows().collect();

        // the plain loop
        let (person, pet) = (space.base("person").unwrap(), space.base("pet").unwrap());
        let mut want: BTreeSet<Vec<u64>> = BTreeSet::new();
        let mut want_back: BTreeSet<Vec<u64>> = BTreeSet::new();
        for (s, &row) in PET_ROW.iter().enumerate() {
            if (row as u64) < PETS {
                want.insert(vec![person + s as u64, pet + row as u64]);
                want_back.insert(vec![s as u64, person + s as u64]);
            }
        }
        assert_eq!(want.len(), 4);
        assert_eq!(got, want, "{threads} threads");
        assert_eq!(back, want_back, "{threads} threads");
    }
}