Skip to main content

reddb_server/runtime/
impl_fast_path.rs

1//! Fast-path entity lookup, plan-cache invalidation, and DDL epoch.
2//!
3//! Extracted verbatim from `impl_core.rs` (impl_core slice 9/10, issue #1630).
4//! Houses the string-pattern `try_fast_entity_lookup`, `invalidate_plan_cache`,
5//! the monotonic `ddl_epoch` reader, and `clear_table_planner_stats`.
6use super::execution_context::entity_visible_under_current_snapshot;
7use super::*;
8
9impl RedDBRuntime {
10    /// Ultra-fast path: detect `SELECT * FROM table WHERE _entity_id = N` by string pattern
11    /// and execute it without SQL parsing or planning. Returns None if pattern doesn't match.
12    pub(crate) fn try_fast_entity_lookup(
13        &self,
14        query: &str,
15    ) -> Option<RedDBResult<RuntimeQueryResult>> {
16        // Pattern: "SELECT * FROM <table> WHERE _entity_id = <id>"
17        // or "SELECT * FROM <table> WHERE _entity_id =<id>"
18        let q = query.trim();
19        if !q.starts_with("SELECT") && !q.starts_with("select") {
20            return None;
21        }
22
23        // Find "WHERE _entity_id = " or "WHERE _entity_id ="
24        let where_pos = q
25            .find("WHERE _entity_id")
26            .or_else(|| q.find("where _entity_id"))?;
27        let after_field = &q[where_pos + 16..].trim_start(); // skip "WHERE _entity_id"
28        let after_eq = after_field.strip_prefix('=')?.trim_start();
29
30        // Parse the entity ID number
31        let id_str = after_eq.trim();
32        let entity_id: u64 = id_str.parse().ok()?;
33
34        // Extract table name: between "FROM " and " WHERE"
35        let from_pos = q.find("FROM ").or_else(|| q.find("from "))? + 5;
36        let table = q[from_pos..where_pos].trim();
37        if table.is_empty()
38            || table.contains(' ') && !table.contains(" AS ") && !table.contains(" as ")
39        {
40            return None; // complex query, fall through
41        }
42        let table_name = table.split_whitespace().next()?;
43
44        // Direct entity lookup — skips SQL parse, plan cache, result
45        // cache, view rewriter, RLS gate. Safe because the gating in
46        // `execute_query` guarantees no scope override / no
47        // transaction context is active. MVCC visibility is still
48        // honoured against the current snapshot.
49        let store = self.inner.db.store();
50        let entity = store
51            .get(
52                table_name,
53                crate::storage::unified::EntityId::new(entity_id),
54            )
55            .filter(entity_visible_under_current_snapshot)
56            .filter(|entity| {
57                self.inner
58                    .db
59                    .replica_allows_entity_at_read(table_name, entity)
60            });
61
62        let count = if entity.is_some() { 1u64 } else { 0 };
63
64        // Materialize a record so downstream consumers that walk
65        // `result.records` (embedded runtime API, decrypt pass, CLI)
66        // see the row. Previously only `pre_serialized_json` was
67        // filled, which caused those consumers to see zero rows and
68        // skewed benchmarks.
69        let records: Vec<crate::storage::query::unified::UnifiedRecord> = entity
70            .as_ref()
71            .and_then(|e| runtime_table_record_from_entity(e.clone()))
72            .into_iter()
73            .collect();
74
75        let json = match entity {
76            Some(ref e) => execute_runtime_serialize_single_entity(e),
77            None => r#"{"columns":[],"record_count":0,"selection":{"scope":"any"},"records":[]}"#
78                .to_string(),
79        };
80
81        Some(Ok(RuntimeQueryResult {
82            query: query.to_string(),
83            mode: crate::storage::query::modes::QueryMode::Sql,
84            statement: "select",
85            engine: "fast-entity-lookup",
86            result: crate::storage::query::unified::UnifiedResult {
87                columns: Vec::new(),
88                records,
89                stats: crate::storage::query::unified::QueryStats {
90                    rows_scanned: count,
91                    ..Default::default()
92                },
93                pre_serialized_json: Some(json),
94            },
95            affected_rows: 0,
96            statement_type: "select",
97            bookmark: None,
98        }))
99    }
100
101    pub(crate) fn invalidate_plan_cache(&self) {
102        self.inner.query_cache.write().clear();
103        self.inner
104            .ddl_epoch
105            .fetch_add(1, std::sync::atomic::Ordering::Release);
106    }
107
108    /// Read the monotonic DDL epoch counter. Bumped by every
109    /// `invalidate_plan_cache` call so prepared-statement holders can
110    /// detect schema drift between PREPARE and EXECUTE.
111    pub fn ddl_epoch(&self) -> u64 {
112        self.inner
113            .ddl_epoch
114            .load(std::sync::atomic::Ordering::Acquire)
115    }
116
117    pub(crate) fn clear_table_planner_stats(&self, table: &str) {
118        let store = self.inner.db.store();
119        crate::storage::query::planner::stats_catalog::clear_table_stats(store.as_ref(), table);
120        self.invalidate_plan_cache();
121    }
122}