Skip to main content

uqa_storage_sqlite/btree_index/
entries.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Read previously evaluated keys on one provider boundary without collecting their population.
8
9use super::{decode_doc_id, decode_value, native, SQLiteBTreeIndexStore, SQLiteValueIndexKey};
10use rusqlite::{params, OptionalExtension};
11use uqa_core::{DocId, Value};
12use uqa_storage::{StorageBackendResult, ValueIndexKey};
13
14impl SQLiteBTreeIndexStore {
15    pub fn visit_entries(
16        &self,
17        table: &str,
18        field: &ValueIndexKey,
19        visit: &mut dyn FnMut(DocId, Value) -> StorageBackendResult<()>,
20    ) -> StorageBackendResult<bool> {
21        // A consumer's error belongs to that consumer, not the SQLite diagnostic adapter.
22        let mut failure = None;
23        let mut capture = |id, value| match visit(id, value) {
24            Ok(()) => Ok(()),
25            Err(error) => {
26                failure = Some(error);
27                Err(super::SQLiteError::StorageBackend(
28                    "index entry consumer stopped".into(),
29                ))
30            }
31        };
32        let result = if let Some(snapshot) = self.conn.native_snapshot()? {
33            native::visit_entries(&snapshot, table, field, &mut capture)
34        } else {
35            self.conn.with(|conn| {
36                let exists = conn
37                    .prepare_cached(
38                        "SELECT 1 FROM _btree_indexes WHERE table_name = ?1 AND field = ?2",
39                    )?
40                    .query_row(params![table, SQLiteValueIndexKey(field)], |_| Ok(()))
41                    .optional()?
42                    .is_some();
43                if !exists {
44                    return Ok(false);
45                }
46                let mut statement = conn.prepare_cached(
47                    "SELECT doc_id, value_json FROM _btree_index_entries
48                     WHERE table_name = ?1 AND field = ?2 ORDER BY doc_id",
49                )?;
50                let mut rows = statement.query(params![table, SQLiteValueIndexKey(field)])?;
51                while let Some(row) = rows.next()? {
52                    let id = decode_doc_id(row.get(0)?)?;
53                    let encoded: String = row.get(1)?;
54                    capture(id, decode_value(&encoded)?)?;
55                }
56                Ok(true)
57            })
58        };
59        if let Some(error) = failure {
60            return Err(error);
61        }
62        result.map_err(Into::into)
63    }
64}
65
66#[cfg(test)]
67mod tests;