Skip to main content

uqa_execution/
serializable.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Logical relation and row observations selected by the executing access path.
8
9use uqa_core::{CancellationToken, DocId};
10use uqa_sql::SQLError;
11use uqa_storage::{
12    mvcc::{
13        SerializableKeySpace, SerializablePredicate, SerializableReadContext, SerializableSession,
14    },
15    read_control::StorageReadControl,
16};
17
18use crate::storage_errors::storage_error;
19
20/// A physical reader retains its original participant, immutable relation identity and shared allowance. It can neither admit another participant nor finish its transaction.
21#[derive(Clone)]
22pub struct SerializableRelationRead {
23    object: [u8; 16],
24    context: SerializableReadContext,
25    control: StorageReadControl,
26}
27
28impl SerializableRelationRead {
29    pub fn new(
30        object: [u8; 16],
31        context: SerializableReadContext,
32        cancellation: &CancellationToken,
33    ) -> Self {
34        let control = context.read_control(cancellation);
35        Self {
36            object,
37            context,
38            control,
39        }
40    }
41
42    /// Retain the original mutation participant before reading its selected target, including an absent unique-key match.
43    pub fn for_mutation(
44        writes: &dyn SerializableWrites,
45        table: &str,
46    ) -> Result<Option<Self>, SQLError> {
47        let Some(session) = writes.serializable_session() else {
48            return Ok(None);
49        };
50        let Some(context) = session
51            .serializable_read_context()
52            .map_err(|error| storage_error("retain serializable mutation reader", &error))?
53        else {
54            return Ok(None);
55        };
56        Ok(writes
57            .serializable_write_object(table)?
58            .map(|object| Self::new(object, context, writes.serializable_cancellation())))
59    }
60
61    /// A sequential access path observes the relation before reading even an empty result. Index access paths must supply their own precise logical ranges instead.
62    pub fn observe_scan(&self) -> Result<(), SQLError> {
63        self.observe(SerializablePredicate::object(self.object))
64    }
65
66    /// Rechecks observe the selected logical row even when it is absent or supplied from a retained cache.
67    pub fn observe_row(&self, doc_id: DocId) -> Result<(), SQLError> {
68        self.observe(SerializablePredicate::point(
69            self.object,
70            SerializableKeySpace::Rows,
71            &doc_id.to_be_bytes(),
72        ))
73    }
74
75    fn observe(&self, predicate: SerializablePredicate<'_>) -> Result<(), SQLError> {
76        self.context
77            .observe_read(predicate, &self.control)
78            .map_err(|error| {
79                storage_error("observe serializable read", &error.into_storage_error())
80            })
81    }
82}
83
84/// Demand-driven sources retain one relation observation for a sequential scan and precise row observations for selected tuple rechecks.
85#[derive(Default)]
86pub struct SerializableScan {
87    read: Option<SerializableRelationRead>,
88    relation_observed: bool,
89}
90
91impl SerializableScan {
92    pub fn new(read: Option<SerializableRelationRead>) -> Self {
93        Self {
94            read,
95            relation_observed: false,
96        }
97    }
98
99    pub fn observe_relation(&mut self) -> Result<(), SQLError> {
100        if !self.relation_observed {
101            if let Some(read) = &self.read {
102                read.observe_scan()?;
103            }
104            self.relation_observed = true;
105        }
106        Ok(())
107    }
108
109    pub fn observe_row(&self, doc_id: DocId) -> Result<(), SQLError> {
110        if let Some(read) = &self.read {
111            read.observe_row(doc_id)?;
112        }
113        Ok(())
114    }
115}
116
117/// State adapters supply the original mutation session and a persistent relation's immutable identity. Temporary relations do not participate in shared conflict tracking.
118pub trait SerializableWrites {
119    fn serializable_session(&self) -> Option<&dyn SerializableSession>;
120    fn serializable_cancellation(&self) -> &CancellationToken;
121    fn serializable_write_object(&self, table: &str) -> Result<Option<[u8; 16]>, SQLError>;
122}
123
124/// Record evaluated row intent before its private mutation. The surrounding statement/savepoint owns rollback of both the intent and the row change.
125pub fn observe_row_write(
126    writes: &dyn SerializableWrites,
127    table: &str,
128    doc_id: DocId,
129) -> Result<(), SQLError> {
130    let Some(session) = writes.serializable_session() else {
131        return Ok(());
132    };
133    if session
134        .serializable_read_context()
135        .map_err(|error| storage_error("inspect serializable writer", &error))?
136        .is_none()
137    {
138        return Ok(());
139    }
140    let Some(object) = writes.serializable_write_object(table)? else {
141        return Ok(());
142    };
143    session
144        .observe_serializable_write(SerializablePredicate::point(
145            object,
146            SerializableKeySpace::Rows,
147            &doc_id.to_be_bytes(),
148        ))
149        .map_err(|error| storage_error("observe serializable write", &error))
150}
151
152pub mod column_index;
153mod field;
154pub mod index_key;
155pub mod text;
156pub mod vector;