use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
use base64::Engine;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use crate::error::{Error, Result};
use crate::protocol::{ColumnDef, JsonMap, TableSchema, USERS_TABLE};
pub const QUERY_MAX_DEPTH: usize = 3;
pub const QUERY_MAX_NODES: usize = 8;
pub const QUERY_MAX_LIMIT: u64 = 10_000;
const MAX_LINK_HOPS: usize = 3;
const MAX_IN_VALUES: usize = 1000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueType {
String,
Number,
Boolean,
Datetime,
Json,
}
impl ValueType {
fn of(column_type: &str) -> ValueType {
match column_type {
"number" => ValueType::Number,
"boolean" => ValueType::Boolean,
"datetime" => ValueType::Datetime,
"json" => ValueType::Json,
_ => ValueType::String,
}
}
fn name(self) -> &'static str {
match self {
ValueType::String => "string",
ValueType::Number => "number",
ValueType::Boolean => "boolean",
ValueType::Datetime => "datetime",
ValueType::Json => "json",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CmpOp {
Eq,
Ne,
Gt,
Gte,
Lt,
Lte,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Scalar {
Str(String),
Num(f64),
Bool(bool),
}
#[derive(Debug, Clone, PartialEq)]
pub enum Pred {
True,
False,
And(Vec<Pred>),
Or(Vec<Pred>),
Not(Box<Pred>),
Cmp {
field: String,
ty: ValueType,
op: CmpOp,
value: Scalar,
},
In {
field: String,
ty: ValueType,
values: Vec<Scalar>,
},
Like {
field: String,
pattern: String,
ci: bool,
},
IsNull {
field: String,
ty: ValueType,
},
Link {
field: String,
table: String,
pred: Box<Pred>,
},
}
fn invalid(msg: impl std::fmt::Display) -> Error {
Error::new("invalid_query", format!("invalid query: {msg}"))
.with_hint("Fix the query: PROTOCOL.md §17.5 lists the keys, options and where operators a query takes.")
}
pub fn and(ps: Vec<Pred>) -> Pred {
let mut args = Vec::new();
for p in ps {
match p {
Pred::True => {}
Pred::False => return Pred::False,
Pred::And(a) => args.extend(a),
p => args.push(p),
}
}
match args.len() {
0 => Pred::True,
1 => args.pop().expect("one"),
_ => Pred::And(args),
}
}
fn sorted_keys(o: &Map<String, Value>) -> Vec<&String> {
let mut k: Vec<&String> = o.keys().collect();
k.sort();
k
}
pub fn parse_where(w: Option<&Value>, table: &str, tables: &BTreeMap<String, TableSchema>) -> Result<Pred> {
match w {
None | Some(Value::Null) => Ok(Pred::True),
Some(w) => parse_where_obj(w, table, tables, 0),
}
}
fn parse_where_obj(w: &Value, table: &str, tables: &BTreeMap<String, TableSchema>, depth: usize) -> Result<Pred> {
if depth > 16 {
return Err(invalid("where nests too deeply"));
}
let Value::Object(o) = w else { return Err(invalid("where must be an object")) };
let mut parts = Vec::new();
for key in sorted_keys(o) {
let v = &o[key];
if key == "and" || key == "or" {
let Value::Array(items) = v else {
return Err(invalid(format!("\"{key}\" must be an array of where objects")));
};
let mut args = Vec::new();
for item in items {
args.push(parse_where_obj(item, table, tables, depth + 1)?);
}
if key == "and" {
parts.push(and(args));
} else if args.is_empty() {
parts.push(Pred::False);
} else if args.len() == 1 {
parts.push(args.pop().expect("one"));
} else {
parts.push(Pred::Or(args));
}
} else if key == "$not" {
parts.push(Pred::Not(Box::new(parse_where_obj(v, table, tables, depth + 1)?)));
} else {
let segs: Vec<&str> = key.split('.').collect();
if segs.len() > MAX_LINK_HOPS + 1 {
return Err(invalid(format!("\"{key}\": where paths follow at most {MAX_LINK_HOPS} links")));
}
parts.push(parse_segs(key, &segs, v, table, tables)?);
}
}
Ok(and(parts))
}
fn parse_segs(
path: &str,
segs: &[&str],
v: &Value,
table: &str,
tables: &BTreeMap<String, TableSchema>,
) -> Result<Pred> {
let ts = tables.get(table).ok_or_else(|| invalid(format!("unknown table \"{table}\"")))?;
let name = segs[0];
if segs.len() > 1 {
let c = ts.columns.get(name).ok_or_else(|| invalid(format!("\"{path}\": {table} has no column \"{name}\"")))?;
let target = match (&c.ty[..], &c.ref_table) {
("ref", Some(t)) if !t.is_empty() => t.clone(),
_ => {
return Err(invalid(format!(
"\"{path}\": {table}.{name} is not a ref column with a target table (declare it t.ref(\"table\"))"
)))
}
};
let pred = parse_segs(path, &segs[1..], v, &target, tables)?;
return Ok(Pred::Link { field: name.to_string(), table: target, pred: Box::new(pred) });
}
let ty = if name == "id" {
ValueType::String
} else {
let c = ts.columns.get(name).ok_or_else(|| invalid(format!("{table} has no column \"{name}\"")))?;
ValueType::of(&c.ty)
};
parse_cond(path, name, ty, v)
}
fn parse_cond(path: &str, field: &str, ty: ValueType, v: &Value) -> Result<Pred> {
let f = field.to_string();
let Value::Object(ops) = v else {
if v.is_null() {
return Ok(Pred::IsNull { field: f, ty });
}
return Ok(Pred::Cmp { field: f, ty, op: CmpOp::Eq, value: literal(path, ty, v)? });
};
if ops.is_empty() {
return Err(invalid(format!(
"\"{path}\": an empty operator object matches nothing useful; give a value or an operator"
)));
}
let mut parts = Vec::new();
for op in sorted_keys(ops) {
let arg = &ops[op];
if ty == ValueType::Json && op != "$isNull" {
return Err(invalid(format!("\"{path}\": json columns only support $isNull")));
}
let cmp = match op.as_str() {
"$eq" => Some(CmpOp::Eq),
"$ne" => Some(CmpOp::Ne),
"$gt" => Some(CmpOp::Gt),
"$gte" => Some(CmpOp::Gte),
"$lt" => Some(CmpOp::Lt),
"$lte" => Some(CmpOp::Lte),
_ => None,
};
if let Some(cmp) = cmp {
if arg.is_null() {
match cmp {
CmpOp::Eq => parts.push(Pred::IsNull { field: f.clone(), ty }),
CmpOp::Ne => parts.push(Pred::Not(Box::new(Pred::IsNull { field: f.clone(), ty }))),
_ => return Err(invalid(format!("\"{path}\": {op} needs a value, not null"))),
}
continue;
}
if ty == ValueType::Boolean && !matches!(cmp, CmpOp::Eq | CmpOp::Ne) {
return Err(invalid(format!("\"{path}\": booleans only support equality")));
}
parts.push(Pred::Cmp { field: f.clone(), ty, op: cmp, value: literal(path, ty, arg)? });
continue;
}
match op.as_str() {
"$in" => {
let Value::Array(items) = arg else { return Err(invalid(format!("\"{path}\": $in needs an array"))) };
if items.len() > MAX_IN_VALUES {
return Err(invalid(format!("\"{path}\": $in takes at most {MAX_IN_VALUES} values")));
}
let values = items.iter().map(|x| literal(path, ty, x)).collect::<Result<Vec<_>>>()?;
parts.push(Pred::In { field: f.clone(), ty, values });
}
"$like" | "$ilike" => {
if ty != ValueType::String {
return Err(invalid(format!("\"{path}\": {op} works on string columns")));
}
let Value::String(p) = arg else {
return Err(invalid(format!("\"{path}\": {op} needs a string pattern")));
};
parts.push(Pred::Like { field: f.clone(), pattern: p.clone(), ci: op == "$ilike" });
}
"$isNull" => {
let Value::Bool(b) = arg else { return Err(invalid(format!("\"{path}\": $isNull needs true or false"))) };
let p = Pred::IsNull { field: f.clone(), ty };
parts.push(if *b { p } else { Pred::Not(Box::new(p)) });
}
_ => {
return Err(invalid(format!(
"\"{path}\": unknown operator \"{op}\" (use $eq, $ne, $in, $gt, $gte, $lt, $lte, $like, $ilike or $isNull)"
)))
}
}
}
Ok(and(parts))
}
fn literal(path: &str, ty: ValueType, v: &Value) -> Result<Scalar> {
convert(ty, v).ok_or_else(|| invalid(format!("\"{path}\": {v} is not a {} value", ty.name())))
}
pub fn parse_datetime(s: &str) -> Option<f64> {
let b = s.as_bytes();
if b.len() < 20 {
return None;
}
let num = |r: std::ops::Range<usize>| -> Option<i64> {
let t = s.get(r)?;
t.bytes().all(|c| c.is_ascii_digit()).then(|| t.parse().ok())?
};
let (y, mo, d) = (num(0..4)?, num(5..7)?, num(8..10)?);
let (h, mi, se) = (num(11..13)?, num(14..16)?, num(17..19)?);
if b[4] != b'-' || b[7] != b'-' || !matches!(b[10], b'T' | b't') || b[13] != b':' || b[16] != b':' {
return None;
}
let mut i = 19;
let mut frac_ms = 0i64;
if b.get(i) == Some(&b'.') {
let start = i + 1;
i = start;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
if i == start {
return None;
}
let digit = |n: usize| b.get(start + n).filter(|_| start + n < i).map_or(0, |c| i64::from(c - b'0'));
frac_ms = digit(0) * 100 + digit(1) * 10 + digit(2);
if digit(3) >= 5 {
frac_ms += 1;
}
}
let offset_min = match b.get(i)? {
b'Z' | b'z' if i + 1 == b.len() => 0,
c @ (b'+' | b'-') if i + 6 == b.len() && b[i + 3] == b':' => {
let (oh, om) = (num(i + 1..i + 3)?, num(i + 4..i + 6)?);
if oh > 23 || om > 59 {
return None;
}
let m = oh * 60 + om;
if *c == b'-' {
-m
} else {
m
}
}
_ => return None,
};
let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
let dim = [31, if leap { 29 } else { 28 }, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if !(1..=12).contains(&mo) || d < 1 || d > dim[(mo - 1) as usize] || h > 23 || mi > 59 || se > 59 {
return None;
}
let yy = if mo <= 2 { y - 1 } else { y };
let era = if yy >= 0 { yy } else { yy - 399 } / 400;
let yoe = yy - era * 400;
let mp = (mo + 9) % 12;
let doy = (153 * mp + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146_097 + doe - 719_468;
let secs = days * 86_400 + h * 3600 + mi * 60 + se - offset_min * 60;
Some((secs * 1000 + frac_ms) as f64)
}
fn convert(ty: ValueType, v: &Value) -> Option<Scalar> {
match (ty, v) {
(ValueType::String, Value::String(s)) => Some(Scalar::Str(s.clone())),
(ValueType::Number, Value::Number(n)) => n.as_f64().filter(|f| f.is_finite()).map(|f| Scalar::Num(f + 0.0)),
(ValueType::Boolean, Value::Bool(b)) => Some(Scalar::Bool(*b)),
(ValueType::Datetime, Value::String(s)) => parse_datetime(s).map(Scalar::Num),
_ => None,
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct QueryOrder {
pub field: String,
pub ty: ValueType,
pub desc: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Cursor {
pub value: Option<Scalar>,
pub id: String,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Link {
Forward(String),
Reverse(String),
}
#[derive(Debug, Clone, PartialEq)]
pub struct QNode {
pub key: String,
pub table: String,
pub pred: Pred,
pub order: Option<QueryOrder>,
pub limit: u64,
pub after: Option<Cursor>,
pub before: Option<Cursor>,
pub fields: Option<Vec<String>>,
pub link: Option<Link>,
pub children: Vec<QNode>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CompiledQuery {
pub roots: Vec<QNode>,
pub tables: BTreeSet<String>,
}
pub fn users_schema() -> TableSchema {
let mut columns = BTreeMap::new();
columns.insert("email".to_string(), ColumnDef::new("string").optional());
columns.insert("is_guest".to_string(), ColumnDef::new("boolean"));
columns.insert("created_at".to_string(), ColumnDef::new("datetime"));
TableSchema {
columns,
order: Some(vec!["email".into(), "is_guest".into(), "created_at".into()]),
..Default::default()
}
}
pub fn parse_query(query: &Value, schema: &BTreeMap<String, TableSchema>) -> Result<CompiledQuery> {
let mut tables = schema.clone();
tables.entry(USERS_TABLE.to_string()).or_insert_with(users_schema);
let Value::Object(q) = query else {
return Err(invalid("a query is an object keyed by table name, e.g. {\"posts\": {}}"));
};
if q.is_empty() {
return Err(invalid("a query names at least one table"));
}
let mut count = 0usize;
let mut read = BTreeSet::new();
let mut roots = Vec::new();
for key in sorted_keys(q) {
if key == "$" {
return Err(invalid("\"$\" options belong inside a table, e.g. {\"posts\": {\"$\": {\"limit\": 10}}}"));
}
if !tables.contains_key(key.as_str()) {
let names: Vec<&str> = tables.keys().map(String::as_str).collect();
return Err(invalid(format!("unknown table \"{key}\" (tables: {})", names.join(", "))));
}
roots.push(parse_node(&q[key], key, key, None, &tables, 0, &mut count, &mut read)?);
}
Ok(CompiledQuery { roots, tables: read })
}
const OPTION_KEYS: &[&str] = &["where", "order", "limit", "after", "before", "fields", "via"];
fn link_count(p: &Pred, read: &mut BTreeSet<String>) -> usize {
let mut n = 0;
for (table, pred) in links(p) {
read.insert(table.to_string());
n += 1 + link_count(pred, read);
}
n
}
fn links(p: &Pred) -> Vec<(&str, &Pred)> {
let mut out = Vec::new();
fn walk<'a>(q: &'a Pred, out: &mut Vec<(&'a str, &'a Pred)>) {
match q {
Pred::Link { table, pred, .. } => out.push((table, pred)),
Pred::And(a) | Pred::Or(a) => a.iter().for_each(|x| walk(x, out)),
Pred::Not(x) => walk(x, out),
_ => {}
}
}
walk(p, &mut out);
out
}
fn field_type(ts: &TableSchema, f: &str) -> Option<ValueType> {
if f == "id" {
return Some(ValueType::String);
}
ts.columns.get(f).map(|c| ValueType::of(&c.ty))
}
#[allow(clippy::too_many_arguments)]
fn parse_node(
raw: &Value,
key: &str,
table: &str,
parent: Option<&QNode>,
tables: &BTreeMap<String, TableSchema>,
depth: usize,
count: &mut usize,
read: &mut BTreeSet<String>,
) -> Result<QNode> {
let too_many =
|| invalid(format!("a query reads at most {QUERY_MAX_NODES} tables (nodes plus link paths in where)"));
*count += 1;
if *count > QUERY_MAX_NODES {
return Err(too_many());
}
let Value::Object(raw) = raw else {
return Err(invalid(format!("\"{key}\" must be an object (use {{}} for every row)")));
};
read.insert(table.to_string());
let ts = &tables[table];
let empty = Map::new();
let opts = match raw.get("$") {
None => &empty,
Some(Value::Object(o)) => o,
Some(_) => return Err(invalid(format!("\"{key}\": $ must be an object"))),
};
for k in opts.keys() {
if !OPTION_KEYS.contains(&k.as_str()) {
return Err(invalid(format!(
"\"{key}\": $: unknown option \"{k}\" (options: where, order, limit, after, before, fields, via)"
)));
}
}
let pred = parse_where(opts.get("where"), table, tables)?;
*count += link_count(&pred, read);
if *count > QUERY_MAX_NODES {
return Err(too_many());
}
let mut n = QNode {
key: key.to_string(),
table: table.to_string(),
pred,
order: None,
limit: 0,
after: None,
before: None,
fields: None,
link: None,
children: Vec::new(),
};
if let Some(order) = opts.get("order") {
let Value::Object(o) = order else {
return Err(invalid(format!("\"{key}\": order sorts by one field, e.g. {{\"createdAt\": \"desc\"}}")));
};
if o.len() > 1 {
return Err(invalid(format!("\"{key}\": order sorts by one field, e.g. {{\"createdAt\": \"desc\"}}")));
}
for (f, dir) in o {
let ty =
field_type(ts, f).ok_or_else(|| invalid(format!("\"{key}\": order: {table} has no column \"{f}\"")))?;
if ty == ValueType::Json {
return Err(invalid(format!("\"{key}\": order: json columns can't be sorted")));
}
let desc = match dir.as_str() {
Some("asc") => false,
Some("desc") => true,
_ => return Err(invalid(format!("\"{key}\": order: direction is \"asc\" or \"desc\", not {dir}"))),
};
n.order = Some(QueryOrder { field: f.clone(), ty, desc });
}
}
if let Some(limit) = opts.get("limit") {
let l = limit.as_u64().filter(|l| (1..=QUERY_MAX_LIMIT).contains(l) && limit.is_u64());
let Some(l) = l else { return Err(invalid(format!("\"{key}\": limit is 1 to {QUERY_MAX_LIMIT}"))) };
if parent.is_some() {
return Err(invalid(format!(
"\"{key}\": only top-level tables take a limit; nested links return every linked row"
)));
}
n.limit = l;
}
let (after, before) = (opts.get("after"), opts.get("before"));
if after.is_some() || before.is_some() {
if parent.is_some() {
return Err(invalid(format!("\"{key}\": only top-level tables page")));
}
if after.is_some() && before.is_some() {
return Err(invalid(format!("\"{key}\": give after or before, not both")));
}
let o = n.order.get_or_insert_with(|| QueryOrder { field: "id".into(), ty: ValueType::String, desc: false });
let ty = o.ty;
if let Some(a) = after {
n.after = Some(decode_cursor(a, ty, key)?);
}
if let Some(b) = before {
n.before = Some(decode_cursor(b, ty, key)?);
}
}
if let Some(fields) = opts.get("fields") {
let Value::Array(fs) = fields else { return Err(invalid(format!("\"{key}\": fields is an array of columns"))) };
let mut set = BTreeSet::new();
for f in fs {
match f.as_str() {
Some(name) if field_type(ts, name).is_some() => {
set.insert(name.to_string());
}
_ => return Err(invalid(format!("\"{key}\": fields: {table} has no column {f}"))),
}
}
n.fields = Some(set.into_iter().collect());
}
let via = opts.get("via");
if via.is_some() && parent.is_none() {
return Err(invalid(format!("\"{key}\": via picks the column of a nested link")));
}
if let Some(p) = parent {
n.link = Some(resolve_link(&n, p, key, via, tables)?);
}
for child in sorted_keys(raw) {
if child == "$" {
continue;
}
if depth + 1 > QUERY_MAX_DEPTH {
return Err(invalid(format!(
"\"{child}\": a query follows at most {QUERY_MAX_DEPTH} links below a top-level table"
)));
}
let child_table = link_target(&n, child, tables)?;
let c = parse_node(&raw[child], child, &child_table, Some(&n), tables, depth + 1, count, read)?;
n.children.push(c);
}
Ok(n)
}
fn link_target(parent: &QNode, key: &str, tables: &BTreeMap<String, TableSchema>) -> Result<String> {
if let Some(def) = tables.get(&parent.table).and_then(|t| t.columns.get(key)) {
if def.ty == "ref" {
let Some(target) = def.ref_table.as_deref().filter(|t| !t.is_empty()) else {
return Err(invalid(format!(
"\"{key}\": {}.{key} has no target table; declare it t.ref(\"table\") to follow it",
parent.table
)));
};
if !tables.contains_key(target) {
return Err(invalid(format!(
"\"{key}\": {}.{key} points at \"{target}\", which doesn't exist",
parent.table
)));
}
return Ok(target.to_string());
}
}
if tables.contains_key(key) {
return Ok(key.to_string());
}
Err(invalid(format!("\"{key}\" under \"{}\" is neither a ref column of {} nor a table", parent.key, parent.table)))
}
fn resolve_link(
n: &QNode,
p: &QNode,
key: &str,
via: Option<&Value>,
tables: &BTreeMap<String, TableSchema>,
) -> Result<Link> {
if let Some(def) = tables.get(&p.table).and_then(|t| t.columns.get(key)) {
if def.ty == "ref" && def.ref_table.as_deref() == Some(n.table.as_str()) {
if via.is_some() {
return Err(invalid(format!(
"\"{key}\": via is for reverse links; {}.{key} is a forward link",
p.table
)));
}
return Ok(Link::Forward(key.to_string()));
}
}
let cols = &tables[&n.table].columns;
let points_back = |d: &ColumnDef| d.ty == "ref" && d.ref_table.as_deref() == Some(p.table.as_str());
if let Some(via) = via {
let ok = via.as_str().and_then(|v| cols.get(v).map(|d| (v, d))).filter(|(_, d)| points_back(d));
let Some((v, _)) = ok else {
return Err(invalid(format!(
"\"{key}\": via {via} must be a ref column of {} that points at {}",
n.table, p.table
)));
};
return Ok(Link::Reverse(v.to_string()));
}
let cands: Vec<&String> = cols.iter().filter(|(_, d)| points_back(d)).map(|(k, _)| k).collect();
match cands.len() {
0 => Err(invalid(format!("\"{key}\": {} has no ref column pointing at {}", n.table, p.table))),
1 => Ok(Link::Reverse(cands[0].clone())),
_ => Err(invalid(format!(
"\"{key}\": several columns of {} point at {} ({}); pick one with \"$\": {{\"via\": \"…\"}}",
n.table,
p.table,
cands.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")
))),
}
}
pub fn encode_cursor(value: Option<&Value>, id: &str) -> String {
B64.encode(json!([value.cloned().unwrap_or(Value::Null), id]).to_string())
}
fn decode_cursor(s: &Value, ty: ValueType, key: &str) -> Result<Cursor> {
let bad = || invalid(format!("\"{key}\": malformed cursor"));
let s = s.as_str().ok_or_else(bad)?;
let bytes = B64.decode(s.trim_end_matches('=')).map_err(|_| bad())?;
let parts: Value = serde_json::from_slice(&bytes).map_err(|_| bad())?;
let Value::Array(parts) = parts else { return Err(bad()) };
if parts.len() != 2 {
return Err(bad());
}
let id = parts[1].as_str().ok_or_else(bad)?.to_string();
if parts[0].is_null() {
return Ok(Cursor { value: None, id });
}
let value =
convert(ty, &parts[0]).ok_or_else(|| invalid(format!("\"{key}\": cursor does not fit the order field")))?;
Ok(Cursor { value: Some(value), id })
}
pub type LinkResolver<'a> = &'a dyn Fn(&str, &str, &Pred) -> Option<bool>;
fn compare(a: &Scalar, b: &Scalar) -> Ordering {
match (a, b) {
(Scalar::Str(x), Scalar::Str(y)) => x.as_bytes().cmp(y.as_bytes()),
(Scalar::Bool(x), Scalar::Bool(y)) => x.cmp(y),
(Scalar::Num(x), Scalar::Num(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
_ => Ordering::Equal,
}
}
pub fn field_value(row: &JsonMap, id: &str, field: &str, ty: ValueType) -> Option<Scalar> {
if field == "id" {
return Some(Scalar::Str(id.to_string()));
}
row.get(field).and_then(|v| convert(ty, v))
}
pub fn like(s: &str, pattern: &str, ci: bool) -> bool {
let (s, pattern) =
if ci { (s.to_lowercase(), pattern.to_lowercase()) } else { (s.to_string(), pattern.to_string()) };
let parts: Vec<&str> = pattern.split('%').collect();
if parts.len() == 1 {
return s == pattern;
}
let head = parts[0];
let Some(mut rest) = s.strip_prefix(head) else { return false };
for mid in &parts[1..parts.len() - 1] {
match rest.find(mid) {
Some(i) => rest = &rest[i + mid.len()..],
None => return false,
}
}
rest.ends_with(parts[parts.len() - 1])
}
pub fn match_pred(p: &Pred, id: &str, row: &JsonMap, resolve: Option<LinkResolver<'_>>) -> Option<bool> {
match p {
Pred::True => Some(true),
Pred::False => Some(false),
Pred::And(args) => {
let mut unknown = false;
for a in args {
match match_pred(a, id, row, resolve) {
Some(false) => return Some(false),
None => unknown = true,
_ => {}
}
}
(!unknown).then_some(true)
}
Pred::Or(args) => {
let mut unknown = false;
for a in args {
match match_pred(a, id, row, resolve) {
Some(true) => return Some(true),
None => unknown = true,
_ => {}
}
}
(!unknown).then_some(false)
}
Pred::Not(a) => match_pred(a, id, row, resolve).map(|m| !m),
Pred::IsNull { field, ty } => Some(if *ty == ValueType::Json {
row.get(field).is_none_or(Value::is_null)
} else {
field_value(row, id, field, *ty).is_none()
}),
Pred::Cmp { field, ty, op, value } => {
let Some(v) = field_value(row, id, field, *ty) else { return Some(*op == CmpOp::Ne) };
let c = compare(&v, value);
Some(match op {
CmpOp::Eq => c == Ordering::Equal,
CmpOp::Ne => c != Ordering::Equal,
CmpOp::Gt => c == Ordering::Greater,
CmpOp::Gte => c != Ordering::Less,
CmpOp::Lt => c == Ordering::Less,
CmpOp::Lte => c != Ordering::Greater,
})
}
Pred::In { field, ty, values } => {
let v = field_value(row, id, field, *ty);
Some(v.is_some_and(|v| values.iter().any(|w| compare(&v, w) == Ordering::Equal)))
}
Pred::Like { field, pattern, ci } => Some(match field_value(row, id, field, ValueType::String) {
Some(Scalar::Str(v)) => like(&v, pattern, *ci),
_ => false,
}),
Pred::Link { field, table, pred } => {
let Some(Scalar::Str(target)) = field_value(row, id, field, ValueType::String) else { return Some(false) };
resolve.and_then(|r| r(table, &target, pred))
}
}
}
pub fn compare_rows(o: Option<&QueryOrder>, a: (&str, &JsonMap), b: (&str, &JsonMap)) -> Ordering {
let by_id = a.0.as_bytes().cmp(b.0.as_bytes());
let Some(o) = o else { return by_id };
let mut c = Ordering::Equal;
if o.field != "id" {
let va = field_value(a.1, a.0, &o.field, o.ty);
let vb = field_value(b.1, b.0, &o.field, o.ty);
c = match (&va, &vb) {
(None, Some(_)) => Ordering::Greater,
(Some(_), None) => Ordering::Less,
(Some(x), Some(y)) => compare(x, y),
(None, None) => Ordering::Equal,
};
}
if c == Ordering::Equal {
c = by_id;
}
if o.desc {
c.reverse()
} else {
c
}
}
fn effective_order(n: &QNode) -> QueryOrder {
let o = n.order.clone().unwrap_or(QueryOrder { field: "id".into(), ty: ValueType::String, desc: false });
if n.before.is_some() {
QueryOrder { desc: !o.desc, ..o }
} else {
o
}
}
fn after_cursor(o: &QueryOrder, c: &Cursor, id: &str, row: &JsonMap) -> bool {
let mut cursor_row = JsonMap::new();
if o.field != "id" {
if let Some(v) = &c.value {
let jv = match v {
Scalar::Str(s) => Value::String(s.clone()),
Scalar::Bool(b) => Value::Bool(*b),
Scalar::Num(n) if o.ty == ValueType::Datetime => Value::String(format_datetime(*n)),
Scalar::Num(n) => json!(n),
};
cursor_row.insert(o.field.clone(), jv);
}
}
compare_rows(Some(o), (id, row), (&c.id, &cursor_row)) == Ordering::Greater
}
fn format_datetime(ms: f64) -> String {
let ms = ms as i64;
let (days, rem) = (ms.div_euclid(86_400_000), ms.rem_euclid(86_400_000));
let z = days + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!(
"{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{:03}Z",
rem / 3_600_000,
rem / 60_000 % 60,
rem / 1000 % 60,
rem % 1000
)
}
pub fn cursor_of(n: &QNode, id: &str, row: &JsonMap) -> String {
match &n.order {
Some(o) if o.field != "id" => {
let v = field_value(row, id, &o.field, o.ty).and_then(|_| row.get(&o.field));
encode_cursor(v, id)
}
_ => encode_cursor(None, id),
}
}
pub trait QuerySource {
fn rows(&self, table: &str) -> Vec<JsonMap>;
fn confirmed(&self, _table: &str, _id: &str) -> bool {
false
}
fn complete(&self, _table: &str) -> bool {
true
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PageInfo {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub start_cursor: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub end_cursor: Option<String>,
pub has_more: bool,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct QueryResult {
pub data: BTreeMap<String, Vec<Value>>,
pub page_info: BTreeMap<String, PageInfo>,
}
type TableRows = std::rc::Rc<Vec<(String, JsonMap)>>;
struct Eval<'a> {
src: &'a dyn QuerySource,
tables: std::cell::RefCell<HashMap<String, TableRows>>,
}
impl Eval<'_> {
fn table(&self, t: &str) -> TableRows {
if let Some(r) = self.tables.borrow().get(t) {
return r.clone();
}
let rows: Vec<(String, JsonMap)> = self
.src
.rows(t)
.into_iter()
.filter_map(|mut r| {
let id = r.remove("id")?.as_str()?.to_string();
Some((id, r))
})
.collect();
let rows = std::rc::Rc::new(rows);
self.tables.borrow_mut().insert(t.to_string(), rows.clone());
rows
}
fn row(&self, t: &str, id: &str) -> Option<JsonMap> {
self.table(t).iter().find(|(i, _)| i == id).map(|(_, r)| r.clone())
}
fn resolve(&self, table: &str, id: &str, pred: &Pred) -> Option<bool> {
match self.row(table, id) {
Some(r) => match_pred(pred, id, &r, Some(&|t: &str, i: &str, p: &Pred| self.resolve(t, i, p))),
None if !self.src.complete(table) => None,
None => Some(false),
}
}
fn include(&self, table: &str, pred: &Pred, id: &str, row: &JsonMap) -> bool {
match match_pred(pred, id, row, Some(&|t: &str, i: &str, p: &Pred| self.resolve(t, i, p))) {
Some(m) => m,
None => self.src.confirmed(table, id),
}
}
fn build(&self, n: &QNode, id: &str, row: &JsonMap) -> Value {
let mut obj = Map::new();
for (k, v) in row {
if k == "id" || n.fields.as_ref().is_some_and(|f| !f.contains(k)) {
continue;
}
obj.insert(k.clone(), v.clone());
}
obj.insert("id".into(), Value::String(id.to_string()));
for c in &n.children {
match c.link.as_ref().expect("nested nodes have links") {
Link::Forward(col) => {
let target = match field_value(row, id, col, ValueType::String) {
Some(Scalar::Str(t)) => self.row(&c.table, &t).map(|r| (t, r)),
_ => None,
};
let v = match target {
Some((tid, tr)) if self.include(&c.table, &c.pred, &tid, &tr) => self.build(c, &tid, &tr),
_ => Value::Null,
};
obj.insert(c.key.clone(), v);
}
Link::Reverse(col) => {
let rows = self.table(&c.table);
let mut kids: Vec<&(String, JsonMap)> = rows
.iter()
.filter(|(kid, k)| {
k.get(col).and_then(Value::as_str) == Some(id) && self.include(&c.table, &c.pred, kid, k)
})
.collect();
kids.sort_by(|a, b| compare_rows(c.order.as_ref(), (&a.0, &a.1), (&b.0, &b.1)));
let list = kids.iter().map(|(kid, k)| self.build(c, kid, k)).collect();
obj.insert(c.key.clone(), Value::Array(list));
}
}
}
Value::Object(obj)
}
}
pub fn evaluate_query(q: &CompiledQuery, src: &dyn QuerySource) -> QueryResult {
let ev = Eval { src, tables: Default::default() };
let mut out = QueryResult::default();
for root in &q.roots {
let order = effective_order(root);
let cursor = root.after.as_ref().or(root.before.as_ref());
let all = ev.table(&root.table);
let mut rows: Vec<&(String, JsonMap)> = all
.iter()
.filter(|(id, r)| ev.include(&root.table, &root.pred, id, r))
.filter(|(id, r)| cursor.is_none_or(|c| after_cursor(&order, c, id, r)))
.collect();
rows.sort_by(|a, b| compare_rows(Some(&order), (&a.0, &a.1), (&b.0, &b.1)));
let mut has_more = false;
if root.limit > 0 && rows.len() as u64 > root.limit {
rows.truncate(root.limit as usize);
has_more = true;
}
if root.before.is_some() {
rows.reverse();
}
out.data.insert(root.key.clone(), rows.iter().map(|(id, r)| ev.build(root, id, r)).collect());
out.page_info.insert(
root.key.clone(),
PageInfo {
has_more,
start_cursor: rows.first().map(|(id, r)| cursor_of(root, id, r)),
end_cursor: rows.last().map(|(id, r)| cursor_of(root, id, r)),
},
);
}
out
}
pub fn row_matches(q: &CompiledQuery, src: &dyn QuerySource, table: &str, id: &str, row: &JsonMap) -> Option<bool> {
let ev = Eval { src, tables: Default::default() };
let mut out = Some(false);
for root in q.roots.iter().filter(|r| r.table == table) {
match match_pred(&root.pred, id, row, Some(&|t: &str, i: &str, p: &Pred| ev.resolve(t, i, p))) {
Some(true) => return Some(true),
None => out = None,
Some(false) => {}
}
}
out
}
pub fn canonical_json(v: &Value) -> String {
match v {
Value::Array(a) => format!("[{}]", a.iter().map(canonical_json).collect::<Vec<_>>().join(",")),
Value::Object(o) => format!(
"{{{}}}",
sorted_keys(o)
.into_iter()
.map(|k| format!("{}:{}", Value::String(k.clone()), canonical_json(&o[k])))
.collect::<Vec<_>>()
.join(",")
),
v => v.to_string(),
}
}
pub fn query_id(space_id: &str, query: &Value, params: Option<&Value>) -> String {
let s = format!("{space_id}\u{0}{}\u{0}{}", canonical_json(query), canonical_json(params.unwrap_or(&Value::Null)));
let units: Vec<u16> = s.encode_utf16().collect();
let mut h1: u32 = 0x811c_9dc5;
let mut h2: u32 = 0x0100_0193 ^ units.len() as u32;
for c in units {
h1 = (h1 ^ c as u32).wrapping_mul(0x0100_0193);
h2 = (h2 ^ c as u32).wrapping_mul(0x5bd1_e995);
}
format!("q{h1:08x}{h2:08x}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn datetimes_parse_and_round_trip() {
assert_eq!(parse_datetime("1970-01-01T00:00:00Z"), Some(0.0));
assert_eq!(parse_datetime("2026-01-01T11:30:00+01:00"), parse_datetime("2026-01-01T10:30:00Z"));
assert_eq!(parse_datetime("2025-12-31T23:59:59.500Z"), Some(1_767_225_599_500.0));
assert_eq!(parse_datetime("2026-02-30T00:00:00Z"), None);
assert_eq!(parse_datetime("2026-01-01 00:00:00Z"), None);
for ms in [0.0, 1_767_225_599_500.0, -86_400_001.0] {
assert_eq!(parse_datetime(&format_datetime(ms)), Some(ms));
}
}
#[test]
fn like_patterns() {
assert!(like("100% juice", "100%", false));
assert!(like("Apple", "a%", true));
assert!(!like("Apple", "a%", false));
assert!(like("a_b", "a_b", false));
assert!(!like("a", "a%a", false));
}
#[test]
fn query_ids_are_stable() {
let q = json!({"b": {}, "a": {"$": {"limit": 2}}});
let r = json!({"a": {"$": {"limit": 2}}, "b": {}});
assert_eq!(query_id("s1", &q, None), query_id("s1", &r, None));
assert_ne!(query_id("s1", &q, None), query_id("s2", &q, None));
assert_eq!(query_id("s1", &q, None).len(), 17);
}
}