Skip to main content

reddb_server/runtime/
table_row_mvcc_resolver.rs

1use crate::storage::unified::entity::{EntityId, EntityKind, UnifiedEntity};
2use crate::storage::unified::UnifiedStore;
3
4/// Table-row-only MVCC read resolver for the current statement.
5///
6/// Candidate discovery stays with each caller. This resolver owns the
7/// table-row visibility decision before a candidate is materialized.
8#[derive(Clone)]
9pub(crate) struct TableRowMvccReadResolver {
10    snapshot: TableRowReadSnapshot,
11}
12
13#[derive(Clone)]
14enum TableRowReadSnapshot {
15    CurrentThread,
16    Captured(Option<super::impl_core::SnapshotContext>),
17}
18
19impl TableRowMvccReadResolver {
20    pub(crate) fn current_statement() -> Self {
21        Self {
22            snapshot: TableRowReadSnapshot::CurrentThread,
23        }
24    }
25
26    pub(crate) fn captured(snapshot: Option<super::impl_core::SnapshotContext>) -> Self {
27        Self {
28            snapshot: TableRowReadSnapshot::Captured(snapshot),
29        }
30    }
31
32    pub(crate) fn resolve_candidate<'a>(
33        &self,
34        candidate: &'a UnifiedEntity,
35    ) -> Option<&'a UnifiedEntity> {
36        if !matches!(candidate.kind, EntityKind::TableRow { .. }) {
37            return None;
38        }
39        if self.visible(candidate) {
40            Some(candidate)
41        } else {
42            None
43        }
44    }
45
46    pub(crate) fn resolve_read_candidate<'a>(
47        &self,
48        candidate: &'a UnifiedEntity,
49    ) -> Option<&'a UnifiedEntity> {
50        if matches!(candidate.kind, EntityKind::TableRow { .. }) {
51            return self.resolve_candidate(candidate);
52        }
53        if self.visible(candidate) {
54            Some(candidate)
55        } else {
56            None
57        }
58    }
59
60    pub(crate) fn try_resolve_logical_id(
61        &self,
62        store: &UnifiedStore,
63        collection: &str,
64        logical_id: EntityId,
65    ) -> crate::RedDBResult<Option<UnifiedEntity>> {
66        let mut selected = reddb_engine::transaction::read::try_resolve_logical_id(
67            store,
68            collection,
69            logical_id,
70            self.needs_version_selection(),
71            |entity| self.resolve_candidate(entity).is_some(),
72        )?;
73        if let Some(manager) = store.get_collection(collection) {
74            manager.restore_owned_row_schemas(selected.iter_mut());
75        }
76        Ok(selected)
77    }
78
79    fn needs_version_selection(&self) -> bool {
80        match &self.snapshot {
81            TableRowReadSnapshot::CurrentThread => {
82                super::impl_core::capture_current_snapshot().is_some()
83            }
84            TableRowReadSnapshot::Captured(snapshot) => snapshot.is_some(),
85        }
86    }
87
88    fn visible(&self, candidate: &UnifiedEntity) -> bool {
89        match &self.snapshot {
90            TableRowReadSnapshot::CurrentThread => {
91                super::impl_core::entity_visible_under_current_snapshot(candidate)
92            }
93            TableRowReadSnapshot::Captured(snapshot) => {
94                super::impl_core::entity_visible_with_context(snapshot.as_ref(), candidate)
95            }
96        }
97    }
98}
99
100impl reddb_engine::transaction::read::TableRowVersionStore for UnifiedStore {
101    fn table_row_versions_by_logical_id(
102        &self,
103        collection: &str,
104        logical_id: EntityId,
105    ) -> Vec<UnifiedEntity> {
106        UnifiedStore::table_row_versions_by_logical_id(self, collection, logical_id)
107    }
108
109    fn get_table_row_by_logical_id(
110        &self,
111        collection: &str,
112        logical_id: EntityId,
113    ) -> Option<UnifiedEntity> {
114        UnifiedStore::get_table_row_by_logical_id(self, collection, logical_id)
115    }
116}
117
118impl reddb_engine::transaction::read::FallibleTableRowVersionStore for UnifiedStore {
119    type Error = crate::storage::StoreError;
120
121    fn try_get_table_row_by_logical_id(
122        &self,
123        collection: &str,
124        logical_id: EntityId,
125    ) -> Result<Option<UnifiedEntity>, Self::Error> {
126        UnifiedStore::try_get_table_row_by_logical_id(self, collection, logical_id)
127    }
128
129    fn try_for_each_table_row_version(
130        &self,
131        collection: &str,
132        logical_id: EntityId,
133        visit: impl FnMut(&UnifiedEntity) -> bool,
134    ) -> Result<(), Self::Error> {
135        UnifiedStore::try_for_each_table_row_version(self, collection, logical_id, visit)
136    }
137
138    fn try_live_table_row_head(
139        &self,
140        collection: &str,
141        logical_id: EntityId,
142    ) -> Result<Option<UnifiedEntity>, Self::Error> {
143        UnifiedStore::try_live_table_row_head(self, collection, logical_id)
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use std::collections::HashSet;
150    use std::sync::Arc;
151
152    use super::*;
153    use crate::storage::transaction::snapshot::{Snapshot, SnapshotManager};
154    use crate::storage::unified::entity::{EntityId, UnifiedEntity};
155    use reddb_types::Value;
156
157    fn row_with_xids(xmin: u64, xmax: u64) -> UnifiedEntity {
158        let mut row =
159            UnifiedEntity::table_row(EntityId::new(1), "accounts", 1, vec![Value::Integer(1)]);
160        row.set_xmin(xmin);
161        row.set_xmax(xmax);
162        row
163    }
164
165    fn snapshot_context(xid: u64) -> super::super::impl_core::SnapshotContext {
166        super::super::impl_core::SnapshotContext {
167            branch: None,
168            snapshot: Snapshot {
169                xid,
170                in_progress: HashSet::new(),
171            },
172            manager: Arc::new(SnapshotManager::new()),
173            own_xids: HashSet::new(),
174            requires_index_fallback: false,
175            hidden_writers_only: false,
176            serializable_reader: None,
177        }
178    }
179
180    #[test]
181    fn current_row_fallback_keeps_live_legacy_rows_visible() {
182        super::super::impl_core::clear_current_snapshot();
183        let resolver = TableRowMvccReadResolver::current_statement();
184        let row = row_with_xids(0, 0);
185
186        assert!(resolver.resolve_candidate(&row).is_some());
187    }
188
189    #[test]
190    fn current_row_fallback_hides_tombstoned_rows() {
191        super::super::impl_core::clear_current_snapshot();
192        let resolver = TableRowMvccReadResolver::current_statement();
193        let row = row_with_xids(0, 4);
194
195        assert!(resolver.resolve_candidate(&row).is_none());
196    }
197
198    #[test]
199    fn captured_snapshot_applies_xmin_and_xmax_visibility() {
200        let resolver = TableRowMvccReadResolver::captured(Some(snapshot_context(10)));
201
202        assert!(resolver.resolve_candidate(&row_with_xids(5, 0)).is_some());
203        assert!(resolver.resolve_candidate(&row_with_xids(11, 0)).is_none());
204        assert!(resolver.resolve_candidate(&row_with_xids(5, 9)).is_none());
205        assert!(resolver.resolve_candidate(&row_with_xids(5, 11)).is_some());
206    }
207
208    #[test]
209    fn read_candidate_uses_same_snapshot_gate_for_table_rows() {
210        let resolver = TableRowMvccReadResolver::captured(Some(snapshot_context(10)));
211
212        assert!(resolver
213            .resolve_read_candidate(&row_with_xids(5, 11))
214            .is_some());
215        assert!(resolver
216            .resolve_read_candidate(&row_with_xids(11, 0))
217            .is_none());
218    }
219}