1mod query;
7#[cfg(feature = "sql")]
8mod sql;
9#[cfg(all(test, feature = "sql"))]
13mod tests;
14mod write;
15
16use crate::{
17 db::{
18 Db, EntityFieldDescription, EntitySchemaDescription, FluentDeleteQuery, FluentLoadQuery,
19 IndexState, IntegrityReport, MigrationPlan, MigrationRunOutcome, MissingRowPolicy,
20 PersistedRow, Query, QueryError, StorageReport, StoreRegistry, WriteBatchResponse,
21 commit::EntityRuntimeHooks,
22 data::DataKey,
23 executor::{DeleteExecutor, LoadExecutor, SaveExecutor},
24 query::plan::VisibleIndexes,
25 schema::{
26 describe_entity_model, show_indexes_for_model,
27 show_indexes_for_model_with_runtime_state,
28 },
29 },
30 error::InternalError,
31 metrics::sink::{MetricsSink, with_metrics_sink},
32 model::entity::EntityModel,
33 traits::{CanisterKind, EntityKind, EntityValue, Path},
34 value::Value,
35};
36use std::thread::LocalKey;
37
38#[cfg(feature = "perf-attribution")]
39pub use query::QueryExecutionAttribution;
40#[cfg(all(feature = "sql", feature = "perf-attribution"))]
41pub use sql::SqlQueryExecutionAttribution;
42#[cfg(feature = "sql")]
43pub use sql::SqlStatementResult;
44#[cfg(all(feature = "sql", feature = "structural-read-metrics"))]
45pub use sql::{SqlProjectionMaterializationMetrics, with_sql_projection_materialization_metrics};
46
47pub struct DbSession<C: CanisterKind> {
54 db: Db<C>,
55 debug: bool,
56 metrics: Option<&'static dyn MetricsSink>,
57}
58
59impl<C: CanisterKind> DbSession<C> {
60 #[must_use]
62 pub(crate) const fn new(db: Db<C>) -> Self {
63 Self {
64 db,
65 debug: false,
66 metrics: None,
67 }
68 }
69
70 #[must_use]
72 pub const fn new_with_hooks(
73 store: &'static LocalKey<StoreRegistry>,
74 entity_runtime_hooks: &'static [EntityRuntimeHooks<C>],
75 ) -> Self {
76 Self::new(Db::new_with_hooks(store, entity_runtime_hooks))
77 }
78
79 #[must_use]
81 pub const fn debug(mut self) -> Self {
82 self.debug = true;
83 self
84 }
85
86 #[must_use]
88 pub const fn metrics_sink(mut self, sink: &'static dyn MetricsSink) -> Self {
89 self.metrics = Some(sink);
90 self
91 }
92
93 fn with_metrics<T>(&self, f: impl FnOnce() -> T) -> T {
94 if let Some(sink) = self.metrics {
95 with_metrics_sink(sink, f)
96 } else {
97 f()
98 }
99 }
100
101 fn execute_save_with<E, T, R>(
103 &self,
104 op: impl FnOnce(SaveExecutor<E>) -> Result<T, InternalError>,
105 map: impl FnOnce(T) -> R,
106 ) -> Result<R, InternalError>
107 where
108 E: PersistedRow<Canister = C> + EntityValue,
109 {
110 let value = self.with_metrics(|| op(self.save_executor::<E>()))?;
111
112 Ok(map(value))
113 }
114
115 fn execute_save_entity<E>(
117 &self,
118 op: impl FnOnce(SaveExecutor<E>) -> Result<E, InternalError>,
119 ) -> Result<E, InternalError>
120 where
121 E: PersistedRow<Canister = C> + EntityValue,
122 {
123 self.execute_save_with(op, std::convert::identity)
124 }
125
126 fn execute_save_batch<E>(
127 &self,
128 op: impl FnOnce(SaveExecutor<E>) -> Result<Vec<E>, InternalError>,
129 ) -> Result<WriteBatchResponse<E>, InternalError>
130 where
131 E: PersistedRow<Canister = C> + EntityValue,
132 {
133 self.execute_save_with(op, WriteBatchResponse::new)
134 }
135
136 #[must_use]
142 pub const fn load<E>(&self) -> FluentLoadQuery<'_, E>
143 where
144 E: EntityKind<Canister = C>,
145 {
146 FluentLoadQuery::new(self, Query::new(MissingRowPolicy::Ignore))
147 }
148
149 #[must_use]
151 pub const fn load_with_consistency<E>(
152 &self,
153 consistency: MissingRowPolicy,
154 ) -> FluentLoadQuery<'_, E>
155 where
156 E: EntityKind<Canister = C>,
157 {
158 FluentLoadQuery::new(self, Query::new(consistency))
159 }
160
161 #[must_use]
163 pub fn delete<E>(&self) -> FluentDeleteQuery<'_, E>
164 where
165 E: PersistedRow<Canister = C>,
166 {
167 FluentDeleteQuery::new(self, Query::new(MissingRowPolicy::Ignore).delete())
168 }
169
170 #[must_use]
172 pub fn delete_with_consistency<E>(
173 &self,
174 consistency: MissingRowPolicy,
175 ) -> FluentDeleteQuery<'_, E>
176 where
177 E: PersistedRow<Canister = C>,
178 {
179 FluentDeleteQuery::new(self, Query::new(consistency).delete())
180 }
181
182 #[must_use]
186 pub const fn select_one(&self) -> Value {
187 Value::Int(1)
188 }
189
190 #[must_use]
197 pub fn show_indexes<E>(&self) -> Vec<String>
198 where
199 E: EntityKind<Canister = C>,
200 {
201 self.show_indexes_for_store_model(E::Store::PATH, E::MODEL)
202 }
203
204 #[must_use]
210 pub fn show_indexes_for_model(&self, model: &'static EntityModel) -> Vec<String> {
211 show_indexes_for_model(model)
212 }
213
214 pub(in crate::db) fn show_indexes_for_store_model(
218 &self,
219 store_path: &str,
220 model: &'static EntityModel,
221 ) -> Vec<String> {
222 let runtime_state = self.try_index_state_for_store_path(store_path);
223
224 show_indexes_for_model_with_runtime_state(model, runtime_state)
225 }
226
227 #[must_use]
229 pub fn show_columns<E>(&self) -> Vec<EntityFieldDescription>
230 where
231 E: EntityKind<Canister = C>,
232 {
233 self.show_columns_for_model(E::MODEL)
234 }
235
236 #[must_use]
238 pub fn show_columns_for_model(
239 &self,
240 model: &'static EntityModel,
241 ) -> Vec<EntityFieldDescription> {
242 describe_entity_model(model).fields().to_vec()
243 }
244
245 #[must_use]
247 pub fn show_entities(&self) -> Vec<String> {
248 self.db.runtime_entity_names()
249 }
250
251 #[must_use]
256 pub fn show_tables(&self) -> Vec<String> {
257 self.show_entities()
258 }
259
260 fn try_index_state_for_store_path(&self, store_path: &str) -> Option<IndexState> {
265 self.db
266 .with_store_registry(|registry| registry.try_get_store(store_path).ok())
267 .map(|store| store.index_state())
268 }
269
270 fn visible_indexes_for_store_model(
273 &self,
274 store_path: &str,
275 model: &'static EntityModel,
276 ) -> Result<VisibleIndexes<'static>, QueryError> {
277 let store = self
280 .db
281 .recovered_store(store_path)
282 .map_err(QueryError::execute)?;
283 let state = store.index_state();
284 if state != IndexState::Ready {
285 return Ok(VisibleIndexes::none());
286 }
287 debug_assert_eq!(state, IndexState::Ready);
288
289 Ok(VisibleIndexes::planner_visible(model.indexes()))
292 }
293
294 #[must_use]
299 pub fn describe_entity<E>(&self) -> EntitySchemaDescription
300 where
301 E: EntityKind<Canister = C>,
302 {
303 self.describe_entity_model(E::MODEL)
304 }
305
306 #[must_use]
308 pub fn describe_entity_model(&self, model: &'static EntityModel) -> EntitySchemaDescription {
309 describe_entity_model(model)
310 }
311
312 pub fn storage_report(
314 &self,
315 name_to_path: &[(&'static str, &'static str)],
316 ) -> Result<StorageReport, InternalError> {
317 self.db.storage_report(name_to_path)
318 }
319
320 pub fn storage_report_default(&self) -> Result<StorageReport, InternalError> {
322 self.db.storage_report_default()
323 }
324
325 pub fn integrity_report(&self) -> Result<IntegrityReport, InternalError> {
327 self.db.integrity_report()
328 }
329
330 pub fn execute_migration_plan(
335 &self,
336 plan: &MigrationPlan,
337 max_steps: usize,
338 ) -> Result<MigrationRunOutcome, InternalError> {
339 self.with_metrics(|| self.db.execute_migration_plan(plan, max_steps))
340 }
341
342 #[must_use]
347 pub(in crate::db) const fn load_executor<E>(&self) -> LoadExecutor<E>
348 where
349 E: EntityKind<Canister = C> + EntityValue,
350 {
351 LoadExecutor::new(self.db, self.debug)
352 }
353
354 #[must_use]
355 pub(in crate::db) const fn delete_executor<E>(&self) -> DeleteExecutor<E>
356 where
357 E: PersistedRow<Canister = C> + EntityValue,
358 {
359 DeleteExecutor::new(self.db)
360 }
361
362 #[must_use]
363 pub(in crate::db) const fn save_executor<E>(&self) -> SaveExecutor<E>
364 where
365 E: PersistedRow<Canister = C> + EntityValue,
366 {
367 SaveExecutor::new(self.db, self.debug)
368 }
369}
370
371#[doc(hidden)]
376pub fn debug_remove_entity_row_data_only<C, E>(
377 session: &DbSession<C>,
378 key: &E::Key,
379) -> Result<bool, InternalError>
380where
381 C: CanisterKind,
382 E: PersistedRow<Canister = C> + EntityValue,
383{
384 let store = session.db.recovered_store(E::Store::PATH)?;
387
388 let data_key = DataKey::try_from_field_value(E::ENTITY_TAG, key)?;
391 let raw_key = data_key.to_raw()?;
392 let storage_key = data_key.storage_key();
393
394 let removed = store.with_data_mut(|data| data.remove(&raw_key).is_some());
398 if !removed {
399 return Ok(false);
400 }
401
402 store.with_index_mut(|index| index.mark_memberships_missing_for_storage_key(storage_key))?;
403
404 Ok(true)
405}
406
407#[doc(hidden)]
413pub fn debug_mark_store_index_state<C>(
414 session: &DbSession<C>,
415 store_path: &str,
416 state: IndexState,
417) -> Result<(), InternalError>
418where
419 C: CanisterKind,
420{
421 let store = session.db.recovered_store(store_path)?;
424
425 match state {
428 IndexState::Building => store.mark_index_building(),
429 IndexState::Ready => store.mark_index_ready(),
430 IndexState::Dropping => store.mark_index_dropping(),
431 }
432
433 Ok(())
434}