diff --git a/benches/minigraf_bench.rs b/benches/minigraf_bench.rs index 6549afeb5e..58c47b869a 100644 --- a/benches/minigraf_bench.rs +++ b/benches/minigraf_bench.rs @@ -19,7 +19,7 @@ mod helpers; -use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; +use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; use minigraf::OpenOptions; // ── Task 3: insert/ ─────────────────────────────────────────────────────────── diff --git a/src/db.rs b/src/db.rs index 0b345711f6..bcdb722432 100644 --- a/src/db.rs +++ b/src/db.rs @@ -538,6 +538,46 @@ impl Minigraf { Ok(()) } + /// Parse and plan a query once; bind slots (`$name`) are left unresolved. + /// + /// Returns a [`crate::query::datalog::prepared::PreparedQuery`] that can be executed + /// many times with different bind values via + /// [`crate::query::datalog::prepared::PreparedQuery::execute`]. + /// + /// # Errors + /// - Parse failure. + /// - A bind slot appears in an attribute position (rejected at prepare time). + /// - The command is not a `(query ...)` — `transact`, `retract`, and `rule` + /// are not preparable. + pub fn prepare( + &self, + query_str: &str, + ) -> Result { + use crate::query::datalog::prepared::prepare_query; + + let cmd = parse_datalog_command(query_str).map_err(|e| anyhow::anyhow!("{}", e))?; + + let query = match cmd { + DatalogCommand::Query(q) => q, + DatalogCommand::Transact(_) => { + anyhow::bail!("only (query ...) commands can be prepared; got transact") + } + DatalogCommand::Retract(_) => { + anyhow::bail!("only (query ...) commands can be prepared; got retract") + } + DatalogCommand::Rule(_) => { + anyhow::bail!("only (query ...) commands can be prepared; got rule") + } + }; + + prepare_query( + query, + self.inner.fact_storage.clone(), + self.inner.rules.clone(), + self.inner.functions.clone(), + ) + } + /// Returns a clone of the underlying `FactStorage` for use by the REPL. /// /// Cloning is cheap — `FactStorage` is `Arc`-backed. diff --git a/src/graph/storage.rs b/src/graph/storage.rs index 54bfb80a55..0de4e8852c 100644 --- a/src/graph/storage.rs +++ b/src/graph/storage.rs @@ -319,6 +319,9 @@ impl FactStorage { .filter(|f| match as_of { AsOf::Counter(n) => f.tx_count <= *n, AsOf::Timestamp(t) => f.tx_id <= *t as u64, + AsOf::Slot(_) => { + panic!("internal: unsubstituted :as-of bind slot reached get_facts_as_of"); + } }) .collect(); Ok(filtered) diff --git a/src/lib.rs b/src/lib.rs index 4e28f95f2b..4e290bf414 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -35,3 +35,6 @@ pub use query::{ // Bi-temporal query types (Phase 4+) pub use query::datalog::types::{AsOf, ValidAt}; + +// Prepared statements (Phase 7.8) +pub use query::datalog::prepared::{BindValue, PreparedQuery}; diff --git a/src/query/datalog/executor.rs b/src/query/datalog/executor.rs index 332bf5b897..f37842e27a 100644 --- a/src/query/datalog/executor.rs +++ b/src/query/datalog/executor.rs @@ -217,6 +217,9 @@ impl DatalogExecutor { .filter(|f| f.valid_from <= *t && *t < f.valid_to) .collect(), Some(ValidAt::AnyValidTime) => asserted, + Some(ValidAt::Slot(_)) => { + panic!("internal: unsubstituted :valid-at bind slot reached the executor"); + } None => asserted .into_iter() .filter(|f| f.valid_from <= now && now < f.valid_to) @@ -239,6 +242,9 @@ impl DatalogExecutor { let valid_at_value = match &query.valid_at { Some(ValidAt::Timestamp(t)) => Value::Integer(*t), Some(ValidAt::AnyValidTime) => Value::Null, + Some(ValidAt::Slot(_)) => { + panic!("internal: unsubstituted :valid-at bind slot reached the executor"); + } None => Value::Integer(now), }; @@ -365,6 +371,9 @@ impl DatalogExecutor { let valid_at_value = match &query.valid_at { Some(ValidAt::Timestamp(t)) => Value::Integer(*t), Some(ValidAt::AnyValidTime) => Value::Null, + Some(ValidAt::Slot(_)) => { + panic!("internal: unsubstituted :valid-at bind slot reached the executor"); + } None => Value::Integer(now), }; @@ -1085,6 +1094,9 @@ pub(crate) fn evaluate_branch( let branch_valid_at_value = match &valid_at { Some(ValidAt::Timestamp(t)) => Value::Integer(*t), Some(ValidAt::AnyValidTime) => Value::Null, + Some(ValidAt::Slot(_)) => { + panic!("internal: unsubstituted :valid-at bind slot reached the executor"); + } None => Value::Integer(tx_id_now() as i64), }; @@ -1432,6 +1444,9 @@ pub(crate) fn eval_expr( let r = eval_expr(rhs, binding, registry)?; eval_binop(op, l, r) } + Expr::Slot(_) => { + panic!("internal: unsubstituted bind slot reached eval_expr"); + } } } diff --git a/src/query/datalog/mod.rs b/src/query/datalog/mod.rs index 6656fde269..0dc0613e83 100644 --- a/src/query/datalog/mod.rs +++ b/src/query/datalog/mod.rs @@ -4,6 +4,7 @@ pub mod functions; pub mod matcher; pub mod optimizer; pub mod parser; +pub mod prepared; pub mod rules; pub mod stratification; pub mod types; diff --git a/src/query/datalog/parser.rs b/src/query/datalog/parser.rs index 610aad2dac..9baba4c9dc 100644 --- a/src/query/datalog/parser.rs +++ b/src/query/datalog/parser.rs @@ -24,6 +24,7 @@ enum Token { Boolean(bool), TaggedLiteral(String), // e.g., "#uuid" Nil, + BindSlot(String), // $identifier — named bind slot for PreparedQuery } /// Tokenize EDN input @@ -219,6 +220,31 @@ fn tokenize(input: &str) -> Result, String> { return Err("Unexpected character: !".to_string()); } } + '$' => { + chars.next(); // consume '$' + let mut name = String::new(); + while let Some(&ch) = chars.peek() { + if ch.is_alphanumeric() || ch == '_' || ch == '-' { + if name.len() >= MAX_SYMBOL_LENGTH { + return Err(format!( + "Bind slot name exceeds maximum length of {} bytes", + MAX_SYMBOL_LENGTH + )); + } + name.push(ch); + chars.next(); + } else { + break; + } + } + if name.is_empty() { + return Err( + "Bind slot '$' must be followed by an identifier (e.g. $entity)" + .to_string(), + ); + } + tokens.push(Token::BindSlot(name)); + } _ => { return Err(format!("Unexpected character: {}", ch)); } @@ -384,6 +410,13 @@ impl Parser { self.advance(); Ok(EdnValue::Nil) } + Some(Token::BindSlot(_)) => { + if let Some(Token::BindSlot(name)) = self.advance() { + Ok(EdnValue::BindSlot(name)) + } else { + unreachable!() + } + } Some(token) => Err(format!("Unexpected token: {:?}", token)), None => Err("Unexpected end of input".to_string()), } @@ -676,6 +709,7 @@ fn parse_query(elements: &[EdnValue]) -> Result { let ts = parse_timestamp(s).map_err(|e| e.to_string())?; AsOf::Timestamp(ts) } + EdnValue::BindSlot(name) => AsOf::Slot(name.clone()), other => { return Err(format!( ":as-of must be an integer (counter) or ISO 8601 string, got {:?}", @@ -698,6 +732,7 @@ fn parse_query(elements: &[EdnValue]) -> Result { ValidAt::Timestamp(ts) } EdnValue::Keyword(k) if k == ":any-valid-time" => ValidAt::AnyValidTime, + EdnValue::BindSlot(name) => ValidAt::Slot(name.clone()), other => { return Err(format!( ":valid-at must be an ISO 8601 string or :any-valid-time, got {:?}", @@ -981,6 +1016,7 @@ fn parse_expr_arg(edn: &EdnValue) -> Result { EdnValue::Nil => Ok(Expr::Lit(Value::Null)), EdnValue::Keyword(k) => Ok(Expr::Lit(Value::Keyword(k.clone()))), EdnValue::List(inner) => parse_expr(inner), + EdnValue::BindSlot(name) => Ok(Expr::Slot(name.clone())), other => Err(format!("unsupported expression argument: {:?}", other)), } } @@ -1492,6 +1528,7 @@ fn expr_vars(expr: &Expr) -> Vec { v } Expr::UnaryOp(_, arg) => expr_vars(arg), + Expr::Slot(_) => vec![], } } @@ -2667,6 +2704,112 @@ mod tests { "pseudo-attr in value position should error" ); } + + #[test] + fn test_tokenize_bind_slot() { + let result = parse_edn("$entity"); + assert!( + matches!(result, Ok(EdnValue::BindSlot(ref s)) if s == "entity"), + "expected BindSlot" + ); + } + + #[test] + fn test_tokenize_bind_slot_hyphenated() { + let result = parse_edn("$min-level"); + assert!( + matches!(result, Ok(EdnValue::BindSlot(ref s)) if s == "min-level"), + "expected BindSlot(min-level)" + ); + } + + #[test] + fn test_parse_bind_slot_in_entity_position() { + let cmd = + parse_datalog_command("(query [:find ?name :where [$entity :person/name ?name]])"); + assert!(cmd.is_ok(), "parse failed"); + match cmd.unwrap() { + DatalogCommand::Query(q) => match &q.where_clauses[0] { + WhereClause::Pattern(p) => { + assert!(matches!(&p.entity, EdnValue::BindSlot(s) if s == "entity")); + } + _ => panic!("expected Pattern"), + }, + _ => panic!("expected Query"), + } + } + + #[test] + fn test_parse_bind_slot_in_value_position() { + let cmd = parse_datalog_command("(query [:find ?e :where [?e :person/name $name]])"); + assert!(cmd.is_ok(), "parse failed"); + match cmd.unwrap() { + DatalogCommand::Query(q) => match &q.where_clauses[0] { + WhereClause::Pattern(p) => { + assert!(matches!(&p.value, EdnValue::BindSlot(s) if s == "name")); + } + _ => panic!("expected Pattern"), + }, + _ => panic!("expected Query"), + } + } + + #[test] + fn test_parse_as_of_slot() { + let cmd = parse_datalog_command("(query [:find ?v :as-of $tx :where [?e :score ?v]])"); + assert!(cmd.is_ok(), "parse failed"); + match cmd.unwrap() { + DatalogCommand::Query(q) => { + assert!(matches!(q.as_of, Some(AsOf::Slot(ref s)) if s == "tx")); + } + _ => panic!("expected Query"), + } + } + + #[test] + fn test_parse_valid_at_slot() { + let cmd = parse_datalog_command("(query [:find ?v :valid-at $date :where [?e :score ?v]])"); + assert!(cmd.is_ok(), "parse failed"); + match cmd.unwrap() { + DatalogCommand::Query(q) => { + assert!(matches!(q.valid_at, Some(ValidAt::Slot(ref s)) if s == "date")); + } + _ => panic!("expected Query"), + } + } + + #[test] + fn test_parse_expr_bind_slot_in_binop() { + let cmd = parse_datalog_command( + "(query [:any-valid-time :find ?v :where [?e :score ?v] [(>= ?v $threshold)]])", + ); + assert!(cmd.is_ok(), "parse failed"); + match cmd.unwrap() { + DatalogCommand::Query(q) => { + let expr_clause = q + .where_clauses + .iter() + .find(|c| matches!(c, WhereClause::Expr { .. })); + assert!(expr_clause.is_some(), "no Expr clause found"); + match expr_clause.unwrap() { + WhereClause::Expr { + expr: Expr::BinOp(_, _, rhs), + .. + } => { + assert!(matches!(rhs.as_ref(), Expr::Slot(s) if s == "threshold")); + } + _other => panic!("expected BinOp Expr clause"), + } + } + _ => panic!("expected Query"), + } + } + + #[test] + fn test_parse_bind_slot_empty_name_is_error() { + let result = parse_edn("$"); + assert!(result.is_err(), "bare '$' should be a parse error"); + } } #[cfg(test)] diff --git a/src/query/datalog/prepared.rs b/src/query/datalog/prepared.rs new file mode 100644 index 0000000000..cf193d7f86 --- /dev/null +++ b/src/query/datalog/prepared.rs @@ -0,0 +1,682 @@ +use crate::graph::FactStorage; +use crate::graph::types::Value; +use crate::query::datalog::executor::{DatalogExecutor, QueryResult}; +use crate::query::datalog::functions::FunctionRegistry; +use crate::query::datalog::rules::RuleRegistry; +use crate::query::datalog::types::{ + AsOf, AttributeSpec, DatalogCommand, DatalogQuery, EdnValue, Expr, ValidAt, WhereClause, +}; +use anyhow::Result; +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, RwLock}; +use uuid::Uuid; + +// ─── BindValue ──────────────────────────────────────────────────────────────── + +/// A concrete value supplied to a named bind slot (`$name`) in a `PreparedQuery`. +#[derive(Debug, Clone)] +pub enum BindValue { + /// Substituted into an entity position: `[$entity :attr ?v]`. + /// Not accepted in rule invocation argument positions — use `Val(Value::Ref(...))` there. + Entity(Uuid), + /// Substituted into a value position `[?e :attr $val]` or an expression literal. + Val(Value), + /// Substituted into an `:as-of $tx` slot (monotonic transaction counter). + TxCount(u64), + /// Substituted into an `:as-of $tx` slot (wall-clock millis) or `:valid-at $date` slot. + Timestamp(i64), + /// Substituted into a `:valid-at $date` slot — disables valid-time filtering. + AnyValidTime, +} + +fn bind_value_type_name(bv: &BindValue) -> &'static str { + match bv { + BindValue::Entity(_) => "Entity", + BindValue::Val(_) => "Val", + BindValue::TxCount(_) => "TxCount", + BindValue::Timestamp(_) => "Timestamp", + BindValue::AnyValidTime => "AnyValidTime", + } +} + +// ─── PreparedQuery ──────────────────────────────────────────────────────────── + +/// A parsed query template with named bind slots (`$name`). +/// +/// Obtain via [`crate::db::Minigraf::prepare`]. +/// Execute many times via [`PreparedQuery::execute`]. +pub struct PreparedQuery { + template: DatalogQuery, + slot_names: Vec, + fact_storage: FactStorage, + rules: Arc>, + functions: Arc>, +} + +impl std::fmt::Debug for PreparedQuery { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PreparedQuery") + .field("slot_names", &self.slot_names) + .finish_non_exhaustive() + } +} + +impl PreparedQuery { + /// Substitute bind values and execute against the current database state. + /// + /// Extra bindings not referenced by the query are silently ignored. + /// + /// # Errors + /// - Missing bind value for a slot present in the query. + /// - Type mismatch (e.g. `Val` supplied for an `:as-of` slot). + pub fn execute(&self, bindings: &[(&str, BindValue)]) -> Result { + let binding_map: HashMap<&str, &BindValue> = + bindings.iter().map(|(name, val)| (*name, val)).collect(); + + for name in &self.slot_names { + if !binding_map.contains_key(name.as_str()) { + anyhow::bail!("missing bind value for slot '${}'", name); + } + } + + let filled_query = substitute(&self.template, &binding_map)?; + + let executor = DatalogExecutor::new_with_rules_and_functions( + self.fact_storage.clone(), + self.rules.clone(), + self.functions.clone(), + ); + executor.execute(DatalogCommand::Query(filled_query)) + } +} + +// ─── Internal constructor ───────────────────────────────────────────────────── + +pub(crate) fn prepare_query( + query: DatalogQuery, + fact_storage: FactStorage, + rules: Arc>, + functions: Arc>, +) -> Result { + validate_no_attribute_slots(&query)?; + let slot_names = collect_slot_names(&query); + Ok(PreparedQuery { + template: query, + slot_names, + fact_storage, + rules, + functions, + }) +} + +// ─── Validation ─────────────────────────────────────────────────────────────── + +fn validate_no_attribute_slots(query: &DatalogQuery) -> Result<()> { + validate_clauses_no_attr_slots(&query.where_clauses) +} + +fn validate_clauses_no_attr_slots(clauses: &[WhereClause]) -> Result<()> { + for clause in clauses { + match clause { + WhereClause::Pattern(p) => { + if let AttributeSpec::Real(EdnValue::BindSlot(name)) = &p.attribute { + anyhow::bail!( + "bind slot '${name}' is not permitted in attribute position; \ + the query optimizer selects an index based on the attribute at \ + prepare time and cannot handle a parameterised attribute" + ); + } + } + WhereClause::Not(inner) => validate_clauses_no_attr_slots(inner)?, + WhereClause::NotJoin { clauses: inner, .. } => validate_clauses_no_attr_slots(inner)?, + WhereClause::Or(branches) => { + for b in branches { + validate_clauses_no_attr_slots(b)?; + } + } + WhereClause::OrJoin { branches, .. } => { + for b in branches { + validate_clauses_no_attr_slots(b)?; + } + } + WhereClause::Expr { .. } | WhereClause::RuleInvocation { .. } => {} + } + } + Ok(()) +} + +// ─── Slot collection ────────────────────────────────────────────────────────── + +fn collect_slot_names(query: &DatalogQuery) -> Vec { + let mut names: HashSet = HashSet::new(); + if let Some(AsOf::Slot(name)) = &query.as_of { + names.insert(name.clone()); + } + if let Some(ValidAt::Slot(name)) = &query.valid_at { + names.insert(name.clone()); + } + collect_slots_from_clauses(&query.where_clauses, &mut names); + let mut result: Vec = names.into_iter().collect(); + result.sort(); + result +} + +fn collect_slots_from_clauses(clauses: &[WhereClause], names: &mut HashSet) { + for clause in clauses { + match clause { + WhereClause::Pattern(p) => { + if let EdnValue::BindSlot(name) = &p.entity { + names.insert(name.clone()); + } + if let EdnValue::BindSlot(name) = &p.value { + names.insert(name.clone()); + } + } + WhereClause::Not(inner) => collect_slots_from_clauses(inner, names), + WhereClause::NotJoin { clauses: inner, .. } => collect_slots_from_clauses(inner, names), + WhereClause::Or(branches) => { + for b in branches { + collect_slots_from_clauses(b, names); + } + } + WhereClause::OrJoin { branches, .. } => { + for b in branches { + collect_slots_from_clauses(b, names); + } + } + WhereClause::Expr { expr, .. } => collect_slots_from_expr(expr, names), + WhereClause::RuleInvocation { args, .. } => { + for arg in args { + if let EdnValue::BindSlot(name) = arg { + names.insert(name.clone()); + } + } + } + } + } +} + +fn collect_slots_from_expr(expr: &Expr, names: &mut HashSet) { + match expr { + Expr::Slot(name) => { + names.insert(name.clone()); + } + Expr::BinOp(_, l, r) => { + collect_slots_from_expr(l, names); + collect_slots_from_expr(r, names); + } + Expr::UnaryOp(_, arg) => collect_slots_from_expr(arg, names), + Expr::Var(_) | Expr::Lit(_) => {} + } +} + +// ─── Substitution ───────────────────────────────────────────────────────────── + +fn substitute( + template: &DatalogQuery, + bindings: &HashMap<&str, &BindValue>, +) -> Result { + let mut query = template.clone(); + + if let Some(AsOf::Slot(name)) = query.as_of.take() { + query.as_of = Some(resolve_as_of_slot(&name, bindings)?); + } + + if let Some(ValidAt::Slot(name)) = query.valid_at.take() { + query.valid_at = Some(resolve_valid_at_slot(&name, bindings)?); + } + + for clause in &mut query.where_clauses { + substitute_where_clause(clause, bindings)?; + } + + Ok(query) +} + +fn substitute_where_clause( + clause: &mut WhereClause, + bindings: &HashMap<&str, &BindValue>, +) -> Result<()> { + match clause { + WhereClause::Pattern(p) => substitute_pattern(p, bindings), + WhereClause::Not(clauses) => { + for c in clauses { + substitute_where_clause(c, bindings)?; + } + Ok(()) + } + WhereClause::NotJoin { clauses, .. } => { + for c in clauses { + substitute_where_clause(c, bindings)?; + } + Ok(()) + } + WhereClause::Or(branches) => { + for branch in branches { + for c in branch { + substitute_where_clause(c, bindings)?; + } + } + Ok(()) + } + WhereClause::OrJoin { branches, .. } => { + for branch in branches { + for c in branch { + substitute_where_clause(c, bindings)?; + } + } + Ok(()) + } + WhereClause::Expr { expr, .. } => substitute_expr(expr, bindings), + WhereClause::RuleInvocation { args, .. } => { + for arg in args { + substitute_edn_value(arg, bindings)?; + } + Ok(()) + } + } +} + +fn substitute_pattern( + p: &mut crate::query::datalog::types::Pattern, + bindings: &HashMap<&str, &BindValue>, +) -> Result<()> { + if let EdnValue::BindSlot(name) = &p.entity { + let name = name.clone(); + p.entity = resolve_entity_slot(&name, bindings)?; + } + if let EdnValue::BindSlot(name) = &p.value { + let name = name.clone(); + p.value = resolve_value_slot(&name, bindings)?; + } + Ok(()) +} + +fn substitute_expr(expr: &mut Expr, bindings: &HashMap<&str, &BindValue>) -> Result<()> { + match expr { + Expr::Slot(name) => { + let name = name.clone(); + *expr = Expr::Lit(resolve_val_slot(&name, bindings)?); + Ok(()) + } + Expr::BinOp(_, lhs, rhs) => { + substitute_expr(lhs, bindings)?; + substitute_expr(rhs, bindings) + } + Expr::UnaryOp(_, arg) => substitute_expr(arg, bindings), + Expr::Var(_) | Expr::Lit(_) => Ok(()), + } +} + +fn substitute_edn_value(val: &mut EdnValue, bindings: &HashMap<&str, &BindValue>) -> Result<()> { + if let EdnValue::BindSlot(name) = val { + let name = name.clone(); + *val = resolve_value_slot(&name, bindings)?; + } + Ok(()) +} + +// ─── Slot resolvers ─────────────────────────────────────────────────────────── + +fn resolve_entity_slot(name: &str, bindings: &HashMap<&str, &BindValue>) -> Result { + match bindings.get(name) { + Some(BindValue::Entity(u)) => Ok(EdnValue::Uuid(*u)), + Some(other) => anyhow::bail!( + "slot '${name}' in entity position requires Entity, got {}", + bind_value_type_name(other) + ), + None => anyhow::bail!("missing bind value for slot '${name}'"), + } +} + +fn resolve_value_slot(name: &str, bindings: &HashMap<&str, &BindValue>) -> Result { + match bindings.get(name) { + Some(BindValue::Val(v)) => Ok(value_to_edn(v)), + Some(other) => anyhow::bail!( + "slot '${name}' in value position requires Val, got {}", + bind_value_type_name(other) + ), + None => anyhow::bail!("missing bind value for slot '${name}'"), + } +} + +fn resolve_val_slot(name: &str, bindings: &HashMap<&str, &BindValue>) -> Result { + match bindings.get(name) { + Some(BindValue::Val(v)) => Ok(v.clone()), + Some(other) => anyhow::bail!( + "slot '${name}' in expression position requires Val, got {}", + bind_value_type_name(other) + ), + None => anyhow::bail!("missing bind value for slot '${name}'"), + } +} + +fn resolve_as_of_slot(name: &str, bindings: &HashMap<&str, &BindValue>) -> Result { + match bindings.get(name) { + Some(BindValue::TxCount(n)) => Ok(AsOf::Counter(*n)), + Some(BindValue::Timestamp(t)) => Ok(AsOf::Timestamp(*t)), + Some(other) => anyhow::bail!( + "slot '${name}' in :as-of position requires TxCount or Timestamp, got {}", + bind_value_type_name(other) + ), + None => anyhow::bail!("missing bind value for slot '${name}'"), + } +} + +fn resolve_valid_at_slot(name: &str, bindings: &HashMap<&str, &BindValue>) -> Result { + match bindings.get(name) { + Some(BindValue::Timestamp(t)) => Ok(ValidAt::Timestamp(*t)), + Some(BindValue::AnyValidTime) => Ok(ValidAt::AnyValidTime), + Some(other) => anyhow::bail!( + "slot '${name}' in :valid-at position requires Timestamp or AnyValidTime, got {}", + bind_value_type_name(other) + ), + None => anyhow::bail!("missing bind value for slot '${name}'"), + } +} + +fn value_to_edn(v: &Value) -> EdnValue { + match v { + Value::String(s) => EdnValue::String(s.clone()), + Value::Integer(i) => EdnValue::Integer(*i), + Value::Float(f) => EdnValue::Float(*f), + Value::Boolean(b) => EdnValue::Boolean(*b), + Value::Keyword(k) => EdnValue::Keyword(k.clone()), + Value::Ref(u) => EdnValue::Uuid(*u), + Value::Null => EdnValue::Nil, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::query::datalog::types::{BinOp, FindSpec, Pattern}; + + fn make_query_entity_slot() -> DatalogQuery { + DatalogQuery::new( + vec![FindSpec::Variable("?name".to_string())], + vec![WhereClause::Pattern(Pattern::new( + EdnValue::BindSlot("entity".to_string()), + EdnValue::Keyword(":person/name".to_string()), + EdnValue::Symbol("?name".to_string()), + ))], + ) + } + + fn make_query_value_slot() -> DatalogQuery { + DatalogQuery::new( + vec![FindSpec::Variable("?e".to_string())], + vec![WhereClause::Pattern(Pattern::new( + EdnValue::Symbol("?e".to_string()), + EdnValue::Keyword(":person/name".to_string()), + EdnValue::BindSlot("name".to_string()), + ))], + ) + } + + fn make_query_attr_slot() -> DatalogQuery { + DatalogQuery::new( + vec![FindSpec::Variable("?v".to_string())], + vec![WhereClause::Pattern(Pattern::new( + EdnValue::Symbol("?e".to_string()), + EdnValue::BindSlot("attr".to_string()), + EdnValue::Symbol("?v".to_string()), + ))], + ) + } + + fn make_query_as_of_slot() -> DatalogQuery { + let mut q = DatalogQuery::new( + vec![FindSpec::Variable("?v".to_string())], + vec![WhereClause::Pattern(Pattern::new( + EdnValue::Symbol("?e".to_string()), + EdnValue::Keyword(":score".to_string()), + EdnValue::Symbol("?v".to_string()), + ))], + ); + q.as_of = Some(AsOf::Slot("tx".to_string())); + q + } + + fn make_query_valid_at_slot() -> DatalogQuery { + let mut q = DatalogQuery::new( + vec![FindSpec::Variable("?v".to_string())], + vec![WhereClause::Pattern(Pattern::new( + EdnValue::Symbol("?e".to_string()), + EdnValue::Keyword(":score".to_string()), + EdnValue::Symbol("?v".to_string()), + ))], + ); + q.valid_at = Some(ValidAt::Slot("date".to_string())); + q + } + + fn make_query_expr_slot() -> DatalogQuery { + DatalogQuery::new( + vec![FindSpec::Variable("?v".to_string())], + vec![ + WhereClause::Pattern(Pattern::new( + EdnValue::Symbol("?e".to_string()), + EdnValue::Keyword(":score".to_string()), + EdnValue::Symbol("?v".to_string()), + )), + WhereClause::Expr { + expr: Expr::BinOp( + BinOp::Gte, + Box::new(Expr::Var("?v".to_string())), + Box::new(Expr::Slot("threshold".to_string())), + ), + binding: None, + }, + ], + ) + } + + #[test] + fn test_validate_rejects_attribute_slot() { + let q = make_query_attr_slot(); + let result = validate_no_attribute_slots(&q); + assert!(result.is_err(), "expected error for attribute slot"); + assert!( + result + .unwrap_err() + .to_string() + .contains("attribute position") + ); + } + + #[test] + fn test_validate_accepts_entity_slot() { + let q = make_query_entity_slot(); + assert!(validate_no_attribute_slots(&q).is_ok()); + } + + #[test] + fn test_validate_accepts_value_slot() { + let q = make_query_value_slot(); + assert!(validate_no_attribute_slots(&q).is_ok()); + } + + #[test] + fn test_collect_entity_slot_name() { + let q = make_query_entity_slot(); + let names = collect_slot_names(&q); + assert_eq!(names, vec!["entity"]); + } + + #[test] + fn test_collect_value_slot_name() { + let q = make_query_value_slot(); + let names = collect_slot_names(&q); + assert_eq!(names, vec!["name"]); + } + + #[test] + fn test_collect_as_of_slot_name() { + let q = make_query_as_of_slot(); + let names = collect_slot_names(&q); + assert!(names.contains(&"tx".to_string())); + } + + #[test] + fn test_collect_valid_at_slot_name() { + let q = make_query_valid_at_slot(); + let names = collect_slot_names(&q); + assert!(names.contains(&"date".to_string())); + } + + #[test] + fn test_collect_expr_slot_name() { + let q = make_query_expr_slot(); + let names = collect_slot_names(&q); + assert!(names.contains(&"threshold".to_string())); + } + + #[test] + fn test_collect_deduplicates() { + let q = DatalogQuery::new( + vec![ + FindSpec::Variable("?name".to_string()), + FindSpec::Variable("?age".to_string()), + ], + vec![ + WhereClause::Pattern(Pattern::new( + EdnValue::BindSlot("entity".to_string()), + EdnValue::Keyword(":person/name".to_string()), + EdnValue::Symbol("?name".to_string()), + )), + WhereClause::Pattern(Pattern::new( + EdnValue::BindSlot("entity".to_string()), + EdnValue::Keyword(":person/age".to_string()), + EdnValue::Symbol("?age".to_string()), + )), + ], + ); + let names = collect_slot_names(&q); + assert_eq!(names.len(), 1); + assert_eq!(names[0], "entity"); + } + + #[test] + fn test_substitute_entity_slot() { + let q = make_query_entity_slot(); + let uuid = Uuid::new_v4(); + let bv = BindValue::Entity(uuid); + let bindings: HashMap<&str, &BindValue> = [("entity", &bv)].into(); + let filled = substitute(&q, &bindings).unwrap(); + match &filled.where_clauses[0] { + WhereClause::Pattern(p) => { + assert_eq!(p.entity, EdnValue::Uuid(uuid)); + } + _ => panic!("expected Pattern"), + } + } + + #[test] + fn test_substitute_value_slot() { + let q = make_query_value_slot(); + let bv = BindValue::Val(Value::String("Alice".to_string())); + let bindings: HashMap<&str, &BindValue> = [("name", &bv)].into(); + let filled = substitute(&q, &bindings).unwrap(); + match &filled.where_clauses[0] { + WhereClause::Pattern(p) => { + assert_eq!(p.value, EdnValue::String("Alice".to_string())); + } + _ => panic!("expected Pattern"), + } + } + + #[test] + fn test_substitute_as_of_counter() { + let q = make_query_as_of_slot(); + let bv = BindValue::TxCount(42); + let bindings: HashMap<&str, &BindValue> = [("tx", &bv)].into(); + let filled = substitute(&q, &bindings).unwrap(); + assert!(matches!(filled.as_of, Some(AsOf::Counter(42)))); + } + + #[test] + fn test_substitute_as_of_timestamp() { + let q = make_query_as_of_slot(); + let bv = BindValue::Timestamp(1_685_577_600_000); + let bindings: HashMap<&str, &BindValue> = [("tx", &bv)].into(); + let filled = substitute(&q, &bindings).unwrap(); + assert!(matches!( + filled.as_of, + Some(AsOf::Timestamp(1_685_577_600_000)) + )); + } + + #[test] + fn test_substitute_valid_at_timestamp() { + let q = make_query_valid_at_slot(); + let bv = BindValue::Timestamp(1_685_577_600_000); + let bindings: HashMap<&str, &BindValue> = [("date", &bv)].into(); + let filled = substitute(&q, &bindings).unwrap(); + assert!(matches!( + filled.valid_at, + Some(ValidAt::Timestamp(1_685_577_600_000)) + )); + } + + #[test] + fn test_substitute_valid_at_any() { + let q = make_query_valid_at_slot(); + let bv = BindValue::AnyValidTime; + let bindings: HashMap<&str, &BindValue> = [("date", &bv)].into(); + let filled = substitute(&q, &bindings).unwrap(); + assert!(matches!(filled.valid_at, Some(ValidAt::AnyValidTime))); + } + + #[test] + fn test_substitute_expr_slot() { + let q = make_query_expr_slot(); + let bv = BindValue::Val(Value::Integer(50)); + let bindings: HashMap<&str, &BindValue> = [("threshold", &bv)].into(); + let filled = substitute(&q, &bindings).unwrap(); + match &filled.where_clauses[1] { + WhereClause::Expr { + expr: Expr::BinOp(_, _, rhs), + .. + } => { + assert!(matches!(rhs.as_ref(), Expr::Lit(Value::Integer(50)))); + } + _ => panic!("expected BinOp Expr clause"), + } + } + + #[test] + fn test_substitute_type_mismatch_entity_gets_val() { + let q = make_query_entity_slot(); + let bv = BindValue::Val(Value::String("Alice".to_string())); + let bindings: HashMap<&str, &BindValue> = [("entity", &bv)].into(); + let result = substitute(&q, &bindings); + assert!(result.is_err(), "expected type mismatch error"); + assert!(result.unwrap_err().to_string().contains("entity position")); + } + + #[test] + fn test_substitute_type_mismatch_as_of_gets_val() { + let q = make_query_as_of_slot(); + let bv = BindValue::Val(Value::Integer(42)); + let bindings: HashMap<&str, &BindValue> = [("tx", &bv)].into(); + let result = substitute(&q, &bindings); + assert!(result.is_err(), "expected type mismatch error"); + assert!(result.unwrap_err().to_string().contains(":as-of position")); + } + + #[test] + fn test_substitute_type_mismatch_valid_at_gets_tx_count() { + let q = make_query_valid_at_slot(); + let bv = BindValue::TxCount(5); + let bindings: HashMap<&str, &BindValue> = [("date", &bv)].into(); + let result = substitute(&q, &bindings); + assert!(result.is_err(), "expected type mismatch error"); + assert!( + result + .unwrap_err() + .to_string() + .contains(":valid-at position") + ); + } +} diff --git a/src/query/datalog/types.rs b/src/query/datalog/types.rs index 5918ba2ae0..f4a4736f1f 100644 --- a/src/query/datalog/types.rs +++ b/src/query/datalog/types.rs @@ -27,6 +27,10 @@ pub enum EdnValue { Map(Vec<(EdnValue, EdnValue)>), /// Null/nil Nil, + /// A named bind slot: `$identifier`. + /// Only valid in a `PreparedQuery` template AST — must be replaced by + /// `substitute()` before the query reaches the executor. + BindSlot(String), } impl EdnValue { @@ -219,6 +223,8 @@ pub enum Expr { Var(String), /// Literal value: `100`, `"foo"`, `true` Lit(Value), + /// Named bind slot: `$name` — substituted to `Expr::Lit` before execution. + Slot(String), BinOp(BinOp, Box, Box), UnaryOp(UnaryOp, Box), } @@ -657,6 +663,8 @@ pub enum AsOf { Counter(u64), /// Select facts whose `tx_id` (wall-clock millis since epoch) is ≤ t. Timestamp(i64), + /// Named bind slot: `$name` — resolved to `Counter` or `Timestamp` at execute time. + Slot(String), } /// A point-in-time selector for valid-time travel queries. @@ -669,6 +677,8 @@ pub enum ValidAt { Timestamp(i64), /// Return all facts regardless of valid time (no valid-time filter). AnyValidTime, + /// Named bind slot: `$name` — resolved to `Timestamp` or `AnyValidTime` at execute time. + Slot(String), } /// A Datalog command (top-level form) @@ -1374,4 +1384,31 @@ mod tests { assert_eq!(PseudoAttr::TxId.as_keyword(), ":db/tx-id"); assert_eq!(PseudoAttr::ValidAt.as_keyword(), ":db/valid-at"); } + + #[test] + fn test_bind_slot_edn_variant_exists() { + let v = EdnValue::BindSlot("entity".to_string()); + assert!(matches!(v, EdnValue::BindSlot(_))); + // BindSlot is not a logic variable — it is not a ?-prefixed symbol + assert!(!v.is_variable()); + assert!(v.as_variable().is_none()); + } + + #[test] + fn test_as_of_slot_variant_exists() { + let a = AsOf::Slot("tx".to_string()); + assert!(matches!(a, AsOf::Slot(_))); + } + + #[test] + fn test_valid_at_slot_variant_exists() { + let v = ValidAt::Slot("date".to_string()); + assert!(matches!(v, ValidAt::Slot(_))); + } + + #[test] + fn test_expr_slot_variant_exists() { + let e = Expr::Slot("threshold".to_string()); + assert!(matches!(e, Expr::Slot(_))); + } } diff --git a/tests/prepared_statements_test.rs b/tests/prepared_statements_test.rs new file mode 100644 index 0000000000..df2724d0e0 --- /dev/null +++ b/tests/prepared_statements_test.rs @@ -0,0 +1,388 @@ +use minigraf::db::Minigraf; +use minigraf::query::datalog::executor::QueryResult; +use minigraf::{BindValue, Value}; +use uuid::Uuid; + +// ─── Happy-path tests ───────────────────────────────────────────────────────── + +#[test] +fn prepare_and_execute_entity_slot() { + let db = Minigraf::in_memory().unwrap(); + let alice = Uuid::new_v4(); + let bob = Uuid::new_v4(); + + db.execute(&format!( + r#"(transact [[#uuid "{alice}" :person/name "Alice"] + [#uuid "{bob}" :person/name "Bob"]])"# + )) + .unwrap(); + + let prepared = db + .prepare("(query [:find ?name :where [$entity :person/name ?name]])") + .unwrap(); + + let r1 = prepared + .execute(&[("entity", BindValue::Entity(alice))]) + .unwrap(); + match r1 { + QueryResult::QueryResults { results, .. } => { + assert_eq!(results.len(), 1); + assert_eq!(results[0][0], Value::String("Alice".to_string())); + } + _ => panic!("expected QueryResults"), + } + + let r2 = prepared + .execute(&[("entity", BindValue::Entity(bob))]) + .unwrap(); + match r2 { + QueryResult::QueryResults { results, .. } => { + assert_eq!(results.len(), 1); + assert_eq!(results[0][0], Value::String("Bob".to_string())); + } + _ => panic!("expected QueryResults"), + } +} + +#[test] +fn prepare_and_execute_value_slot() { + let db = Minigraf::in_memory().unwrap(); + db.execute(r#"(transact [[:alice :person/name "Alice"] [:bob :person/name "Bob"]])"#) + .unwrap(); + + let prepared = db + .prepare("(query [:find ?e :where [?e :person/name $name]])") + .unwrap(); + + let alice_id = Uuid::new_v5(&Uuid::NAMESPACE_OID, b":alice"); + let bob_id = Uuid::new_v5(&Uuid::NAMESPACE_OID, b":bob"); + + let r = prepared + .execute(&[("name", BindValue::Val(Value::String("Alice".to_string())))]) + .unwrap(); + match r { + QueryResult::QueryResults { results, .. } => { + assert_eq!(results.len(), 1); + assert_eq!(results[0][0], Value::Ref(alice_id)); + } + _ => panic!("expected QueryResults"), + } + + let r2 = prepared + .execute(&[("name", BindValue::Val(Value::String("Bob".to_string())))]) + .unwrap(); + match r2 { + QueryResult::QueryResults { results, .. } => { + assert_eq!(results.len(), 1); + assert_eq!(results[0][0], Value::Ref(bob_id)); + } + _ => panic!("expected QueryResults"), + } +} + +#[test] +fn prepare_and_execute_as_of_counter() { + let db = Minigraf::in_memory().unwrap(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#) + .unwrap(); + db.execute(r#"(transact [[:alice :person/name "Alice-v2"]])"#) + .unwrap(); + + let prepared = db + .prepare("(query [:find ?name :as-of $tx :where [?e :person/name ?name]])") + .unwrap(); + + // At tx 1 only "Alice" exists + let r = prepared.execute(&[("tx", BindValue::TxCount(1))]).unwrap(); + match r { + QueryResult::QueryResults { results, .. } => { + assert_eq!(results.len(), 1); + assert_eq!(results[0][0], Value::String("Alice".to_string())); + } + _ => panic!("expected QueryResults"), + } +} + +#[test] +fn prepare_and_execute_as_of_timestamp() { + let db = Minigraf::in_memory().unwrap(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#) + .unwrap(); + + // Use a very large timestamp — all facts should be visible + let prepared = db + .prepare("(query [:find ?name :as-of $ts :where [?e :person/name ?name]])") + .unwrap(); + + let r = prepared + .execute(&[("ts", BindValue::Timestamp(i64::MAX))]) + .unwrap(); + match r { + QueryResult::QueryResults { results, .. } => { + assert!(!results.is_empty()); + } + _ => panic!("expected QueryResults"), + } +} + +#[test] +fn prepare_and_execute_valid_at() { + let db = Minigraf::in_memory().unwrap(); + // t1 = 2001-09-09T01:46:40Z, t2 = 2033-05-18T03:33:20Z, t3 (ISO) = 2065-01-24T05:20:00Z + let t1: i64 = 1_000_000_000_000; + let t2: i64 = 2_000_000_000_000; + + db.execute( + "(transact {:valid-from \"2001-09-09T01:46:40Z\" :valid-to \"2065-01-24T05:20:00Z\"} \ + [[:alice :employment/status :active]])", + ) + .unwrap(); + + let prepared = db + .prepare("(query [:find ?s :valid-at $date :where [?e :employment/status ?s]])") + .unwrap(); + + // Inside the valid window + let r = prepared + .execute(&[("date", BindValue::Timestamp(t2))]) + .unwrap(); + match r { + QueryResult::QueryResults { results, .. } => { + assert_eq!(results.len(), 1); + } + _ => panic!("expected QueryResults"), + } + + // Before the valid window + let r2 = prepared + .execute(&[("date", BindValue::Timestamp(t1 - 1))]) + .unwrap(); + match r2 { + QueryResult::QueryResults { results, .. } => { + assert_eq!(results.len(), 0); + } + _ => panic!("expected QueryResults"), + } +} + +#[test] +fn prepare_and_execute_valid_at_any() { + let db = Minigraf::in_memory().unwrap(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#) + .unwrap(); + + // The slot $va is resolved to AnyValidTime at execute() time, bypassing valid-time filtering. + let prepared = db + .prepare("(query [:find ?name :valid-at $va :where [?e :person/name ?name]])") + .unwrap(); + + let r = prepared + .execute(&[("va", BindValue::AnyValidTime)]) + .unwrap(); + match r { + QueryResult::QueryResults { results, .. } => { + assert_eq!(results.len(), 1); + assert_eq!(results[0][0], Value::String("Alice".to_string())); + } + _ => panic!("expected QueryResults"), + } +} + +#[test] +fn prepare_and_execute_expr_slot() { + let db = Minigraf::in_memory().unwrap(); + db.execute(r#"(transact [[:a :score 10] [:b :score 50] [:c :score 90]])"#) + .unwrap(); + + let prepared = db + .prepare("(query [:any-valid-time :find ?e :where [?e :score ?v] [(>= ?v $threshold)]])") + .unwrap(); + + let r = prepared + .execute(&[("threshold", BindValue::Val(Value::Integer(50)))]) + .unwrap(); + match r { + QueryResult::QueryResults { results, .. } => { + assert_eq!(results.len(), 2); // :b (50) and :c (90) + } + _ => panic!("expected QueryResults"), + } +} + +#[test] +fn prepare_and_execute_combined() { + let db = Minigraf::in_memory().unwrap(); + let alice = Uuid::new_v4(); + + db.execute(&format!( + r#"(transact [[#uuid "{alice}" :employment/status :active]])"# + )) + .unwrap(); + + let prepared = db + .prepare( + "(query [:find ?s \ + :as-of $tx \ + :valid-at $date \ + :where [$entity :employment/status ?s] \ + [(= ?s $expected-status)]])", + ) + .unwrap(); + + let r = prepared + .execute(&[ + ("tx", BindValue::TxCount(100)), + ("date", BindValue::AnyValidTime), + ("entity", BindValue::Entity(alice)), + ( + "expected-status", + BindValue::Val(Value::Keyword(":active".to_string())), + ), + ]) + .unwrap(); + match r { + QueryResult::QueryResults { results, .. } => { + assert_eq!(results.len(), 1); + } + _ => panic!("expected QueryResults"), + } +} + +#[test] +fn plan_reused_across_executions() { + let db = Minigraf::in_memory().unwrap(); + let alice = Uuid::new_v4(); + let bob = Uuid::new_v4(); + let carol = Uuid::new_v4(); + + db.execute(&format!( + r#"(transact [[#uuid "{alice}" :person/name "Alice"] + [#uuid "{bob}" :person/name "Bob"] + [#uuid "{carol}" :person/name "Carol"]])"# + )) + .unwrap(); + + let prepared = db + .prepare("(query [:find ?name :where [$entity :person/name ?name]])") + .unwrap(); + + for (uuid, expected) in [(alice, "Alice"), (bob, "Bob"), (carol, "Carol")] { + let r = prepared + .execute(&[("entity", BindValue::Entity(uuid))]) + .unwrap(); + match r { + QueryResult::QueryResults { results, .. } => { + assert_eq!(results.len(), 1); + assert_eq!(results[0][0], Value::String(expected.to_string())); + } + _ => panic!("expected QueryResults"), + } + } +} + +// ─── Error tests ────────────────────────────────────────────────────────────── + +#[test] +fn prepare_rejects_attribute_slot() { + let db = Minigraf::in_memory().unwrap(); + let result = db.prepare("(query [:find ?v :where [?e $attr ?v]])"); + assert!(result.is_err(), "expected error for attribute slot"); + assert!( + result + .unwrap_err() + .to_string() + .contains("attribute position"), + "error should mention attribute position" + ); +} + +#[test] +fn prepare_rejects_transact() { + let db = Minigraf::in_memory().unwrap(); + let result = db.prepare(r#"(transact [[:alice :person/name "Alice"]])"#); + assert!(result.is_err(), "expected error for transact"); + assert!(result.unwrap_err().to_string().contains("transact")); +} + +#[test] +fn prepare_rejects_retract() { + let db = Minigraf::in_memory().unwrap(); + let result = db.prepare(r#"(retract [[:alice :person/name "Alice"]])"#); + assert!(result.is_err(), "expected error for retract"); + assert!(result.unwrap_err().to_string().contains("retract")); +} + +#[test] +fn prepare_rejects_rule() { + let db = Minigraf::in_memory().unwrap(); + let result = db.prepare("(rule [(reachable ?a ?b) [?a :edge ?b]])"); + assert!(result.is_err(), "expected error for rule"); + assert!(result.unwrap_err().to_string().contains("rule")); +} + +#[test] +fn execute_missing_slot() { + let db = Minigraf::in_memory().unwrap(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#) + .unwrap(); + + let prepared = db + .prepare("(query [:find ?name :where [$entity :person/name ?name]])") + .unwrap(); + + // Intentionally omit the "entity" binding + let result = prepared.execute(&[]); + assert!(result.is_err(), "expected error for missing slot"); + assert!( + result.unwrap_err().to_string().contains("entity"), + "error should mention the missing slot name" + ); +} + +#[test] +fn execute_type_mismatch_as_of() { + let db = Minigraf::in_memory().unwrap(); + let prepared = db + .prepare("(query [:find ?v :as-of $tx :where [?e :score ?v]])") + .unwrap(); + + let result = prepared.execute(&[("tx", BindValue::Val(Value::Integer(42)))]); + assert!(result.is_err(), "expected type mismatch error"); + assert!( + result.unwrap_err().to_string().contains(":as-of position"), + "error should mention :as-of position" + ); +} + +#[test] +fn execute_type_mismatch_entity() { + let db = Minigraf::in_memory().unwrap(); + let prepared = db + .prepare("(query [:find ?name :where [$entity :person/name ?name]])") + .unwrap(); + + let result = prepared.execute(&[( + "entity", + BindValue::Val(Value::String("not-a-uuid".to_string())), + )]); + assert!(result.is_err(), "expected type mismatch error"); + assert!( + result.unwrap_err().to_string().contains("entity position"), + "error should mention entity position" + ); +} + +#[test] +fn execute_extra_bindings_ignored() { + let db = Minigraf::in_memory().unwrap(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#) + .unwrap(); + + let prepared = db + .prepare("(query [:find ?name :where [:alice :person/name ?name]])") + .unwrap(); + + // Provide an extra binding that the query doesn't reference + let result = prepared.execute(&[("unused-slot", BindValue::Val(Value::Integer(99)))]); + assert!(result.is_ok(), "extra bindings should be silently ignored"); +}