use std::collections::BTreeMap;
use relate_core::{Error, Result, Value};
use relate_ir::Expr;
use relate_model::EntityKind;
use crate::ctx::ExecCtx;
use crate::eval::eval;
use crate::exec::candidates::ranked_candidates;
use crate::procedure_registry::ProcSignature;
use crate::row::Row;
use super::super::compose::{ComposeSource, Produced};
use super::super::fulltext;
use super::super::vector::{resolve_vector_index, scan_candidates, vector_operand};
use super::contract::CallSpec;
fn entity_kind_mismatch(kind: EntityKind, resolved: EntityKind, family: &str) -> Result<()> {
if resolved != kind {
return Err(Error::execution(format!(
"WrongIndexType: {family} index entity type mismatch"
)));
}
Ok(())
}
struct ScanInputs<'a> {
kind: EntityKind,
args: &'a [Expr],
ctx: ExecCtx<'a>,
index_name: String,
}
fn scan_call_source<'a>(
ctx: ExecCtx<'a>,
kind: EntityKind,
call: CallSpec<'a>,
signature: &'static ProcSignature,
mut scan: impl FnMut(&Row, &ScanInputs<'_>) -> Result<Vec<(Value, f64)>> + 'a,
) -> Result<ComposeSource<'a>> {
let CallSpec {
yield_items,
optional,
where_clause,
..
} = call;
let args = call.check_diverted_positional(signature)?;
let CallSpec { name, source, .. } = call;
let columns: Vec<&'static str> = signature.returns.iter().map(|ret| ret.name).collect();
let defaults = columns.clone();
Ok(ComposeSource::new(
&defaults,
yield_items,
optional,
where_clause,
move |input| {
let index_name = super::contract::string_arg(ctx, input, source, 0, "indexName", name)?;
let inputs = ScanInputs {
kind,
args,
ctx,
index_name,
};
Ok(Produced::Rows(
scan(input, &inputs)?
.into_iter()
.map(|(entity, score)| {
BTreeMap::from([
(columns[0].to_string(), entity),
(columns[1].to_string(), Value::Float(score)),
])
})
.collect(),
))
},
))
}
const RANKING_ALL: (usize, usize) = (0, usize::MAX);
#[derive(Clone, Copy)]
enum OptionKey {
Skip,
Limit,
Analyzer,
}
impl OptionKey {
const ALL: [Self; 3] = [Self::Skip, Self::Limit, Self::Analyzer];
fn parse(key: &str) -> Option<Self> {
Self::ALL.into_iter().find(|option| option.name() == key)
}
fn name(self) -> &'static str {
match self {
Self::Skip => "skip",
Self::Limit => "limit",
Self::Analyzer => "analyzer",
}
}
fn names() -> String {
let names: Vec<&str> = Self::ALL.iter().map(|option| option.name()).collect();
names.join(", ")
}
fn read(
self,
value: &Value,
window: &mut (usize, usize),
analyzer: &mut Option<fulltext::Analyzer>,
procedure: &str,
) -> Result<()> {
let slot = match self {
Self::Skip => &mut window.0,
Self::Limit => &mut window.1,
Self::Analyzer => {
*analyzer = fulltext::Analyzer::from_value(value)?;
return Ok(());
}
};
let invalid = || {
Error::argument_error(format!(
"{procedure} option `{}` expects a non-negative INTEGER",
self.name()
))
};
let Value::Int(count) = value else {
return Err(invalid());
};
*slot = usize::try_from(*count).map_err(|_| invalid())?;
Ok(())
}
}
fn query_options(
value: &Value,
procedure: &str,
) -> Result<((usize, usize), Option<fulltext::Analyzer>)> {
let Value::Map(options) = value else {
return Err(Error::invalid_argument_type(format!(
"{procedure} argument `options` expects MAP"
)));
};
let mut window = RANKING_ALL;
let mut analyzer = None;
for (key, value) in options.iter() {
let Some(option) = OptionKey::parse(key) else {
return Err(Error::argument_error(format!(
"{procedure} does not accept the `{key}` option (valid: {})",
OptionKey::names()
)));
};
option.read(value, &mut window, &mut analyzer, procedure)?;
}
Ok((window, analyzer))
}
pub(crate) fn fulltext_call_source<'a>(
ctx: ExecCtx<'a>,
kind: EntityKind,
call: CallSpec<'a>,
signature: &'static ProcSignature,
) -> Result<ComposeSource<'a>> {
let corpora = fulltext::CorpusMemo::new(ctx.graph);
scan_call_source(ctx, kind, call, signature, move |input, s| {
let query_value = eval(s.ctx.graph, input, &s.args[1], s.ctx.params)?;
let Some(query) = fulltext::operand(&query_value)? else {
return Ok(Vec::new());
};
let (window, query_analyzer) = match s.args.get(2) {
Some(expr) => query_options(
&eval(s.ctx.graph, input, expr, s.ctx.params)?,
signature.name,
)?,
None => (RANKING_ALL, None),
};
let scan = fulltext::resolve_analyzers(s.ctx.graph, &s.index_name, query_analyzer)?;
entity_kind_mismatch(s.kind, scan.detail.entity_kind(), "fulltext")?;
Ok(
ranked_candidates(
s.ctx.graph,
s.kind,
fulltext::search(&corpora, s.ctx.graph, scan, query, window.0, window.1, &[])?,
),
)
})
}
pub(crate) fn vector_call_source<'a>(
ctx: ExecCtx<'a>,
kind: EntityKind,
call: CallSpec<'a>,
signature: &'static ProcSignature,
) -> Result<ComposeSource<'a>> {
scan_call_source(ctx, kind, call, signature, move |input, s| {
let limit = match eval(s.ctx.graph, input, &s.args[1], s.ctx.params)? {
Value::Int(value) if (1..=i32::MAX as i64).contains(&value) => value as usize,
_ => {
return Err(Error::invalid_argument_value(format!(
"{} must be a positive INTEGER",
signature.args[1].name
)))
}
};
let query = eval(s.ctx.graph, input, &s.args[2], s.ctx.params)?;
let Some(query) = vector_operand(&query)? else {
return Ok(Vec::new());
};
let scan = resolve_vector_index(s.ctx.graph, &s.index_name, &query)?;
entity_kind_mismatch(s.kind, scan.detail.entity_kind(), "vector")?;
let candidates = scan_candidates(s.ctx, &scan, &query, limit, s.kind, &[])?;
Ok(candidates)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_options_map_reads_skip_limit_and_the_query_analyzer() {
use crate::test_support::value_map;
let procedure = "db.index.fulltext.queryNodes";
let read = |options: &[(&str, Value)]| query_options(&value_map(options), procedure);
assert_eq!(read(&[]).unwrap(), (RANKING_ALL, None));
assert_eq!(read(&[("limit", Value::Int(2))]).unwrap(), ((0, 2), None));
assert_eq!(
read(&[("skip", Value::Int(1)), ("limit", Value::Int(2))]).unwrap(),
((1, 2), None)
);
assert_eq!(
read(&[("skip", Value::Int(2))]).unwrap(),
((2, usize::MAX), None)
);
assert_eq!(
read(&[("analyzer", Value::String("ENGLISH".into()))]).unwrap(),
(RANKING_ALL, Some(fulltext::Analyzer::English))
);
assert_eq!(
read(&[("analyzer", Value::Null)]).unwrap(),
(RANKING_ALL, None)
);
for option in OptionKey::ALL {
let value = match option {
OptionKey::Skip | OptionKey::Limit => Value::Int(1),
OptionKey::Analyzer => Value::Null,
};
assert!(read(&[(option.name(), value)]).is_ok(), "{}", option.name());
}
for bad in [
Value::Int(1),
value_map(&[("limit", Value::Int(-1))]),
value_map(&[("limit", Value::String("two".into()))]),
value_map(&[("count", Value::Int(1))]),
] {
let error = query_options(&bad, procedure).expect_err("rejected");
assert!(error.to_string().contains("option"), "{bad:?}: {error}");
}
let error = query_options(
&value_map(&[("analyzer", Value::String("not-a-real-analyzer".into()))]),
procedure,
)
.expect_err("rejected");
assert!(error.to_string().contains("analyzer name"), "{error}");
}
}