Skip to main content

lora_database/database/
execute.rs

1//! Query-execute family on [`Database<S>`].
2//!
3//! These methods cover the `execute_*` and `execute_rows_*` entry points
4//! plus the cooperative-deadline variants and the plan-cache-backed
5//! compile path. The actual write routing (optimistic OCC vs. pessimistic
6//! `with_logged_write_guard`) is dispatched from
7//! [`Database::execute_rows_with_params_deadline`]; the OCC body lives
8//! in [`super::occ`] and the WAL-bracketed write closure lives in
9//! [`super::write_guard`].
10
11use std::any::Any;
12use std::collections::BTreeMap;
13use std::time::Duration;
14
15use web_time::Instant;
16
17use anyhow::Result;
18use lora_ast::Statement;
19use lora_executor::{
20    classify_stream, collect_compiled, project_rows, ExecuteOptions, LoraValue,
21    MutableExecutionContext, MutableExecutor, QueryResult, Row, StreamShape,
22};
23use lora_parser::parse_query;
24use lora_store::{GraphStorage, GraphStorageMut, InMemoryGraph};
25
26use crate::database::{Database, QUERY_FAILURE_POISON};
27use crate::error::LoraError;
28use crate::wal::write_scope::{ensure_wal_query_can_start, WalAbortPolicy};
29
30use super::pull_mode::should_collect_read_via_pull;
31
32impl<S> Database<S>
33where
34    S: GraphStorage + GraphStorageMut + Any + Clone + Send + Sync + 'static,
35{
36    /// Execute a query and return its result.
37    pub fn execute(
38        &self,
39        query: &str,
40        options: Option<ExecuteOptions>,
41    ) -> Result<QueryResult, LoraError> {
42        self.execute_with_params(query, options, BTreeMap::new())
43    }
44
45    /// Execute a query with a cooperative deadline. The timeout is checked at
46    /// executor operator boundaries and hot scan loops; if it fires, the query
47    /// returns an error and any WAL-backed mutating query is aborted through
48    /// the existing failure path.
49    pub fn execute_with_timeout(
50        &self,
51        query: &str,
52        options: Option<ExecuteOptions>,
53        timeout: Duration,
54    ) -> Result<QueryResult, LoraError> {
55        let deadline = Instant::now()
56            .checked_add(timeout)
57            .unwrap_or_else(Instant::now);
58        let rows =
59            self.execute_rows_with_params_deadline(query, BTreeMap::new(), Some(deadline))?;
60        Ok(project_rows(rows, options.unwrap_or_default()))
61    }
62
63    /// Execute a query with bound parameters.
64    ///
65    /// When a WAL is attached the call is bracketed by a transaction:
66    ///
67    /// 1. `recorder.arm()` after analyze + compile (so a parse /
68    ///    semantic / compile error never opens a tx that has to be
69    ///    immediately aborted). Arming is *cheap*: no record is
70    ///    appended to the WAL yet, so a pure read query that
71    ///    completes here pays nothing for the WAL hot path.
72    /// 2. The executor runs; every primitive mutation fires
73    ///    `MutationRecorder::record`, which buffers events in memory.
74    /// 3. On Ok, `recorder.commit()` writes `TxBegin`, one batched
75    ///    mutation record, and `TxCommit` only when mutations occurred,
76    ///    then applies the WAL's configured single-thread flush policy.
77    /// 4. On Err, `recorder.abort()` clears the pending batch. The
78    ///    engine has no rollback, so the in-memory state may already
79    ///    be partially mutated; the live handle is quarantined while
80    ///    durable recovery stays atomic because no committed batch was
81    ///    written.
82    /// 5. The recorder's poisoned flag is polled once. If set, the query
83    ///    fails loudly with the durability error so the caller can act on it;
84    ///    the WAL refuses further appends until the operator restarts the
85    ///    database, which recovers from the last consistent snapshot + WAL.
86    pub fn execute_with_params(
87        &self,
88        query: &str,
89        options: Option<ExecuteOptions>,
90        params: BTreeMap<String, LoraValue>,
91    ) -> Result<QueryResult, LoraError> {
92        let rows = self.execute_rows_with_params_deadline(query, params, None)?;
93        Ok(project_rows(rows, options.unwrap_or_default()))
94    }
95
96    /// Execute a parameterised query with a cooperative deadline.
97    pub fn execute_with_params_timeout(
98        &self,
99        query: &str,
100        options: Option<ExecuteOptions>,
101        params: BTreeMap<String, LoraValue>,
102        timeout: Duration,
103    ) -> Result<QueryResult, LoraError> {
104        let deadline = Instant::now()
105            .checked_add(timeout)
106            .unwrap_or_else(Instant::now);
107        let rows = self.execute_rows_with_params_deadline(query, params, Some(deadline))?;
108        Ok(project_rows(rows, options.unwrap_or_default()))
109    }
110
111    /// Execute a query and return hydrated rows before final result-format
112    /// projection.
113    pub fn execute_rows(&self, query: &str) -> Result<Vec<Row>, LoraError> {
114        self.execute_rows_with_params(query, BTreeMap::new())
115    }
116
117    /// Execute a query with parameters and return hydrated rows before final
118    /// result-format projection.
119    pub fn execute_rows_with_params(
120        &self,
121        query: &str,
122        params: BTreeMap<String, LoraValue>,
123    ) -> Result<Vec<Row>, LoraError> {
124        Ok(self.execute_rows_with_params_deadline(query, params, None)?)
125    }
126
127    pub(crate) fn execute_rows_with_params_deadline(
128        &self,
129        query: &str,
130        params: BTreeMap<String, LoraValue>,
131        deadline: Option<Instant>,
132    ) -> Result<Vec<Row>> {
133        // Schema commands (CREATE INDEX, SHOW INDEXES) are catalog-level
134        // mutations and don't share the row-producing pipeline. A cheap
135        // textual prefix check routes them out before the parser cache and
136        // analyzer get involved.
137        if Self::is_schema_command_text(query) {
138            let document = parse_query(query)?;
139            if let Statement::Schema(cmd) = &document.statement {
140                return self.execute_schema_command(cmd, params, deadline);
141            }
142            // Fall through if the prefix matched but the parser disagreed —
143            // shouldn't happen given the grammar, but the regular path
144            // below will surface a parse error coherently.
145        }
146
147        // Procedure calls we route ourselves (vector kNN today; full-text
148        // queries land here too once they ship). These bypass the
149        // analyzer/compiler, which doesn't yet model standalone CALL.
150        if super::procedures::is_procedure_call_text(query) {
151            let document = parse_query(query)?;
152            if let lora_ast::Statement::Query(lora_ast::Query::StandaloneCall(call)) =
153                &document.statement
154            {
155                return self.execute_procedure_call(call, params);
156            }
157        }
158
159        // Compile (or fetch from the plan cache) under the read lock. The
160        // read lock is also what the read-only fast path runs under, so we
161        // can reuse it without a release/reacquire when the plan turns out
162        // to be a pure read.
163        let (store, store_epoch) = self.read_store_with_epoch_deadline(deadline)?;
164        let compiled = self.compile_query_cached(query, &*store, store_epoch)?;
165        let shape = classify_stream(&compiled);
166
167        if matches!(shape, StreamShape::ReadOnly) {
168            if let Some(rec) = &self.wal {
169                ensure_wal_query_can_start(rec)?;
170            }
171            if deadline.is_none() && should_collect_read_via_pull(&compiled) {
172                return collect_compiled(&*store, params, &compiled).map_err(anyhow::Error::from);
173            }
174            let executor = lora_executor::Executor::with_deadline(
175                lora_executor::ExecutionContext {
176                    storage: &*store,
177                    params,
178                },
179                deadline,
180            );
181            return executor
182                .execute_compiled_rows_parallel_safe(&compiled)
183                .map_err(anyhow::Error::from);
184        }
185
186        // Mutating path. Drop the snapshot used for compilation and route
187        // through the single-writer auto-commit path. The writer mutex is held
188        // for mutate + WAL commit so live state and WAL order stay identical.
189        // The method name still says "optimistic" because this is the seam a
190        // future write-set/CAS implementation can reuse.
191        drop(store);
192        debug_assert!(shape.is_mutating());
193
194        if std::any::TypeId::of::<S>() == std::any::TypeId::of::<InMemoryGraph>() {
195            return self.execute_mutating_optimistic(params, deadline, &compiled);
196        }
197
198        // Backends that aren't `InMemoryGraph` don't support the
199        // recorder install hook, so fall back to the pessimistic path.
200        let store = self.write_store_deadline(deadline)?;
201        self.with_logged_write_guard(
202            store,
203            WalAbortPolicy::PoisonIfMutated(QUERY_FAILURE_POISON),
204            |store| {
205                let mut executor = MutableExecutor::with_deadline(
206                    MutableExecutionContext {
207                        storage: store,
208                        params,
209                    },
210                    deadline,
211                );
212                Ok(executor.execute_compiled_rows(&compiled)?)
213            },
214        )
215    }
216}