Skip to main content

icydb_core/db/session/
mod.rs

1//! Module: session
2//! Responsibility: user-facing query/write execution facade over db executors.
3//! Does not own: planning semantics, cursor validation rules, or storage mutation protocol.
4//! Boundary: converts fluent/query intent calls into executor operations and response DTOs.
5
6mod accepted_schema;
7mod bounded_cache;
8mod catalog;
9mod integrity;
10mod mutation_job;
11mod query;
12mod read_set;
13mod request;
14mod response;
15mod resumable_job;
16#[cfg(feature = "sql")]
17mod sql;
18mod write;
19
20#[cfg(all(test, feature = "sql", feature = "diagnostics"))]
21mod tests;
22
23use crate::metrics::sink::with_metrics_sink;
24use crate::{
25    db::{Db, StoreRegistry},
26    metrics::sink::MetricsSink,
27    traits::CanisterKind,
28};
29use std::thread::LocalKey;
30
31pub(in crate::db) use accepted_schema::AcceptedSchemaCatalogContext;
32#[cfg(all(test, feature = "sql", feature = "diagnostics"))]
33pub(in crate::db) use accepted_schema::{
34    AcceptedSchemaRuntimeBuildCounts, accepted_schema_runtime_build_counts_for_tests,
35    reset_accepted_schema_runtime_build_counts_for_tests,
36};
37#[cfg(all(feature = "sql", feature = "diagnostics"))]
38pub use query::{
39    DirectDataRowAttribution, GroupedCountAttribution, GroupedExecutionAttribution,
40    KernelRowAttribution, ScalarAggregateAttribution,
41};
42#[doc(hidden)]
43pub use query::{
44    MAX_TYPED_EXACT_KEY_BATCH_INPUT_BYTES, MAX_TYPED_EXACT_KEY_BATCH_ITEMS,
45    MAX_TYPED_EXACT_KEY_BATCH_RESULT_BYTES, MAX_TYPED_EXACT_KEY_BATCH_STORED_BYTES,
46};
47pub use request::RequestExecutionRoot;
48pub(in crate::db) use request::RequestExecutionScope;
49pub(in crate::db) use response::finalize_structural_grouped_projection_result;
50pub(in crate::db) use response::grouped_cursor_from_bytes;
51#[cfg(all(feature = "sql", feature = "diagnostics"))]
52pub use sql::{
53    SqlCompileAttribution, SqlDistinctProjectionAttribution, SqlExecutionAttribution,
54    SqlHybridCoveringAttribution, SqlOutputBlobAttribution, SqlPureCoveringAttribution,
55    SqlQueryCacheAttribution, SqlQueryExecutionAttribution,
56};
57#[cfg(feature = "sql")]
58pub use sql::{
59    SqlConstraintValidationPage, SqlConstraintValidationRevisionStatus,
60    SqlConstraintValidationState, SqlDdlExecutionStatus, SqlDdlMutationKind,
61    SqlDdlPreparationReport, SqlIntegrityError, SqlStatementDispatch, SqlStatementResult,
62    SqlStatementShellSurface, SqlStatementSurface, sql_statement_dispatch,
63    sql_statement_entity_name, sql_statement_shell_surface, sql_statement_surface,
64};
65#[cfg(feature = "sql")]
66pub(in crate::db::session) use write::{
67    AcceptedStructuralMutation, AcceptedStructuralMutationTarget,
68    structural_data_key_from_runtime_values,
69};
70
71///
72/// DbSession
73///
74/// Session-scoped database handle with policy (debug, metrics) and execution routing.
75///
76
77pub struct DbSession<C: CanisterKind> {
78    db: Db<C>,
79    debug: bool,
80    metrics: Option<&'static dyn MetricsSink>,
81}
82
83impl<C: CanisterKind> DbSession<C> {
84    /// Construct one session facade over a sealed runtime store registry.
85    #[must_use]
86    pub fn new(
87        store: &'static LocalKey<StoreRegistry>,
88        request_root: &RequestExecutionRoot,
89    ) -> Self {
90        Self {
91            db: Db::new(store, request_root.scope()),
92            debug: false,
93            metrics: None,
94        }
95    }
96
97    /// Advance generated startup recovery without admitting ordinary database work.
98    #[doc(hidden)]
99    pub fn __continue_startup_recovery(&self) -> Result<bool, crate::error::InternalError> {
100        self.db.continue_startup_recovery()
101    }
102
103    /// Construct a session from the active synchronous request scope.
104    ///
105    /// Generated zero-argument `db!()` wiring uses this entry. `None` means
106    /// that the caller did not establish a request execution boundary.
107    #[doc(hidden)]
108    #[must_use]
109    pub fn __new_from_current_request(store: &'static LocalKey<StoreRegistry>) -> Option<Self> {
110        request::current_request_scope().map(|scope| Self {
111            db: Db::new(store, scope),
112            debug: false,
113            metrics: None,
114        })
115    }
116
117    /// Enable bounded request-wide query diagnostics without resetting prior counters.
118    ///
119    /// Returns `true` only when this call enabled collection. Every session
120    /// derived from the same request root observes the same diagnostic state.
121    #[cfg(feature = "diagnostics")]
122    #[must_use]
123    pub fn enable_request_diagnostics(&self) -> bool {
124        self.db.request_execution_scope().enable_diagnostics()
125    }
126
127    /// Snapshot bounded request-wide query diagnostics when collection is enabled.
128    #[cfg(feature = "diagnostics")]
129    #[must_use]
130    pub fn request_diagnostics(&self) -> Option<crate::db::RequestDiagnostics> {
131        self.db.request_execution_scope().diagnostics_snapshot()
132    }
133
134    /// Enable debug execution behavior where supported by executors.
135    #[must_use]
136    pub const fn debug(mut self) -> Self {
137        self.debug = true;
138        self
139    }
140
141    /// Attach one metrics sink for all session-executed operations.
142    #[must_use]
143    pub const fn metrics_sink(mut self, sink: &'static dyn MetricsSink) -> Self {
144        self.metrics = Some(sink);
145        self
146    }
147
148    fn with_metrics<T>(&self, f: impl FnOnce() -> T) -> T {
149        if let Some(sink) = self.metrics {
150            with_metrics_sink(sink, f)
151        } else {
152            f()
153        }
154    }
155}