use std::sync::{Arc, Weak};
use std::time::Duration;
use rusqlite::Connection;
use rusqlite::types::Value as SqlValue;
use serde::de::DeserializeOwned;
use super::engine::{FILE, InFiles, Search};
use super::index::{Found, Hit, Index, Rebuild, SearchCall};
use super::open::{OpenIndex, Status};
use super::read::{Answer, Query, Ranked};
use super::rebuild::read_current;
use super::settings::{Settings, Table, Wanted};
use super::table;
use crate::engine::{Host, SharedFile};
use crate::sqlite::{Settle, sql_error};
use crate::sync::lock;
use crate::transaction::sealed::Sealed;
use crate::{Error, Memory, Result, Transaction, TxHandle};
const PENDING: Duration = Duration::from_secs(1);
const GONE_ROWS: usize = 1024;
const HAS_TABLE: &str = "select exists (select 1 from sqlite_schema where type = 'table' and name = ?1)";
const READ_COLUMNS: &str = "select name, pk from pragma_table_info(?1)";
const UNIQUE_INDEXES: &str = "select list.name, info.name from pragma_index_list(?1) as list
join pragma_index_info(list.name) as info where list.\"unique\" and not list.partial";
impl Search {
pub(crate) fn in_file(shared: &SharedFile) -> Result<Arc<Search>> {
shared.engine(|store| {
let owner = shared.owner().to_owned();
let search = Search::start(store, Arc::clone(shared.file()), Some(owner.clone()), None)?;
shared.file().settle_with(Arc::downgrade(&search) as Weak<dyn Settle>);
if let Err(error) = search.drop_orphans() {
tracing::warn!(target: "tinystore", "search in {owner}: indexes of tables gone left: {error}");
}
InFiles::of(store)?.keep(&search);
let weak = Arc::downgrade(&search);
store.every(&format!("search in {owner}: pending keys"), PENDING, move || {
weak.upgrade().map_or(Ok(()), |search| search.settle_beside())
})?;
Ok(search)
})
}
fn settle_beside(&self) -> Result<()> {
if !self.file.is_copy() && self.file.read(table::any_pending)? {
self.file.transaction(|_| Ok::<(), Error>(()))?;
}
Ok(())
}
fn drop_orphans(&self) -> Result<()> {
let names: Vec<String> = self.list()?.into_iter().map(|listed| listed.name).collect();
let gone = self.file.read(|connection| {
let mut gone = Vec::new();
for name in names {
let Some(current) = read_current(connection, &name)? else { continue };
let Some(table) = ¤t.serving.settings.table else { continue };
if !has_table(connection, &table.name)? {
gone.push((name, table.name.clone()));
}
}
Ok::<_, Error>(gone)
})?;
for (name, table) in gone {
if self.drop_index(&name)? {
tracing::info!(target: "tinystore", "search in {}: index {name} dropped: table {table} is gone", self.place());
}
}
Ok(())
}
pub(crate) fn place(&self) -> &str {
self.lent_by.as_deref().unwrap_or(FILE)
}
fn note_gone_rows(&self, name: &str, keys: Vec<SqlValue>) {
if keys.is_empty() {
return;
}
let mut gone = lock(&self.gone_rows);
for key in keys {
if gone.len() >= GONE_ROWS {
break;
}
let noted = (name.to_owned(), key);
if !gone.contains(¬ed) {
gone.push(noted);
}
}
drop(gone);
self.wake();
}
}
fn has_table(connection: &Connection, table: &str) -> Result<bool> {
let failed = |error| sql_error(format!("look for table {table}"), error);
let mut select = connection.prepare_cached(HAS_TABLE).map_err(failed)?;
select.query_row([table], |row| row.get(0)).map_err(failed)
}
pub(crate) fn resolve(connection: &Connection, table: &Table, read: &[&str]) -> Result<Table> {
let failed = |error| sql_error(format!("read table {}", table.name), error);
let mut select = connection.prepare_cached(READ_COLUMNS).map_err(failed)?;
let rows = select.query_map([&table.name], |row| Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?)));
let columns: Vec<(String, i64)> = rows.and_then(Iterator::collect).map_err(failed)?;
if columns.is_empty() {
return Err(Error::invalid(format!("the database has no table {}", table.name)));
}
let mut primary: Vec<(i64, String)> =
columns.iter().filter(|(_, pk)| *pk > 0).map(|(name, pk)| (*pk, name.clone())).collect();
primary.sort_unstable();
let primary: Vec<String> = primary.into_iter().map(|(_, name)| name).collect();
let key = match table.key.as_slice() {
[] if primary.is_empty() => {
return Err(Error::invalid(format!(
"table {} has no primary key: give the index a key, a column or columns of unique values",
table.name
)));
}
[] => primary.clone(),
key => key.to_vec(),
};
if let Some(twice) = key.iter().enumerate().find(|(at, column)| key[..*at].contains(column)) {
return Err(Error::invalid(format!("a key names column {} twice", twice.1)));
}
let has = |column: &str| columns.iter().any(|(name, _)| name == column);
let vector = table.vector.as_deref();
let named = key.iter().map(String::as_str).chain(read.iter().copied()).chain(vector);
if let Some(missing) = named.into_iter().find(|column| !has(column)) {
return Err(Error::invalid(format!("table {} has no column {missing}", table.name)));
}
if !same_columns(&primary, &key) && !unique_by_an_index(connection, &table.name, &key)? {
return Err(not_unique(&table.name, &key));
}
Ok(Table { name: table.name.clone(), key, vector: table.vector.clone() })
}
fn unique_by_an_index(connection: &Connection, table: &str, key: &[String]) -> Result<bool> {
let failed = |error| sql_error(format!("read table {table}'s indexes"), error);
let mut select = connection.prepare_cached(UNIQUE_INDEXES).map_err(failed)?;
let rows = select.query_map([table], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)));
let rows: Vec<(String, String)> = rows.and_then(Iterator::collect).map_err(failed)?;
let mut indexes: std::collections::HashMap<&str, Vec<String>> = std::collections::HashMap::new();
for (index, column) in &rows {
indexes.entry(index).or_default().push(column.clone());
}
Ok(indexes.values().any(|columns| same_columns(columns, key)))
}
fn same_columns(a: &[String], b: &[String]) -> bool {
a.len() == b.len() && a.iter().all(|column| b.contains(column))
}
fn not_unique(table: &str, key: &[String]) -> Error {
Error::invalid(match key {
[one] => format!(
"column {one} of table {table} is no key: its values are not unique, by a primary key or a unique index"
),
columns => format!(
"columns {} of table {table} are no key: their values are not unique together, by a primary key or a \
unique index",
columns.join(", ")
),
})
}
pub trait Columns {
#[doc(hidden)]
fn columns(self) -> Vec<String>;
}
impl Columns for &str {
fn columns(self) -> Vec<String> {
vec![self.to_owned()]
}
}
impl Columns for &String {
fn columns(self) -> Vec<String> {
vec![self.clone()]
}
}
impl<S: AsRef<str>> Columns for &[S] {
fn columns(self) -> Vec<String> {
self.iter().map(|column| column.as_ref().to_owned()).collect()
}
}
impl<S: AsRef<str>, const N: usize> Columns for [S; N] {
fn columns(self) -> Vec<String> {
self.iter().map(|column| column.as_ref().to_owned()).collect()
}
}
impl<S: AsRef<str>> Columns for Vec<S> {
fn columns(self) -> Vec<String> {
self.iter().map(|column| column.as_ref().to_owned()).collect()
}
}
pub(crate) type ReadRows<T> =
Arc<dyn Fn(&Connection, &Arc<Memory>, (&str, &[SqlValue])) -> Result<Vec<Option<T>>> + Send + Sync>;
#[must_use = "an index opens at `open`"]
pub struct TableIndexBuilder<T> {
shared: Arc<SharedFile>,
name: String,
wanted: Wanted,
read_rows: ReadRows<T>,
}
impl<T> std::fmt::Debug for TableIndexBuilder<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TableIndexBuilder").field("name", &self.name).field("wanted", &self.wanted).finish()
}
}
impl<T: DeserializeOwned> TableIndexBuilder<T> {
pub(crate) fn in_file(shared: Arc<SharedFile>, name: &str, read_rows: ReadRows<T>) -> Self {
let table = Table { name: String::new(), key: Vec::new(), vector: None };
let wanted = Wanted { table: Some(table), ..Wanted::default() };
TableIndexBuilder { shared, name: name.to_owned(), wanted, read_rows }
}
pub fn table(mut self, table: &str) -> Self {
self.followed().name = table.to_owned();
self
}
pub fn key(mut self, columns: impl Columns) -> Self {
self.followed().key = columns.columns();
self
}
pub fn field(mut self, column: &str, weight: f64) -> Self {
self.wanted.fields.push((column.to_owned(), weight));
self
}
pub fn fields<S: AsRef<str>>(mut self, columns: impl IntoIterator<Item = S>) -> Self {
self.wanted.fields.extend(columns.into_iter().map(|column| (column.as_ref().to_owned(), 1.0)));
self
}
pub fn filters<S: AsRef<str>>(mut self, columns: impl IntoIterator<Item = S>) -> Self {
self.wanted.filters.extend(columns.into_iter().map(|column| column.as_ref().to_owned()));
self
}
pub fn typo_tolerance(mut self, on: bool) -> Self {
self.wanted.typo_tolerance = on;
self
}
pub fn layouts<S: AsRef<str>>(mut self, names: impl IntoIterator<Item = S>) -> Self {
self.wanted.layouts.extend(names.into_iter().map(|name| name.as_ref().to_owned()));
self
}
pub fn vectors(mut self, column: &str, dimensions: usize) -> Self {
self.followed().vector = Some(column.to_owned());
self.wanted.dimensions = Some(dimensions);
self
}
pub fn recall(mut self, recall: f64) -> Self {
self.wanted.recall = Some(recall);
self
}
pub fn vector_weight(mut self, weight: f64) -> Self {
self.wanted.vector_weight = Some(weight);
self
}
pub fn rerank(mut self) -> Self {
self.wanted.rerank = true;
self
}
pub fn rebuild(mut self, rebuild: Rebuild) -> Self {
self.wanted.manual = rebuild == Rebuild::Manual;
self
}
pub fn open(self) -> Result<TableIndex<T>> {
self.opened(false)
}
pub fn reindex(self) -> Result<TableIndex<T>> {
self.opened(true)
}
fn followed(&mut self) -> &mut Table {
self.wanted.table.get_or_insert_with(|| Table { name: String::new(), key: Vec::new(), vector: None })
}
fn opened(mut self, reindex: bool) -> Result<TableIndex<T>> {
let within = |error: Error| error.within(format!("index {}", self.name));
let asked = self.wanted.table.clone().filter(|table| !table.name.is_empty());
let asked = asked.ok_or_else(|| within(Error::invalid("a table's index names its table: table(name)")))?;
self.wanted.check().map_err(within)?;
let search = Search::in_file(&self.shared).map_err(within)?;
let read: Vec<&str> = self.wanted.fields.iter().map(|(column, _)| column.as_str()).collect();
let read: Vec<&str> = read.into_iter().chain(self.wanted.filters.iter().map(String::as_str)).collect();
let table = search.file.read(|connection| resolve(connection, &asked, &read)).map_err(within)?;
self.wanted.table = Some(table);
let open = crate::sqlite::own_work(|| search.open_index(&self.name, &self.wanted, reindex)).map_err(within)?;
Ok(TableIndex { index: Index::of_table(search, open, self.read_rows) })
}
}
pub struct TableIndex<T> {
index: Index<T>,
}
impl<T> Clone for TableIndex<T> {
fn clone(&self) -> Self {
TableIndex { index: self.index.clone() }
}
}
impl<T> std::fmt::Debug for TableIndex<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TableIndex").field("name", &self.index.open.name).finish()
}
}
impl<T: DeserializeOwned> TableIndex<T> {
pub fn name(&self) -> &str {
self.index.name()
}
pub fn search(&self, text: &str) -> SearchCall<'_, T> {
self.index.search(text)
}
pub fn search_vector<'i>(&'i self, vector: &'i [f32]) -> SearchCall<'i, T> {
self.index.search_vector(vector)
}
pub fn status(&self) -> Result<Status> {
self.index.status()
}
pub fn ready(&self) -> Result<()> {
self.index.ready()
}
#[cfg(any(test, feature = "async"))]
pub(crate) fn inner(&self) -> &Index<T> {
&self.index
}
#[cfg(feature = "wire")]
pub(crate) fn into_index(self) -> Index<T> {
self.index
}
}
impl<T> Sealed for TableIndex<T> {}
impl<T: DeserializeOwned> TxHandle for TableIndex<T> {
type InTx<'h>
= TxTableIndex<'h, T>
where
Self: 'h;
fn in_tx<'h>(&'h self, tx: &'h Transaction<'h>) -> TxTableIndex<'h, T> {
TxTableIndex { index: self, tx }
}
}
pub struct TxTableIndex<'a, T> {
index: &'a TableIndex<T>,
tx: &'a Transaction<'a>,
}
impl<T> std::fmt::Debug for TxTableIndex<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TxTableIndex").field("name", &self.index.index.open.name).finish()
}
}
impl<'a, T: DeserializeOwned> TxTableIndex<'a, T> {
pub fn search(&self, text: &str) -> SearchCall<'a, T> {
self.index.index.search(text).in_tx(self.tx)
}
pub fn search_vector(&self, vector: &'a [f32]) -> SearchCall<'a, T> {
self.index.index.search_vector(vector).in_tx(self.tx)
}
}
impl<T> Index<T> {
pub(crate) fn of_table(search: Arc<Search>, open: Arc<OpenIndex>, read_rows: ReadRows<T>) -> Self {
Index { search, open, read_rows: Some(read_rows), _value: std::marker::PhantomData }
}
}
pub(crate) type RowsReader<'r, R> =
&'r dyn Fn(&Connection, &Arc<Memory>, (&str, &[SqlValue])) -> Result<Vec<Option<R>>>;
pub(crate) fn found<T, R>(
index: &Index<T>,
read_rows: RowsReader<'_, R>,
query: Query,
tx: Option<&Transaction<'_>>,
) -> Result<Found<R>> {
let read = |connection: &Connection,
settings: &Settings,
answer: &Answer|
-> Result<(Vec<Option<R>>, ColumnsRead)> {
let select = table::hit_select(&table_of(settings)?);
let keys = answer.hits.iter().map(|hit| table::hit_key(&hit.value)).collect::<Result<Vec<_>>>()?;
let rows = read_rows(connection, &index.search.memory, (&select, &keys))?;
let columns = match answer.sought {
Some(_) => keys.iter().map(|key| table::columns_read(connection, settings, key)).collect::<Result<_>>()?,
None => Vec::new(),
};
Ok((rows, columns))
};
let search = |query: Query| -> Result<Searched<R>> {
match tx {
None => index.search.search_then(&index.open, query, read),
Some(tx) => {
tx.takes(&index.search.file, index.search.place())?;
tx.call(|writer| index.search.search_in(writer, &index.open, query, read))
}
}
};
let limit = query.limit;
let (answer, (rows, mut columns)) =
filled(query, search, |gone| index.search.note_gone_rows(&index.open.name, gone))?;
columns.resize(rows.len(), None);
let Answer { hits, corrected, sought, total, .. } = answer;
let hits = hits.into_iter().zip(rows).zip(columns).filter_map(|((ranked, row), columns)| {
let matches =
sought.as_ref().zip(columns).map(|(sought, columns)| sought.matches(&columns)).unwrap_or_default();
let Ranked { id, score, text_score, similarity, .. } = ranked;
row.map(|value| Hit { id, value, score, matches, text_score, similarity })
});
Ok(Found { hits: hits.take(limit).collect(), corrected, total })
}
type Searched<R> = (Answer, (Vec<Option<R>>, ColumnsRead));
fn filled<R>(
query: Query,
search: impl Fn(Query) -> Result<Searched<R>>,
note: impl Fn(Vec<SqlValue>),
) -> Result<Searched<R>> {
let limit = query.limit;
let reach = (crate::limits::SEARCH_HITS.bound as usize).saturating_sub(query.offset);
let mut asked = limit;
loop {
let (answer, (rows, columns)) = search(Query { limit: asked, ..query.clone() })?;
let gone = answer.hits.iter().zip(&rows).filter(|(_, row)| row.is_none());
let gone: Vec<SqlValue> = gone.map(|(hit, _)| table::hit_key(&hit.value)).collect::<Result<_>>()?;
let (found, held) = (answer.hits.len(), answer.hits.len() - gone.len());
let more = (limit + gone.len()).max(asked * 2).min(reach);
note(gone);
if held >= limit || found < asked || more <= asked {
return Ok((answer, (rows, columns)));
}
asked = more;
}
}
type ColumnsRead = Vec<Option<serde_json::Value>>;
pub(crate) fn drop_in_file(shared: &SharedFile, name: &str) -> Result<bool> {
let within = |error: Error| error.within(format!("index {name}"));
Search::in_file(shared).and_then(|search| search.drop_index(name)).map_err(within)
}
#[cfg(feature = "wire")]
pub(crate) fn found_by<T: DeserializeOwned, R>(
call: SearchCall<'_, T>,
read_rows: RowsReader<'_, R>,
) -> Result<Found<R>> {
let (index, query) = call.asked()?;
found(index, read_rows, query, None)
}
#[cfg(feature = "wire")]
pub(crate) fn table_as_it_is<T: DeserializeOwned>(shared: &SharedFile, name: &str) -> Result<Index<T>> {
let within = |error: Error| error.within(format!("index {name}"));
shared.keeps("_tinystore_search_indexes", "index").map_err(within)?;
let search = Search::in_file(shared).map_err(within)?;
let open = search.open_existing(name).map_err(within)?;
if open.current().serving.settings.table.is_none() {
return Err(within(Error::invalid("an index of documents, which a database keeps none of")));
}
Ok(Index::of_table(search, open, by_cells()))
}
#[cfg(feature = "wire")]
pub(crate) fn by_cells<T>() -> ReadRows<T> {
Arc::new(|_, _, _| Err(Error::internal("the wire reads a table's rows by their cells")))
}
fn table_of(settings: &Settings) -> Result<Table> {
settings.table.clone().ok_or_else(|| Error::internal("a table's index without its table"))
}
#[cfg(test)]
#[path = "table_tests.rs"]
mod tests;