crates/kleene-gql/tests/typed.rs
//! Typed literals and properties in GQL: strings with escapes, signed and float numbers,
//! booleans, `IS [NOT] NULL` and `STARTS WITH` / `ENDS WITH` / `CONTAINS`, each against a
//! plain loop over the same nodes.
use std::sync::Arc;
use arrow_array::{
Array, ArrayRef, BooleanArray, Float64Array, Int64Array, StringArray, UInt64Array,
};
use kleene_gql::{Catalog, Condition, GqlError, Operand, TextOp, lower, parse};
use kleene_plan::{Datum, Engine, Facts, Source, Type};
use kleene_sparse::{CpuBackend, CpuDevice};
/// (id, name, delta, weight, public): some values null, node 6 with no rows at all.
type Func = (
u64,
Option<&'static str>,
Option<i64>,
Option<f64>,
Option<bool>,
);
fn funcs() -> Vec<Func> {
vec![
(0, Some("parse_expr"), Some(-3), Some(1.5), Some(true)),
(1, Some("lex"), Some(4), Some(-0.25), Some(false)),
(2, Some("it's"), None, Some(2.0), None),
(3, Some("parse"), Some(-3), None, Some(true)),
(4, None, Some(0), Some(10.0), Some(false)),
(5, Some("eval_expr"), Some(7), Some(-2.5), Some(true)),
]
}
const IDS: [u64; 7] = [0, 1, 2, 3, 4, 5, 6];
const CALLS: [(u64, u64); 6] = [(0, 1), (1, 2), (0, 3), (3, 5), (5, 4), (6, 0)];
fn col(a: impl Array + 'static) -> ArrayRef {
Arc::new(a)
}
fn catalog() -> Catalog {
let f = funcs();
let ids = || col(UInt64Array::from_iter_values(f.iter().map(|x| x.0)));
let mut c = Catalog::new();
c.label(
"Func",
Source::Facts(Facts::from_rows(1, IDS.iter().map(|&x| [x])).unwrap()),
)
.edge(
"CALLS",
Source::Facts(Facts::from_rows(2, CALLS.iter().map(|&(a, b)| [a, b])).unwrap()),
)
.typed_property(
"Func",
"name",
Source::Columns(vec![
ids(),
col(StringArray::from(f.iter().map(|x| x.1).collect::<Vec<_>>())),
]),
Type::Str,
)
.typed_property(
"Func",
"delta",
Source::Columns(vec![
ids(),
col(Int64Array::from(f.iter().map(|x| x.2).collect::<Vec<_>>())),
]),
Type::I64,
)
.typed_property(
"Func",
"weight",
Source::Columns(vec![
ids(),
col(Float64Array::from(
f.iter().map(|x| x.3).collect::<Vec<_>>(),
)),
]),
Type::F64,
)
.typed_property(
"Func",
"public",
Source::Columns(vec![
ids(),
col(BooleanArray::from(
f.iter().map(|x| x.4).collect::<Vec<_>>(),
)),
]),
Type::Bool,
);
c
}
fn engine() -> Engine<CpuBackend> {
Engine::new(CpuDevice::new(2))
}
/// The ids `RETURN f` gives for `MATCH (f:Func) WHERE <cond>`.
async fn ids(cond: &str) -> Vec<u64> {
let q = format!("MATCH (f:Func) WHERE {cond} RETURN f");
let l = lower(&parse(&q).unwrap(), &catalog()).unwrap_or_else(|e| panic!("{q}: {e}"));
let t = l
.run(&engine())
.await
.unwrap_or_else(|e| panic!("{q}: {e}"));
t.rows.into_iter().map(|r| r[0]).collect()
}
fn want(f: impl Fn(&Func) -> bool) -> Vec<u64> {
funcs().iter().filter(|x| f(x)).map(|x| x.0).collect()
}
/// The row of node `i`, or a row of nulls for the node with none.
fn row(i: u64) -> Func {
funcs()
.into_iter()
.find(|x| x.0 == i)
.unwrap_or((i, None, None, None, None))
}
fn all(f: impl Fn(&Func) -> bool) -> Vec<u64> {
IDS.iter().copied().filter(|&i| f(&row(i))).collect()
}
#[test]
fn literals_parse_with_escapes_signs_and_keywords() {
let q = parse(
r#"MATCH (a) WHERE a.s = 'it''s å\n' AND a.t = "q\"" AND a.x = -5 AND a.y = -1.5e1
AND a.b = TRUE AND a.c <> false AND a.d IS NOT NULL AND a.e IS NULL
AND a.s STARTS WITH 'p' AND a.s ENDS WITH 'r' AND a.s CONTAINS 'x' RETURN a"#,
)
.unwrap();
let f = &q.matches[0].filter;
let right = |i: usize| match &f[i] {
Condition::Cmp(c) => c.right.clone(),
other => panic!("{other:?}"),
};
assert_eq!(right(0), Operand::Str("it's å\n".into()));
assert_eq!(right(1), Operand::Str("q\"".into()));
assert_eq!(right(2), Operand::Signed(-5));
assert_eq!(right(3), Operand::Float(kleene_gql::Float(-15.0)));
assert_eq!(right(4), Operand::Bool(true));
assert_eq!(right(5), Operand::Bool(false));
assert!(matches!(f[6], Condition::IsNull { null: false, .. }));
assert!(matches!(f[7], Condition::IsNull { null: true, .. }));
let ops: Vec<TextOp> = f[8..]
.iter()
.map(|c| match c {
Condition::Text { op, .. } => *op,
other => panic!("{other:?}"),
})
.collect();
assert_eq!(
ops,
[TextOp::StartsWith, TextOp::EndsWith, TextOp::Contains]
);
for bad in [
"MATCH (a) WHERE a.s = 'open RETURN a",
"MATCH (a) WHERE a.s = '\\q' RETURN a",
"MATCH (a) WHERE a.s = '\\u12' RETURN a",
"MATCH (a) WHERE a.x = - RETURN a",
"MATCH (a) WHERE a.x = -9223372036854775809 RETURN a",
"MATCH (a) WHERE a.s STARTS 'p' RETURN a",
"MATCH (a) WHERE a.s IS 3 RETURN a",
"MATCH (null) RETURN null",
] {
assert!(matches!(parse(bad), Err(GqlError::Syntax { .. })), "{bad}");
}
}
#[tokio::test]
async fn typed_comparisons_match_a_plain_loop_and_unknown_is_not_true() {
let name = |x: &Func| x.1;
assert_eq!(
ids("f.name = 'lex'").await,
want(|x| name(x) == Some("lex"))
);
assert_eq!(
ids("f.name = 'it''s'").await,
want(|x| name(x) == Some("it's"))
);
assert_eq!(
ids("f.name < 'm'").await,
want(|x| name(x).is_some_and(|n| n < "m"))
);
assert_eq!(ids("f.delta = -3").await, want(|x| x.2 == Some(-3)));
assert_eq!(
ids("f.delta >= 0").await,
want(|x| x.2.is_some_and(|d| d >= 0))
);
assert_eq!(
ids("f.weight < 0").await,
want(|x| x.3.is_some_and(|w| w < 0.0))
);
assert_eq!(
ids("f.weight >= 1.5").await,
want(|x| x.3.is_some_and(|w| w >= 1.5))
);
assert_eq!(ids("f.public = TRUE").await, want(|x| x.4 == Some(true)));
// NOT of unknown is unknown: a null is in neither side
assert_eq!(
ids("NOT f.public = TRUE").await,
want(|x| x.4 == Some(false))
);
assert_eq!(
ids("f.name IN ('lex', 'parse', 'zz')").await,
want(|x| matches!(name(x), Some("lex" | "parse")))
);
assert_eq!(
ids("f.delta < 0 OR f.weight > 5").await,
want(|x| x.2.is_some_and(|d| d < 0) || x.3.is_some_and(|w| w > 5.0))
);
// two literals are worked out when the query is lowered
assert_eq!(ids("'a' < 'b' AND -1 < 0").await, all(|_| true));
assert!(ids("1.5 > 2").await.is_empty());
}
#[tokio::test]
async fn is_null_counts_a_missing_property_as_null() {
assert_eq!(ids("f.name IS NULL").await, all(|x| x.1.is_none()));
assert_eq!(ids("f.name IS NOT NULL").await, all(|x| x.1.is_some()));
assert_eq!(ids("f.delta IS NULL").await, all(|x| x.2.is_none()));
assert_eq!(ids("NOT f.weight IS NULL").await, all(|x| x.3.is_some()));
assert_eq!(
ids("f.public IS NULL OR f.delta = 7").await,
all(|x| x.4.is_none() || x.2 == Some(7))
);
// a node is never null
assert_eq!(ids("f IS NOT NULL").await, all(|_| true));
assert!(ids("f IS NULL").await.is_empty());
}
#[tokio::test]
async fn text_tests_match_a_plain_loop_in_three_valued_logic() {
for (op, word) in [
(TextOp::StartsWith, "STARTS WITH"),
(TextOp::EndsWith, "ENDS WITH"),
(TextOp::Contains, "CONTAINS"),
] {
for pat in ["parse", "expr", "", "x", "'"] {
let lit = format!("'{}'", pat.replace('\'', "''"));
let yes = |x: &Func| x.1.is_some_and(|n| op.holds(n, pat));
let no = |x: &Func| x.1.is_some_and(|n| !op.holds(n, pat));
assert_eq!(
ids(&format!("f.name {word} {lit}")).await,
all(yes),
"{word} {pat:?}"
);
// false only where the name is there and fails
assert_eq!(
ids(&format!("NOT f.name {word} {lit}")).await,
all(no),
"NOT {word} {pat:?}"
);
assert_eq!(
ids(&format!("f.name {word} {lit} OR f.delta = 4")).await,
all(|x| yes(x) || x.2 == Some(4)),
"{word} {pat:?} OR"
);
}
}
}
#[tokio::test]
async fn typed_values_come_back_by_type_along_edges() {
let l = lower(
&parse(
"MATCH (a:Func)-[:CALLS]->(b:Func) WHERE a.name STARTS WITH 'parse' \
RETURN a.name, b.name, b.delta, b.weight, b.public ORDER BY b.name",
)
.unwrap(),
&catalog(),
)
.unwrap();
// run refuses typed columns
assert!(matches!(
l.run(&engine()).await,
Err(GqlError::Unsupported(_))
));
let t = l.run_typed(&engine()).await.unwrap();
let d = |i: u64| {
let r = row(i);
vec![
r.1.map_or(Datum::Null, |s| Datum::Str(s.into())),
r.2.map_or(Datum::Null, Datum::I64),
r.3.map_or(Datum::Null, Datum::F64),
r.4.map_or(Datum::Null, Datum::Bool),
]
};
let mut want: Vec<Vec<Datum>> = CALLS
.iter()
.filter(|&&(a, _)| row(a).1.is_some_and(|n| n.starts_with("parse")))
.map(|&(a, b)| {
let mut r = vec![d(a)[0].clone()];
r.extend(d(b));
r
})
.collect();
// ORDER BY b.name: strings in byte order, nulls last
want.sort_by_key(|r| match &r[1] {
Datum::Str(s) => (0, s.clone()),
_ => (1, String::new()),
});
assert_eq!(t.rows, want);
assert_eq!(t.columns[0], "a.name");
let text = t.to_string();
assert!(text.contains("\"parse_expr\""), "{text}");
}
#[tokio::test]
async fn mixed_types_are_refused_when_lowered() {
for bad in [
"f.name = 3",
"f.delta = 'x'",
"f.delta = 1.5",
"f.public = 1",
"f.name = f.delta",
"f.delta = NULL",
"f.delta STARTS WITH 'a'",
"f.name CONTAINS f.name",
"'a' < 1",
] {
let q = format!("MATCH (f:Func) WHERE {bad} RETURN f");
let r = lower(&parse(&q).unwrap(), &catalog());
assert!(
matches!(
r,
Err(GqlError::Semantic(_) | GqlError::Unsupported(_) | GqlError::Plan(_))
),
"{bad}: {:?}",
r.map(|_| ())
);
}
}
/// A property the catalog cannot read (its column's type) is refused by name when a query
/// reads it, in a condition, a returned value or a property map; a query that does not read
/// it runs. A query that returns a signed, boolean or string value says so.
#[tokio::test]
async fn a_refused_property_is_refused_by_name_where_it_is_read() {
let mut c = catalog();
c.refused_property("Func", "day", "an Arrow Date32 column, not read");
for q in [
"MATCH (f:Func) WHERE f.day > 2 RETURN f",
"MATCH (f:Func) RETURN f.day",
"MATCH (f:Func {day: 3}) RETURN f",
"MATCH (f)-[:CALLS]->(g:Func) WHERE g.day IS NULL RETURN f",
] {
let e = lower(&parse(q).unwrap(), &c).unwrap_err().to_string();
assert!(e.contains("`day`") && e.contains("Date32"), "{q}: {e}");
}
let l = lower(
&parse("MATCH (f:Func) WHERE f.delta < 0 RETURN f").unwrap(),
&c,
)
.unwrap();
let t = l.run(&engine()).await.unwrap();
let got: Vec<u64> = t.rows.into_iter().map(|r| r[0]).collect();
assert_eq!(got, want(|x| x.2.is_some_and(|d| d < 0)));
assert!(!l.returns_typed());
for (q, typed) in [
("MATCH (f:Func) RETURN f.delta", true),
("MATCH (f:Func) RETURN f.public", true),
("MATCH (f:Func) RETURN f.name", true),
("MATCH (f:Func) RETURN f.weight", false),
("MATCH (f:Func) RETURN count(*)", false),
] {
let l = lower(&parse(q).unwrap(), &c).unwrap();
assert_eq!(l.returns_typed(), typed, "{q}");
}
}