Skip to main content

uqa_execution/query/
local_table.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Physical scans over persisted rows, generated fields, recheck pins, and command overlays.
8
9use crate::RowSchemaExecution;
10use std::sync::Arc;
11use uqa_core::Value;
12use uqa_sql::{plan::source_projection::RelationMetadataProjection, ResultRow, SQLError};
13
14mod borrowed;
15mod command_scan;
16mod row_source;
17
18pub type SharedLockOrigin = (Arc<str>, Arc<str>);
19
20pub struct LocalTableRowSource {
21    cancellation: uqa_core::CancellationToken,
22    serializable: crate::serializable::SerializableScan,
23    table_name: String,
24    table: Arc<dyn super::table_read::TableRead>,
25    column_definitions: Arc<Vec<uqa_sql::ast::ColumnDef>>,
26    columns: Vec<String>,
27    schema: Vec<String>,
28    physical_schema: crate::RowSchema,
29    metadata: RelationMetadataProjection,
30    table_oid: Option<Value>,
31    predicate: Option<crate::ProjectedPredicate>,
32    estimated_cardinality: u64,
33    after: Option<uqa_core::DocId>,
34    lock_origin: Option<SharedLockOrigin>,
35    recheck_pins: Option<Arc<Vec<crate::row_locks::recheck::RecheckDoc>>>,
36    recheck_cursor: usize,
37    /// The only identities the scan's filter admits, in ascending order, and the position of the next of them.
38    candidates: Option<Arc<[uqa_core::DocId]>>,
39    candidate_cursor: usize,
40    command_changes: Option<super::document_changes::DocumentChanges>,
41    command_change_after: Option<uqa_core::DocId>,
42    /// The next changes of the command scan after `command_change_after`, read a page at a time.
43    command_change_page: std::collections::VecDeque<(uqa_core::DocId, bool)>,
44    command_changes_exhausted: bool,
45    command_base_after: Option<uqa_core::DocId>,
46    command_base_ids: std::collections::VecDeque<uqa_core::DocId>,
47    command_base_exhausted: bool,
48}
49
50/// One logical inheritance scan over independently stored physical tables.
51/// Each child source retains its own lock origin and command overlay while the
52/// SQL-visible row type remains the selected ancestor's row type.
53pub struct HierarchyRowSource {
54    sources: std::collections::VecDeque<LocalTableRowSource>,
55    schema: Vec<String>,
56    physical_schema: crate::RowSchema,
57    estimated_cardinality: u64,
58}
59
60impl HierarchyRowSource {
61    pub fn new(sources: Vec<LocalTableRowSource>) -> Result<Self, SQLError> {
62        let first = sources.first().ok_or_else(|| {
63            SQLError::Internal("inheritance scan was built without a physical table".into())
64        })?;
65        let schema = first.schema.clone();
66        let physical_schema = first.physical_schema.clone();
67        let estimated_cardinality = sources
68            .iter()
69            .map(|source| source.estimated_cardinality)
70            .sum();
71        Ok(Self {
72            sources: sources.into(),
73            schema,
74            physical_schema,
75            estimated_cardinality,
76        })
77    }
78}
79
80impl crate::RowSource for HierarchyRowSource {
81    fn schema(&self) -> &[String] {
82        &self.schema
83    }
84
85    fn physical_schema(&self) -> Option<&crate::RowSchema> {
86        Some(&self.physical_schema)
87    }
88
89    fn estimated_cardinality(&self) -> Option<u64> {
90        Some(self.estimated_cardinality)
91    }
92
93    fn next_row(&mut self) -> crate::ExecResult<Option<ResultRow>> {
94        Ok(self.next_batch(1)?.pop())
95    }
96
97    fn next_batch(&mut self, max_rows: usize) -> crate::ExecResult<Vec<ResultRow>> {
98        let rows = self.next_physical_batch(max_rows)?;
99        Ok(rows
100            .iter()
101            .map(|row| self.physical_schema.view(row).to_result_row())
102            .collect())
103    }
104
105    fn next_physical_batch(
106        &mut self,
107        max_rows: usize,
108    ) -> crate::ExecResult<Vec<crate::PhysicalRow>> {
109        let mut rows = Vec::with_capacity(max_rows);
110        while rows.len() < max_rows {
111            let Some(source) = self.sources.front_mut() else {
112                break;
113            };
114            let mut batch = source.next_physical_rows_batch(max_rows - rows.len())?;
115            if batch.is_empty() {
116                self.sources.pop_front();
117            } else {
118                rows.append(&mut batch);
119            }
120        }
121        Ok(rows)
122    }
123}
124
125pub struct LocalTableScanConfig {
126    pub cancellation: uqa_core::CancellationToken,
127    pub serializable: Option<crate::serializable::SerializableRelationRead>,
128    pub table_name: String,
129    pub table: Arc<dyn super::table_read::TableRead>,
130    pub column_definitions: Arc<Vec<uqa_sql::ast::ColumnDef>>,
131    pub columns: Vec<String>,
132    pub schema: Vec<String>,
133    pub physical_schema: crate::RowSchema,
134    pub metadata: RelationMetadataProjection,
135    pub table_oid: Option<Value>,
136    pub predicate: Option<crate::ProjectedPredicate>,
137    pub estimated_cardinality: u64,
138    pub lock_origin: Option<SharedLockOrigin>,
139    pub recheck_pins: Option<Arc<Vec<crate::row_locks::recheck::RecheckDoc>>>,
140    /// The only identities the scan's filter admits, in ascending order.
141    pub candidates: Option<Arc<[uqa_core::DocId]>>,
142    pub command_changes: Option<super::document_changes::DocumentChanges>,
143}
144
145impl LocalTableRowSource {
146    pub fn new(config: LocalTableScanConfig) -> Self {
147        Self {
148            cancellation: config.cancellation,
149            serializable: crate::serializable::SerializableScan::new(config.serializable),
150            table_name: config.table_name,
151            table: config.table,
152            column_definitions: config.column_definitions,
153            columns: config.columns,
154            schema: config.schema,
155            physical_schema: config.physical_schema,
156            metadata: config.metadata,
157            table_oid: config.table_oid,
158            predicate: config.predicate,
159            estimated_cardinality: config.estimated_cardinality,
160            lock_origin: config.lock_origin,
161            recheck_pins: config.recheck_pins,
162            candidates: config.candidates,
163            command_changes: config.command_changes,
164            after: None,
165            recheck_cursor: 0,
166            candidate_cursor: 0,
167            command_change_after: None,
168            command_change_page: std::collections::VecDeque::new(),
169            command_changes_exhausted: false,
170            command_base_after: None,
171            command_base_ids: std::collections::VecDeque::new(),
172            command_base_exhausted: false,
173        }
174    }
175}
176
177pub use row_source::table_lock_origin;