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        // Budgeted reads use the normal typed execution path and checkpoints.
17        if self.resource_limits().read_execution_limits_enabled() {
18            return None;
19        }
20        // Pattern: "SELECT * FROM <table> WHERE _entity_id = <id>"
21        // or "SELECT * FROM <table> WHERE _entity_id =<id>"
22        let q = query.trim();
23        if !q.starts_with("SELECT") && !q.starts_with("select") {
24            return None;
25        }
26
27        // Find "WHERE _entity_id = " or "WHERE _entity_id ="
28        let where_pos = q
29            .find("WHERE _entity_id")
30            .or_else(|| q.find("where _entity_id"))?;
31        let after_field = &q[where_pos + 16..].trim_start(); // skip "WHERE _entity_id"
32        let after_eq = after_field.strip_prefix('=')?.trim_start();
33
34        // Parse the entity ID number
35        let id_str = after_eq.trim();
36        let entity_id: u64 = id_str.parse().ok()?;
37
38        // Extract table name: between "FROM " and " WHERE"
39        let from_pos = q.find("FROM ").or_else(|| q.find("from "))? + 5;
40        let table = q[from_pos..where_pos].trim();
41        if table.is_empty()
42            || table.contains(' ') && !table.contains(" AS ") && !table.contains(" as ")
43        {
44            return None; // complex query, fall through
45        }
46        let table_name = table.split_whitespace().next()?;
47
48        // Direct entity lookup — skips SQL parse, plan cache, result
49        // cache, view rewriter, RLS gate. Safe because the gating in
50        // `execute_query` guarantees no scope override / no
51        // transaction context is active. MVCC visibility is still
52        // honoured against the current snapshot.
53        let store = self.inner.db.store();
54        let entity = store
55            .get(
56                table_name,
57                crate::storage::unified::EntityId::new(entity_id),
58            )
59            .filter(entity_visible_under_current_snapshot)
60            .filter(|entity| self.inner.db.entity_visible_at_read(table_name, entity));
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: reddb_rql::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            notice: None,
99        }))
100    }
101
102    pub(crate) fn invalidate_plan_cache(&self) {
103        self.inner.query_cache.write().clear();
104        self.inner
105            .ddl_epoch
106            .fetch_add(1, std::sync::atomic::Ordering::Release);
107    }
108
109    /// Read the monotonic DDL epoch counter. Bumped by every
110    /// `invalidate_plan_cache` call so prepared-statement holders can
111    /// detect schema drift between PREPARE and EXECUTE.
112    pub fn ddl_epoch(&self) -> u64 {
113        self.inner
114            .ddl_epoch
115            .load(std::sync::atomic::Ordering::Acquire)
116    }
117
118    pub(crate) fn clear_table_planner_stats(&self, table: &str) {
119        let store = self.inner.db.store();
120        crate::storage::query::planner::stats_catalog::clear_table_stats(store.as_ref(), table);
121        self.invalidate_plan_cache();
122    }
123}