crates/kleene-datalog/tests/order.rs
//! The output operator from the Datalog side: a typed relation's rows ordered by a falling
//! key with its nulls last and a rising one, an offset and a limit, as a plain sort gives.
use std::sync::Arc;
use arrow_array::{ArrayRef, Int64Array, StringArray};
use kleene_datalog::{Datum, Engine, Inputs, Order, OrderKey, Program, Type};
use kleene_sparse::{CpuBackend, CpuDevice};
#[tokio::test]
async fn a_relation_ordered_and_cut() {
let names = ["ann", "bo", "cy", "di", "ed", "fi", "gu"];
let ages = [Some(31), None, Some(17), Some(31), None, Some(45), Some(17)];
let mut p = Program::new();
let person = p.input_typed("person", [Type::Str, Type::I64]);
let all = p.derived_typed("all", [Type::Str, Type::I64]);
let (n, a) = (p.var("N"), p.var("A"));
p.rule(all.at([n, a]), [person.at([n, a])]).unwrap();
let mut inputs = Inputs::new();
let ns: ArrayRef = Arc::new(StringArray::from(names.to_vec()));
let ags: ArrayRef = Arc::new(Int64Array::from(ages.to_vec()));
inputs.columns(&person, [ns, ags]);
let out = Engine::<CpuBackend>::new(CpuDevice::new(2))
.run(&p, &inputs)
.await
.unwrap();
// ORDER BY age DESC NULLS LAST, name OFFSET 1 LIMIT 4
let order = Order::new()
.by(OrderKey::desc(1).nulls_last())
.by(OrderKey::asc(0))
.offset(1)
.limit(4);
let got = out.ordered(&p, &all, &order).unwrap();
let mut want: Vec<(Option<i64>, &str)> = ages.iter().copied().zip(names).collect();
want.sort_by(|x, y| match (x.0, y.0) {
(None, None) => x.1.cmp(y.1),
(None, Some(_)) => std::cmp::Ordering::Greater,
(Some(_), None) => std::cmp::Ordering::Less,
(Some(p), Some(q)) => q.cmp(&p).then(x.1.cmp(y.1)),
});
let want: Vec<Vec<Datum>> = want
.into_iter()
.skip(1)
.take(4)
.map(|(a, n)| vec![Datum::Str(n.into()), a.map_or(Datum::Null, Datum::I64)])
.collect();
assert_eq!(got, want);
}