crates/kleene-gql/tests/strings.rs
//! Line 9 from GQL: strings made by a query (`a || b`, `char_length(s)`,
//! `character_length(s)`, `substring(s, start [, len])`), lowered onto the core's computed
//! values ([`kleene_plan::Func`]), each answer against a plain loop over the same words.
use std::sync::Arc;
use arrow_array::{ArrayRef, Int64Array, StringArray, UInt64Array};
use kleene_gql::{Catalog, Params, TypedTable, lower_with, parse};
use kleene_plan::{Datum, Engine, Facts, Source, Type};
use kleene_sparse::{CpuBackend, CpuDevice};
/// Words `0..`: (name, pre, k); one name null.
const WORDS: [(Option<&str>, &str, i64); 9] = [
(Some("lex"), "er", 1),
(Some("ab"), "c", 0),
(Some("日本"), "語", 1),
(None, "x", 2),
(Some("lexer"), "", 9),
(Some("abc"), "lex", -1),
(Some("🦀"), "rs", 0),
(Some("m"), "id", 3),
(Some("er"), "lex", 1),
];
fn catalog() -> Catalog {
let n = WORDS.len() as u64;
let ids = || -> ArrayRef { Arc::new(UInt64Array::from_iter_values(0..n)) };
let mut c = Catalog::new();
c.label(
"Word",
Source::Facts(Facts::from_rows(1, (0..n).map(|x| [x])).unwrap()),
)
.typed_property(
"Word",
"name",
Source::Columns(vec![
ids(),
Arc::new(StringArray::from(
WORDS.iter().map(|w| w.0).collect::<Vec<_>>(),
)),
]),
Type::Str,
)
.typed_property(
"Word",
"pre",
Source::Columns(vec![
ids(),
Arc::new(StringArray::from_iter_values(WORDS.iter().map(|w| w.1))),
]),
Type::Str,
)
.typed_property(
"Word",
"k",
Source::Columns(vec![
ids(),
Arc::new(Int64Array::from_iter_values(WORDS.iter().map(|w| w.2))),
]),
Type::I64,
);
c
}
async fn typed(q: &str, threads: usize) -> TypedTable {
let l = lower_with(
&parse(q).unwrap_or_else(|e| panic!("{q}: {e}")),
&catalog(),
&Params::new(),
)
.unwrap_or_else(|e| panic!("{q}: {e}"));
l.run_typed(&Engine::<CpuBackend>::new(CpuDevice::new(threads)))
.await
.unwrap_or_else(|e| panic!("{q}: {e}"))
}
fn sorted(mut v: Vec<Vec<Datum>>) -> Vec<Vec<Datum>> {
v.sort_by_key(|r| format!("{r:?}"));
v
}
fn s(x: Option<String>) -> Datum {
x.map_or(Datum::Null, Datum::Str)
}
/// `substring` in plain Rust: `n` characters from character `i`; a negative one: null.
fn cut(w: &str, i: i64, n: Option<i64>) -> Option<String> {
if i < 0 || n.is_some_and(|n| n < 0) {
return None;
}
let it = w.chars().skip(i as usize);
Some(match n {
Some(n) => it.take(n as usize).collect(),
None => it.collect(),
})
}
#[tokio::test]
async fn made_strings_from_gql_equal_plain_rust_at_every_thread_count() {
for threads in [1, 2, 4] {
// || : null where a side is null
let t = typed(
"MATCH (w:Word) RETURN w.pre, w.name || '-' || w.pre AS s",
threads,
)
.await;
let want: Vec<Vec<Datum>> = WORDS
.iter()
.map(|w| {
vec![
Datum::Str(w.1.into()),
s(w.0.map(|n| format!("{n}-{}", w.1))),
]
})
.collect();
assert_eq!(sorted(t.rows), sorted(want), "|| at {threads}");
// char_length and character_length count characters; null of null
for f in ["char_length", "character_length"] {
let t = typed(
&format!("MATCH (w:Word) RETURN w.pre, {f}(w.name)"),
threads,
)
.await;
let want: Vec<Vec<Datum>> = WORDS
.iter()
.map(|w| {
vec![
Datum::Str(w.1.into()),
w.0.map_or(Datum::Null, |n| Datum::I64(n.chars().count() as i64)),
]
})
.collect();
assert_eq!(sorted(t.rows), sorted(want), "{f} at {threads}");
}
// substring from 0, with and without a length; past the end shorter
let t = typed(
"MATCH (w:Word) RETURN w.pre, substring(w.name, w.k, 2), substring(w.name, w.k)",
threads,
)
.await;
let want: Vec<Vec<Datum>> = WORDS
.iter()
.map(|w| {
vec![
Datum::Str(w.1.into()),
s(w.0.and_then(|n| cut(n, w.2, Some(2)))),
s(w.0.and_then(|n| cut(n, w.2, None))),
]
})
.collect();
assert_eq!(sorted(t.rows), sorted(want), "substring at {threads}");
// a made string joins a string read; a length in WHERE
let t = typed(
"MATCH (w:Word), (v:Word) WHERE w.name || w.pre = v.name \
AND char_length(v.name) > 2 RETURN w.name, v.name",
threads,
)
.await;
let mut want: Vec<Vec<Datum>> = Vec::new();
for w in &WORDS {
for v in &WORDS {
if let (Some(a), Some(b)) = (w.0, v.0)
&& format!("{a}{}", w.1) == b
&& b.chars().count() > 2
{
want.push(vec![Datum::Str(a.into()), Datum::Str(b.into())]);
}
}
}
assert!(!want.is_empty());
assert_eq!(sorted(t.rows), sorted(want), "join at {threads}");
// made strings in byte order
let t = typed(
"MATCH (w:Word) WHERE w.name IS NOT NULL RETURN w.name || w.pre AS s ORDER BY s",
threads,
)
.await;
let mut want: Vec<String> = WORDS
.iter()
.filter_map(|w| w.0.map(|n| format!("{n}{}", w.1)))
.collect();
want.sort();
let got: Vec<Datum> = t.rows.into_iter().map(|mut r| r.remove(0)).collect();
assert_eq!(
got,
want.into_iter().map(Datum::Str).collect::<Vec<_>>(),
"order at {threads}"
);
}
}