use std::collections::HashSet;
use std::ops::{Bound, RangeBounds};
use std::sync::Arc;
use rusqlite::Connection;
use rusqlite::types::Value as SqlValue;
use serde::Serialize;
use serde_json::Value;
use super::legacy;
use super::merge;
use super::score::Part;
use super::segments;
use super::settings::Settings;
use super::table::key_id;
use crate::limits::{FILTER_CONDITIONS, FILTER_ROWS, FILTER_TEXT, FILTER_VALUES};
use crate::sqlite::sql_error;
use crate::typos::meant;
use crate::{Error, Result};
const FIND_KEYS: &str = "select id from _tinystore_search_keys
where index_id = ?1 and part = ?2 and term in (select value from json_each(?3))";
const FIND_IDS: &str = "select doc from _tinystore_search_docs
where index_id = ?1 and id in (select value from json_each(?2))";
pub(crate) const MOST_VALUE: usize = FILTER_TEXT.bound as usize;
pub(crate) const MOST_CONDITIONS: usize = FILTER_CONDITIONS.bound as usize;
pub(crate) const MOST_VALUES: usize = FILTER_VALUES.bound as usize;
const MOST_ROWS: usize = FILTER_ROWS.bound as usize;
const DOCUMENTS_HAVE_NO_TABLES: &str = "a where by a statement is a table index's: an index of documents has no tables";
const NONE: &str = "n:";
const LEVELS: u32 = 8;
const STEP: u32 = 8;
#[derive(Clone, Debug)]
pub struct Condition(Node);
#[derive(Clone, Debug)]
enum Node {
Values {
path: String,
values: std::result::Result<Value, String>,
list: bool,
},
Rows {
path: String,
rows: Rows,
},
Missing {
path: String,
},
Range {
path: String,
low: Bound<Value>,
high: Bound<Value>,
},
Or(Vec<Condition>),
And(Vec<Condition>),
}
pub fn eq<T: Serialize + ?Sized>(path: &str, value: &T) -> Condition {
let values = serde_json::to_value(value).map_err(|error| error.to_string());
Condition(Node::Values { path: path.to_owned(), values, list: false })
}
pub fn is_in(path: &str, values: impl Values) -> Condition {
let path = path.to_owned();
Condition(match values.listing().0 {
Listed::Values(values) => Node::Values { path, values, list: true },
Listed::Rows(rows) => Node::Rows { path, rows },
})
}
pub trait Values {
#[doc(hidden)]
fn listing(self) -> Listing;
}
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct Listing(Listed);
#[derive(Clone, Debug)]
enum Listed {
Values(std::result::Result<Value, String>),
#[cfg_attr(not(feature = "sql"), expect(dead_code, reason = "only a statement of a database makes one"))]
Rows(Rows),
}
impl<T: Serialize> Values for &[T] {
fn listing(self) -> Listing {
Listing(Listed::Values(serde_json::to_value(self).map_err(|error| error.to_string())))
}
}
impl<T: Serialize, const N: usize> Values for &[T; N] {
fn listing(self) -> Listing {
self.as_slice().listing()
}
}
impl<T: Serialize> Values for &Vec<T> {
fn listing(self) -> Listing {
self.as_slice().listing()
}
}
pub(crate) type ReadColumn = Arc<dyn Fn(&Connection, usize) -> Result<Vec<SqlValue>> + Send + Sync>;
#[derive(Clone)]
pub(crate) struct Rows {
described: String,
read: ReadColumn,
}
impl std::fmt::Debug for Rows {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.described)
}
}
impl Values for Listing {
fn listing(self) -> Listing {
self
}
}
impl Listing {
#[cfg(feature = "sql")]
pub(crate) fn rows(described: String, read: ReadColumn) -> Listing {
Listing(Listed::Rows(Rows { described, read }))
}
}
pub fn range<T: Serialize>(path: &str, bounds: impl RangeBounds<T>) -> Condition {
let value = |bound: Bound<&T>| match bound {
Bound::Included(value) => Bound::Included(serde_json::to_value(value).unwrap_or(Value::Null)),
Bound::Excluded(value) => Bound::Excluded(serde_json::to_value(value).unwrap_or(Value::Null)),
Bound::Unbounded => Bound::Unbounded,
};
Condition(Node::Range { path: path.to_owned(), low: value(bounds.start_bound()), high: value(bounds.end_bound()) })
}
pub fn missing(path: &str) -> Condition {
Condition(Node::Missing { path: path.to_owned() })
}
pub fn or(conditions: impl IntoIterator<Item = Condition>) -> Condition {
Condition(Node::Or(conditions.into_iter().collect()))
}
pub fn and(conditions: impl IntoIterator<Item = Condition>) -> Condition {
Condition(Node::And(conditions.into_iter().collect()))
}
#[cfg(feature = "wire")]
pub(crate) fn from_json(text: &str, statements: &[Listing]) -> Result<Vec<Condition>> {
let value: Value = serde_json::from_str(text).map_err(|error| Error::invalid(format!("a where: {error}")))?;
let condition_of = |value: &Value| condition_of(value, statements);
match value {
Value::Array(items) => items.iter().map(condition_of).collect(),
one => Ok(vec![condition_of(&one)?]),
}
}
#[cfg(feature = "wire")]
fn condition_of(value: &Value, statements: &[Listing]) -> Result<Condition> {
let refused = || Error::invalid(format!("a where's condition {value}"));
let Some((kind, given)) = value.as_object().filter(|object| object.len() == 1).and_then(|o| o.iter().next()) else {
return Err(refused());
};
let path_and = |given: &Value| -> Result<(String, Value)> {
match given.as_array().map(Vec::as_slice) {
Some([Value::String(path), operand]) => Ok((path.clone(), operand.clone())),
_ => Err(refused()),
}
};
match kind.as_str() {
"eq" => path_and(given).map(|(path, operand)| eq(&path, &operand)),
"in" => match path_and(given)? {
(path, Value::Array(values)) => Ok(is_in(&path, &values)),
(path, Value::Object(named)) if named.len() == 1 => {
let at = named.get("statement").and_then(Value::as_u64).ok_or_else(refused)?;
let statement = usize::try_from(at).ok().and_then(|at| statements.get(at)).ok_or_else(|| {
Error::invalid(format!("a where's statement {at}, of {} the query holds", statements.len()))
})?;
Ok(is_in(&path, statement.clone()))
}
_ => Err(refused()),
},
"missing" => given.as_str().map(missing).ok_or_else(refused),
"range" => {
let (path, bounds) = path_and(given)?;
let bound = |strict: &str, loose: &str| match (bounds.get(strict), bounds.get(loose)) {
(Some(value), _) => Bound::Excluded(value.clone()),
(None, Some(value)) => Bound::Included(value.clone()),
(None, None) => Bound::Unbounded,
};
Ok(Condition(Node::Range { path, low: bound("gt", "gte"), high: bound("lt", "lte") }))
}
"or" | "and" => {
let parts = given.as_array().ok_or_else(refused)?.iter().map(|part| condition_of(part, statements));
let parts: Vec<Condition> = parts.collect::<Result<_>>()?;
Ok(if kind == "or" { or(parts) } else { and(parts) })
}
_ => Err(refused()),
}
}
#[derive(Clone, Debug)]
pub(crate) enum Asked {
Terms {
path: String,
terms: Vec<String>,
},
Rows {
path: String,
rows: Rows,
},
Or(Vec<Asked>),
And(Vec<Asked>),
}
#[derive(Default)]
struct Counted {
conditions: usize,
values: usize,
}
pub(crate) fn asked(conditions: &[Condition]) -> Result<Asked> {
let mut counted = Counted::default();
let asked = conditions.iter().map(|condition| condition.asked(&mut counted)).collect::<Result<Vec<_>>>()?;
if counted.conditions > MOST_CONDITIONS {
let refused = format!("a filter of {} conditions, past {MOST_CONDITIONS}", counted.conditions);
return Err(FILTER_CONDITIONS.refuse(counted.conditions as u64, refused));
}
if counted.values > MOST_VALUES {
let refused = format!("a filter of {} values, past {MOST_VALUES}", counted.values);
return Err(FILTER_VALUES.refuse(counted.values as u64, refused));
}
Ok(Asked::And(asked))
}
impl Condition {
fn asked(&self, counted: &mut Counted) -> Result<Asked> {
match &self.0 {
Node::Values { path, values, list } => {
counted.conditions += 1;
let values = values.as_ref().map_err(|why| Error::invalid(format!("filter {path}: {why}")))?;
let terms = match (values, list) {
(Value::Array(_), false) => {
return Err(Error::invalid(format!("filter {path}: eq takes one value, and is_in a list")));
}
(Value::Array(items), true) => items.iter().map(|item| term(item, path)).collect::<Result<_>>()?,
(value, _) => vec![term(value, path)?],
};
counted.values += terms.len();
Ok(Asked::Terms { path: path.clone(), terms })
}
Node::Range { path, low, high } => {
counted.conditions += 1;
Ok(Asked::Terms { path: path.clone(), terms: range_terms(path, low, high)? })
}
Node::Missing { path } => {
counted.conditions += 1;
Ok(Asked::Terms { path: path.clone(), terms: vec![NONE.to_owned()] })
}
Node::Rows { path, rows } => {
counted.conditions += 1;
Ok(Asked::Rows { path: path.clone(), rows: rows.clone() })
}
Node::Or(conditions) => Ok(Asked::Or(conditions.iter().map(|c| c.asked(counted)).collect::<Result<_>>()?)),
Node::And(conditions) => {
Ok(Asked::And(conditions.iter().map(|c| c.asked(counted)).collect::<Result<_>>()?))
}
}
}
}
pub(crate) fn held(document: &Value, path: &str) -> Result<Vec<String>> {
let values: Vec<&Value> = match at(document, path) {
Value::Array(items) => items.iter().filter(|item| !item.is_null()).collect(),
Value::Null => Vec::new(),
value => vec![value],
};
let mut terms = Vec::with_capacity(values.len() * (1 + LEVELS as usize));
for value in values {
terms.push(term(value, path)?);
if let Some(number) = value.as_f64() {
terms.extend((0..LEVELS).map(|level| precise(level, sortable(number) >> (STEP * level))));
}
}
if terms.is_empty() {
terms.push(NONE.to_owned());
}
terms.sort_unstable();
terms.dedup();
Ok(terms)
}
fn term(value: &Value, path: &str) -> Result<String> {
let refused =
|what: &str| Error::invalid(format!("filter {path} holds {what}: a filter keeps text, numbers and booleans"));
match value {
Value::Null => Err(Error::invalid(format!(
"filter {path}: a value of None or null; missing({path:?}) asks for a document with none"
))),
Value::String(text) if text.len() > MOST_VALUE => {
let refused = format!("filter {path} holds {} bytes of text, past {MOST_VALUE}", text.len());
Err(FILTER_TEXT.refuse(text.len() as u64, refused))
}
Value::String(text) => Ok(format!("t:{text}")),
Value::Bool(on) => Ok(format!("b:{on}")),
Value::Number(number) => match (number.as_i64(), number.as_u64(), number.as_f64()) {
(Some(whole), _, _) => Ok(format!("i:{whole}")),
(None, Some(whole), _) => Ok(format!("i:{whole}")),
(None, None, Some(float)) if float.fract() == 0.0 && float.abs() < 9.2e18 => {
Ok(format!("i:{}", float as i64))
}
(None, None, Some(float)) => Ok(precise(0, sortable(float))),
_ => Err(refused(&format!("{number}"))),
},
Value::Array(_) => Err(refused("a list in a list")),
Value::Object(_) => Err(refused("an object")),
}
}
fn sortable(number: f64) -> u64 {
let bits = if number == 0.0 { 0.0f64.to_bits() } else { number.to_bits() };
if bits >> 63 == 1 { !bits } else { bits | 1 << 63 }
}
fn precise(level: u32, prefix: u64) -> String {
format!("r{level}:{prefix:x}")
}
fn range_terms(path: &str, low: &Bound<Value>, high: &Bound<Value>) -> Result<Vec<String>> {
let place = |value: &Value| match value.as_f64() {
Some(number) if number.is_finite() => Ok(sortable(number)),
_ => Err(Error::invalid(format!("filter {path}: a range is of numbers, not {value}"))),
};
let low = match low {
Bound::Included(value) => Some(place(value)?),
Bound::Excluded(value) => place(value)?.checked_add(1),
Bound::Unbounded => Some(0),
};
let high = match high {
Bound::Included(value) => Some(place(value)?),
Bound::Excluded(value) => place(value)?.checked_sub(1),
Bound::Unbounded => Some(u64::MAX),
};
let (Some(low), Some(high)) = (low, high) else { return Ok(Vec::new()) };
Ok(blocks(low, high).into_iter().map(|(level, prefix)| precise(level, prefix)).collect())
}
fn blocks(low: u64, high: u64) -> Vec<(u32, u64)> {
let (mut low, mut high) = (u128::from(low), u128::from(high) + 1);
let mut blocks = Vec::new();
let mut take = |level: u32, from: u128, to: u128| {
let shift = STEP * level;
blocks.extend(((from >> shift)..(to >> shift)).map(|prefix| (level, prefix as u64)));
};
for level in 0..LEVELS {
let coarser = 1u128 << (STEP * (level + 1));
let (up, down) = (low.div_ceil(coarser) * coarser, high / coarser * coarser);
if low >= high {
break;
}
if level == LEVELS - 1 || up >= down {
take(level, low, high);
break;
}
take(level, low, up);
take(level, down, high);
(low, high) = (up, down);
}
blocks
}
fn at<'v>(document: &'v Value, path: &str) -> &'v Value {
let mut at = document;
for name in path.split('.') {
match at.get(name) {
Some(value) => at = value,
None => return &Value::Null,
}
}
at
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Docs {
All,
Only(Vec<u32>),
}
pub(crate) struct Reader<'a> {
pub(crate) connection: &'a Connection,
pub(crate) index: i64,
pub(crate) settings: &'a Settings,
pub(crate) gone: &'a HashSet<u32>,
}
impl Reader<'_> {
pub(crate) fn passing(&self, asked: &Asked) -> Result<Docs> {
match asked {
Asked::Terms { path, terms } => self.holding(path, terms).map(Docs::Only),
Asked::Rows { path, rows } => self.among(path, rows).map(Docs::Only),
Asked::Or(parts) => {
let mut passing = Docs::Only(Vec::new());
for part in parts {
passing = match (passing, self.passing(part)?) {
(Docs::All, _) | (_, Docs::All) => return Ok(Docs::All),
(Docs::Only(a), Docs::Only(b)) => Docs::Only(union(&a, &b)),
};
}
Ok(passing)
}
Asked::And(parts) => {
let mut passing = Docs::All;
for part in parts {
passing = match (passing, self.passing(part)?) {
(Docs::All, other) | (other, Docs::All) => other,
(Docs::Only(a), Docs::Only(b)) => Docs::Only(intersection(&a, &b)),
};
if passing == Docs::Only(Vec::new()) {
break;
}
}
Ok(passing)
}
}
}
fn holding(&self, path: &str, terms: &[String]) -> Result<Vec<u32>> {
let Some(filter) = self.settings.filter(path) else {
let paths = self.settings.filters.iter().map(|filter| filter.path.as_str());
let meant = meant(path, paths).map(|meant| format!("; did you mean {meant}?")).unwrap_or_default();
return Err(Error::invalid(format!("a filter on {path}, which the index was not opened with{meant}")));
};
let segments = segments::of_index(self.connection, self.index)?;
let mut holding = Vec::new();
for key in self.keys(Part::filter(filter.number), terms)? {
holding.extend(self.docs_of(key, &segments)?);
}
Ok(self.sorted(holding))
}
fn among(&self, path: &str, rows: &Rows) -> Result<Vec<u32>> {
let Some(table) = &self.settings.table else { return Err(Error::invalid(DOCUMENTS_HAVE_NO_TABLES)) };
let within = |error: Error| error.within(format!("filter {path}: {}", rows.described));
let values = (rows.read)(self.connection, MOST_ROWS).map_err(within)?;
if values.len() > MOST_ROWS {
let refused = format!("filter {path}: a statement of more than {MOST_ROWS} rows");
return Err(FILTER_ROWS.refuse(values.len() as u64, refused));
}
if table.key == [path] {
return self.keyed(&values);
}
let values = values.into_iter().filter_map(|value| value_of(value, path).transpose());
let terms = values.map(|value| term(&value?, path)).collect::<Result<Vec<_>>>()?;
self.holding(path, &terms)
}
fn keyed(&self, keys: &[SqlValue]) -> Result<Vec<u32>> {
let ids: Vec<String> = keys.iter().filter_map(|key| key_id(key).ok()).collect();
let ids = Value::from(ids).to_string();
let failed = |error| sql_error("find the rows of a where's statement", error);
let mut select = self.connection.prepare_cached(FIND_IDS).map_err(failed)?;
let docs = select.query_map((self.index, ids), |row| row.get(0));
Ok(self.sorted(docs.and_then(Iterator::collect).map_err(failed)?))
}
fn sorted(&self, mut docs: Vec<u32>) -> Vec<u32> {
docs.sort_unstable();
docs.dedup();
docs.retain(|doc| !self.gone.contains(doc));
docs
}
fn as_kept<'t>(&self, term: &'t str) -> &'t str {
match term {
"b:true" if self.settings.table.is_some() => "i:1",
"b:false" if self.settings.table.is_some() => "i:0",
term => term,
}
}
fn keys(&self, part: Part, terms: &[String]) -> Result<Vec<i64>> {
let kept: Vec<&str> = terms.iter().map(|term| self.as_kept(term)).collect();
let failed = |error| sql_error("find a filter's values", error);
let mut select = self.connection.prepare_cached(FIND_KEYS).map_err(failed)?;
let keys = select.query_map((self.index, part.0, Value::from(kept).to_string()), |row| row.get(0));
keys.and_then(Iterator::collect).map_err(failed)
}
fn docs_of(&self, key: i64, segments: &[segments::Segment]) -> Result<Vec<u32>> {
let within = |error: Error| error.within(format!("key {key}"));
let mut docs = legacy::documents(self.connection, self.index, key).map_err(within)?;
for segment in segments {
if let Some((_, piece)) = segments::piece(self.connection, segment, key).map_err(within)? {
docs.extend(merge::documents(self.connection, &piece).map_err(within)?);
}
}
if !docs.is_sorted_by(|a, b| a < b) {
return Err(Error::corrupt(format!("key {key}'s documents are out of their order")));
}
Ok(docs)
}
}
fn value_of(value: SqlValue, path: &str) -> Result<Option<Value>> {
match value {
SqlValue::Null => Ok(None),
SqlValue::Integer(number) => Ok(Some(Value::from(number))),
SqlValue::Real(number) => Ok(Some(Value::from(number))),
SqlValue::Text(text) => Ok(Some(Value::String(text))),
SqlValue::Blob(_) => {
Err(Error::invalid(format!("filter {path} holds a blob: a filter keeps text, numbers and booleans")))
}
}
}
fn union(a: &[u32], b: &[u32]) -> Vec<u32> {
let mut joined = Vec::with_capacity(a.len() + b.len());
let (mut i, mut j) = (0, 0);
loop {
let next = match (a.get(i), b.get(j)) {
(Some(x), Some(y)) => *x.min(y),
(Some(x), None) => *x,
(None, Some(y)) => *y,
(None, None) => return joined,
};
joined.push(next);
i += usize::from(a.get(i) == Some(&next));
j += usize::from(b.get(j) == Some(&next));
}
}
fn intersection(a: &[u32], b: &[u32]) -> Vec<u32> {
let mut both = Vec::with_capacity(a.len().min(b.len()));
let (mut i, mut j) = (0, 0);
while let (Some(x), Some(y)) = (a.get(i), b.get(j)) {
match x.cmp(y) {
std::cmp::Ordering::Less => i += 1,
std::cmp::Ordering::Greater => j += 1,
std::cmp::Ordering::Equal => {
both.push(*x);
(i, j) = (i + 1, j + 1);
}
}
}
both
}
#[cfg(test)]
#[path = "filter_tests.rs"]
mod tests;