Skip to main content

uqa_engine/table_storage/documents/
exact_lookup.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Supply the selected table, private rows and transaction reader to execution-owned exact lookups.
8
9use crate::{Engine, TableState};
10use std::sync::Arc;
11use uqa_core::{DocId, Value};
12use uqa_execution::{
13    mutation::overlay::CommandMutationOverlay,
14    query::document_changes::DocumentChanges,
15    query::exact_lookup::{ExactLookup, ExactLookupOverlay, FieldPresence},
16    serializable::SerializableRelationRead,
17    storage_errors::storage_error,
18};
19use uqa_sql::SQLError;
20use uqa_storage::ValueIndexKey;
21
22struct CommandOverlay<'a> {
23    engine: &'a Engine,
24    table: String,
25}
26
27impl ExactLookupOverlay for CommandOverlay<'_> {
28    fn is_empty(&self) -> Result<bool, SQLError> {
29        Ok(!self
30            .engine
31            .session
32            .command_mutation_overlays
33            .lock()
34            .iter()
35            .any(|overlay| overlay.holds(&self.table)))
36    }
37
38    fn masks(&self, doc_id: DocId) -> Result<bool, SQLError> {
39        let control = self.engine.query_retention_control()?;
40        CommandMutationOverlay::stages(
41            &self.engine.session.command_mutation_overlays.lock(),
42            &self.table,
43            doc_id,
44            &control,
45        )
46    }
47
48    fn find_match(
49        &self,
50        columns: &[String],
51        values: &[Value],
52        presence: FieldPresence,
53    ) -> Result<Option<DocId>, SQLError> {
54        self.engine
55            .command_overlay_exact_match(&self.table, columns, values, presence)
56    }
57}
58
59/// The changes a read merges for a table: this transaction's rows that a fixed snapshot does not show, below the rows the running commands staged, whose exact indexes answer key probes.
60struct QueryOverlay<'a> {
61    fixed: DocumentChanges,
62    commands: CommandOverlay<'a>,
63}
64
65impl<'a> QueryOverlay<'a> {
66    fn new(engine: &'a Engine, table: &str) -> Result<Self, SQLError> {
67        let canonical = engine.command_overlay_table_name(table)?;
68        Ok(Self {
69            fixed: engine
70                .fixed_transaction_row_changes(&canonical)?
71                .unwrap_or_default(),
72            commands: CommandOverlay {
73                engine,
74                table: canonical,
75            },
76        })
77    }
78}
79
80impl ExactLookupOverlay for QueryOverlay<'_> {
81    fn is_empty(&self) -> Result<bool, SQLError> {
82        Ok(!self.fixed.has_changes() && self.commands.is_empty()?)
83    }
84
85    fn masks(&self, doc_id: DocId) -> Result<bool, SQLError> {
86        Ok(self.commands.masks(doc_id)? || self.fixed.masks(doc_id)?)
87    }
88
89    /// The smallest visible identity whose row matches: a staged row, or a fixed-snapshot row that no command restaged.
90    fn find_match(
91        &self,
92        columns: &[String],
93        values: &[Value],
94        presence: FieldPresence,
95    ) -> Result<Option<DocId>, SQLError> {
96        let staged = self.commands.find_match(columns, values, presence)?;
97        if !self.fixed.has_changes() {
98            return Ok(staged);
99        }
100        for change in self.fixed.changes() {
101            let (id, present) =
102                change.map_err(|error| storage_error("read private exact key", &error))?;
103            if staged.is_some_and(|staged| id >= staged) {
104                break;
105            }
106            if !present || self.commands.masks(id)? {
107                continue;
108            }
109            if self.fixed.row_matches_with_catalog(
110                id,
111                columns,
112                values,
113                presence,
114                Some(self.commands.engine),
115            )? {
116                return Ok(Some(id));
117            }
118        }
119        Ok(staged)
120    }
121}
122
123impl Engine {
124    pub fn find_doc_id_by_field(
125        &self,
126        table: &str,
127        field: &str,
128        value: &Value,
129    ) -> Result<Option<DocId>, SQLError> {
130        self.with_direct_table_read(table, |engine, name, table| {
131            let overlay = QueryOverlay::new(engine, name)?;
132            let read = engine.serializable_table_state_read(table)?;
133            ExactLookup {
134                catalog: Some(engine),
135                table: table.as_ref(),
136                overlay: &overlay,
137                read: read.as_ref(),
138            }
139            .find_field_with_index(field, value, |field, value| {
140                engine.read_value_index_state(
141                    name,
142                    table,
143                    &ValueIndexKey::Column(field.into()),
144                    |index| index.field_candidates(value, &engine.query_retention_control()?),
145                )
146            })
147        })
148    }
149
150    pub(crate) fn find_mutation_doc_id_by_field(
151        &self,
152        table: &str,
153        field: &str,
154        value: &Value,
155    ) -> Result<Option<DocId>, SQLError> {
156        let table_state = self.require_table(table)?;
157        let overlay = CommandOverlay {
158            engine: self,
159            table: self.command_overlay_table_name(table)?,
160        };
161        ExactLookup {
162            catalog: Some(self),
163            table: table_state.as_ref(),
164            overlay: &overlay,
165            read: None,
166        }
167        .find_field_with_index(field, value, |field, value| {
168            self.read_value_index_state(
169                table,
170                &table_state,
171                &ValueIndexKey::Column(field.into()),
172                |index| index.field_candidates(value, &self.query_retention_control()?),
173            )
174        })
175    }
176
177    /// Find a matching conflict key in the caller's transaction snapshot. Execution selects the integer primary-key mapping, an answerable value index, or an evaluated scan and records the corresponding serializable read.
178    pub fn find_conflict(
179        &self,
180        table: &str,
181        columns: &[String],
182        values: &[Value],
183    ) -> Result<Option<DocId>, SQLError> {
184        self.with_direct_table_read(table, |engine, name, table| {
185            let overlay = QueryOverlay::new(engine, name)?;
186            let read = engine.serializable_table_state_read(table)?;
187            engine.find_conflict_in_state(name, table, columns, values, &overlay, read.as_ref())
188        })
189    }
190
191    pub(crate) fn find_mutation_conflict(
192        &self,
193        table: &str,
194        columns: &[String],
195        values: &[Value],
196    ) -> Result<Option<DocId>, SQLError> {
197        let table_state = self.require_table(table)?;
198        let overlay = CommandOverlay {
199            engine: self,
200            table: self.command_overlay_table_name(table)?,
201        };
202        self.find_conflict_in_state(table, &table_state, columns, values, &overlay, None)
203    }
204
205    fn find_conflict_in_state(
206        &self,
207        name: &str,
208        table: &Arc<TableState>,
209        columns: &[String],
210        values: &[Value],
211        overlay: &dyn ExactLookupOverlay,
212        read: Option<&SerializableRelationRead>,
213    ) -> Result<Option<DocId>, SQLError> {
214        let schema_columns = table.columns.snapshot();
215        ExactLookup {
216            catalog: Some(self),
217            table: table.as_ref(),
218            overlay,
219            read,
220        }
221        .find_conflict(&schema_columns, columns, values, |column, predicate| {
222            self.value_index_scan_state(
223                name,
224                table,
225                &ValueIndexKey::Column(column.into()),
226                predicate,
227                read,
228            )
229        })
230    }
231}