1use crate::{
2 Error, Key,
3 db::{
4 Db,
5 executor::{
6 FilterEvaluator,
7 plan::{plan_for, set_rows_from_len},
8 },
9 primitives::{FilterDsl, FilterExpr, FilterExt, IntoFilterExpr, Order, SortExpr},
10 query::{LoadQuery, QueryPlan, QueryValidate},
11 response::Response,
12 store::DataRow,
13 },
14 obs::metrics,
15 traits::{EntityKind, FieldValue},
16};
17use std::{cmp::Ordering, marker::PhantomData};
18
19#[derive(Clone, Copy)]
24pub struct LoadExecutor<E: EntityKind> {
25 db: Db<E::Canister>,
26 debug: bool,
27 _marker: PhantomData<E>,
28}
29
30impl<E: EntityKind> LoadExecutor<E> {
31 #[must_use]
36 pub const fn new(db: Db<E::Canister>, debug: bool) -> Self {
37 Self {
38 db,
39 debug,
40 _marker: PhantomData,
41 }
42 }
43
44 fn debug_log(&self, s: impl Into<String>) {
45 if self.debug {
46 println!("{}", s.into());
47 }
48 }
49
50 pub fn one(&self, value: impl FieldValue) -> Result<Response<E>, Error> {
56 self.execute(LoadQuery::new().one::<E>(value))
57 }
58
59 pub fn only(&self) -> Result<Response<E>, Error> {
61 self.execute(LoadQuery::new().one::<E>(()))
62 }
63
64 pub fn many(
66 &self,
67 values: impl IntoIterator<Item = impl FieldValue>,
68 ) -> Result<Response<E>, Error> {
69 self.execute(LoadQuery::new().many::<E>(values))
70 }
71
72 pub fn all(&self) -> Result<Response<E>, Error> {
74 self.execute(LoadQuery::new())
75 }
76
77 pub fn filter<F, I>(&self, f: F) -> Result<Response<E>, Error>
79 where
80 F: FnOnce(FilterDsl) -> I,
81 I: IntoFilterExpr,
82 {
83 self.execute(LoadQuery::new().filter(f))
84 }
85
86 pub fn require_one(&self, query: LoadQuery) -> Result<(), Error> {
92 self.execute(query)?.require_one()
93 }
94
95 pub fn require_one_pk(&self, value: impl FieldValue) -> Result<(), Error> {
97 self.require_one(LoadQuery::new().one::<E>(value))
98 }
99
100 pub fn require_one_filter<F, I>(&self, f: F) -> Result<(), Error>
102 where
103 F: FnOnce(FilterDsl) -> I,
104 I: IntoFilterExpr,
105 {
106 self.require_one(LoadQuery::new().filter(f))
107 }
108
109 pub fn exists(&self, query: LoadQuery) -> Result<bool, Error> {
115 let query = query.limit_1();
116 Ok(!self.execute_raw(&query)?.is_empty())
117 }
118
119 pub fn exists_one(&self, value: impl FieldValue) -> Result<bool, Error> {
121 self.exists(LoadQuery::new().one::<E>(value))
122 }
123
124 pub fn exists_filter<F, I>(&self, f: F) -> Result<bool, Error>
126 where
127 F: FnOnce(FilterDsl) -> I,
128 I: IntoFilterExpr,
129 {
130 self.exists(LoadQuery::new().filter(f))
131 }
132
133 pub fn exists_any(&self) -> Result<bool, Error> {
135 self.exists(LoadQuery::new())
136 }
137
138 pub fn explain(self, query: LoadQuery) -> Result<QueryPlan, Error> {
144 QueryValidate::<E>::validate(&query)?;
145
146 Ok(plan_for::<E>(query.filter.as_ref()))
147 }
148
149 fn execute_raw(&self, query: &LoadQuery) -> Result<Vec<DataRow>, Error> {
150 QueryValidate::<E>::validate(query)?;
151
152 let ctx = self.db.context::<E>();
153 let plan = plan_for::<E>(query.filter.as_ref());
154
155 if let Some(lim) = &query.limit {
156 Ok(ctx.rows_from_plan_with_pagination(plan, lim.offset, lim.limit)?)
157 } else {
158 Ok(ctx.rows_from_plan(plan)?)
159 }
160 }
161
162 pub fn execute(&self, query: LoadQuery) -> Result<Response<E>, Error> {
164 let mut span = metrics::Span::<E>::new(metrics::ExecKind::Load);
165 QueryValidate::<E>::validate(&query)?;
166
167 self.debug_log(format!("🧭 Executing query: {:?} on {}", query, E::PATH));
168
169 let ctx = self.db.context::<E>();
170 let plan = plan_for::<E>(query.filter.as_ref());
171
172 self.debug_log(format!("📄 Query plan: {plan:?}"));
173
174 let pre_paginated = query.filter.is_none() && query.sort.is_none() && query.limit.is_some();
176 let mut rows: Vec<(Key, E)> = if pre_paginated {
177 let data_rows = self.execute_raw(&query)?;
178
179 self.debug_log(format!(
180 "📦 Scanned {} data rows before deserialization",
181 data_rows.len()
182 ));
183
184 let rows = ctx.deserialize_rows(data_rows)?;
185 self.debug_log(format!(
186 "🧩 Deserialized {} entities before filtering",
187 rows.len()
188 ));
189 rows
190 } else {
191 let data_rows = ctx.rows_from_plan(plan)?;
192 self.debug_log(format!(
193 "📦 Scanned {} data rows before deserialization",
194 data_rows.len()
195 ));
196
197 let rows = ctx.deserialize_rows(data_rows)?;
198 self.debug_log(format!(
199 "🧩 Deserialized {} entities before filtering",
200 rows.len()
201 ));
202
203 rows
204 };
205
206 if let Some(f) = &query.filter {
208 let simplified = f.clone().simplify();
209 Self::apply_filter(&mut rows, &simplified);
210
211 self.debug_log(format!(
212 "🔎 Applied filter -> {} entities remaining",
213 rows.len()
214 ));
215 }
216
217 if let Some(sort) = &query.sort
219 && rows.len() > 1
220 {
221 Self::apply_sort(&mut rows, sort);
222 self.debug_log("↕️ Applied sort expression");
223 }
224
225 if let Some(lim) = &query.limit
227 && !pre_paginated
228 {
229 apply_pagination(&mut rows, lim.offset, lim.limit);
230 self.debug_log(format!(
231 "📏 Applied pagination (offset={}, limit={:?}) -> {} entities",
232 lim.offset,
233 lim.limit,
234 rows.len()
235 ));
236 }
237
238 set_rows_from_len(&mut span, rows.len());
239 self.debug_log(format!("✅ Query complete -> {} final rows", rows.len()));
240
241 Ok(Response(rows))
242 }
243
244 pub fn count(&self, query: LoadQuery) -> Result<u32, Error> {
246 Ok(self.execute(query)?.count())
247 }
248
249 pub fn count_all(&self) -> Result<u32, Error> {
250 self.count(LoadQuery::new())
251 }
252
253 fn apply_filter(rows: &mut Vec<(Key, E)>, filter: &FilterExpr) {
255 rows.retain(|(_, e)| FilterEvaluator::new(e).eval(filter));
256 }
257
258 fn apply_sort(rows: &mut [(Key, E)], sort_expr: &SortExpr) {
260 rows.sort_by(|(_, ea), (_, eb)| {
261 for (field, direction) in sort_expr.iter() {
262 let va = ea.get_value(field);
263 let vb = eb.get_value(field);
264
265 let ordering = match (va, vb) {
267 (None, None) => continue, (None, Some(_)) => Ordering::Less, (Some(_), None) => Ordering::Greater, (Some(va), Some(vb)) => match va.partial_cmp(&vb) {
271 Some(ord) => ord,
272 None => continue, },
274 };
275
276 let ordering = match direction {
278 Order::Asc => ordering,
279 Order::Desc => ordering.reverse(),
280 };
281
282 if ordering != Ordering::Equal {
283 return ordering;
284 }
285 }
286
287 Ordering::Equal
289 });
290 }
291}
292
293fn apply_pagination<T>(rows: &mut Vec<T>, offset: u32, limit: Option<u32>) {
295 let total = rows.len();
296 let start = usize::min(offset as usize, total);
297 let end = limit.map_or(total, |l| usize::min(start + l as usize, total));
298
299 if start >= end {
300 rows.clear();
301 } else {
302 rows.drain(..start);
303 rows.truncate(end - start);
304 }
305}
306
307#[cfg(test)]
312mod tests {
313 use super::{LoadExecutor, apply_pagination};
314 use crate::{
315 IndexSpec, Key, Value,
316 db::primitives::{Order, SortExpr},
317 traits::{
318 CanisterKind, EntityKind, FieldValues, Path, SanitizeAuto, SanitizeCustom, StoreKind,
319 ValidateAuto, ValidateCustom, View, Visitable,
320 },
321 };
322 use serde::{Deserialize, Serialize};
323
324 #[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
325 struct SortableEntity {
326 id: u64,
327 primary: i32,
328 secondary: i32,
329 optional_blob: Option<Vec<u8>>,
330 }
331
332 impl SortableEntity {
333 fn new(id: u64, primary: i32, secondary: i32, optional_blob: Option<Vec<u8>>) -> Self {
334 Self {
335 id,
336 primary,
337 secondary,
338 optional_blob,
339 }
340 }
341 }
342
343 struct SortableCanister;
344 struct SortableStore;
345
346 impl Path for SortableCanister {
347 const PATH: &'static str = "test::canister";
348 }
349
350 impl CanisterKind for SortableCanister {}
351
352 impl Path for SortableStore {
353 const PATH: &'static str = "test::store";
354 }
355
356 impl StoreKind for SortableStore {
357 type Canister = SortableCanister;
358 }
359
360 impl Path for SortableEntity {
361 const PATH: &'static str = "test::sortable";
362 }
363
364 impl View for SortableEntity {
365 type ViewType = Self;
366
367 fn to_view(&self) -> Self::ViewType {
368 self.clone()
369 }
370
371 fn from_view(view: Self::ViewType) -> Self {
372 view
373 }
374 }
375
376 impl SanitizeAuto for SortableEntity {}
377 impl SanitizeCustom for SortableEntity {}
378 impl ValidateAuto for SortableEntity {}
379 impl ValidateCustom for SortableEntity {}
380 impl Visitable for SortableEntity {}
381
382 impl FieldValues for SortableEntity {
383 fn get_value(&self, field: &str) -> Option<Value> {
384 match field {
385 "id" => Some(Value::Uint(self.id)),
386 "primary" => Some(Value::Int(i64::from(self.primary))),
387 "secondary" => Some(Value::Int(i64::from(self.secondary))),
388 "optional_blob" => self.optional_blob.clone().map(Value::Blob),
389 _ => None,
390 }
391 }
392 }
393
394 impl EntityKind for SortableEntity {
395 type PrimaryKey = u64;
396 type Store = SortableStore;
397 type Canister = SortableCanister;
398
399 const ENTITY_ID: u64 = 99;
400 const PRIMARY_KEY: &'static str = "id";
401 const FIELDS: &'static [&'static str] = &["id", "primary", "secondary", "optional_blob"];
402 const INDEXES: &'static [&'static IndexSpec] = &[];
403
404 fn key(&self) -> Key {
405 self.id.into()
406 }
407
408 fn primary_key(&self) -> Self::PrimaryKey {
409 self.id
410 }
411 }
412
413 #[test]
414 fn pagination_empty_vec() {
415 let mut v: Vec<i32> = vec![];
416 apply_pagination(&mut v, 0, Some(10));
417 assert!(v.is_empty());
418 }
419
420 #[test]
421 fn pagination_offset_beyond_len_clears() {
422 let mut v = vec![1, 2, 3];
423 apply_pagination(&mut v, 10, Some(5));
424 assert!(v.is_empty());
425 }
426
427 #[test]
428 fn pagination_no_limit_from_offset() {
429 let mut v = vec![1, 2, 3, 4, 5];
430 apply_pagination(&mut v, 2, None);
431 assert_eq!(v, vec![3, 4, 5]);
432 }
433
434 #[test]
435 fn pagination_exact_window() {
436 let mut v = vec![10, 20, 30, 40, 50];
437 apply_pagination(&mut v, 1, Some(3));
439 assert_eq!(v, vec![20, 30, 40]);
440 }
441
442 #[test]
443 fn pagination_limit_exceeds_tail() {
444 let mut v = vec![10, 20, 30];
445 apply_pagination(&mut v, 1, Some(999));
447 assert_eq!(v, vec![20, 30]);
448 }
449
450 #[test]
451 fn apply_sort_orders_descending() {
452 let mut rows = vec![
453 (Key::from(1_u64), SortableEntity::new(1, 10, 1, None)),
454 (Key::from(2_u64), SortableEntity::new(2, 30, 2, None)),
455 (Key::from(3_u64), SortableEntity::new(3, 20, 3, None)),
456 ];
457 let sort_expr = SortExpr::from(vec![("primary".to_string(), Order::Desc)]);
458
459 LoadExecutor::<SortableEntity>::apply_sort(rows.as_mut_slice(), &sort_expr);
460
461 let primary: Vec<i32> = rows.iter().map(|(_, e)| e.primary).collect();
462 assert_eq!(primary, vec![30, 20, 10]);
463 }
464
465 #[test]
466 fn apply_sort_uses_secondary_field_for_ties() {
467 let mut rows = vec![
468 (Key::from(1_u64), SortableEntity::new(1, 1, 5, None)),
469 (Key::from(2_u64), SortableEntity::new(2, 1, 8, None)),
470 (Key::from(3_u64), SortableEntity::new(3, 2, 3, None)),
471 ];
472 let sort_expr = SortExpr::from(vec![
473 ("primary".to_string(), Order::Asc),
474 ("secondary".to_string(), Order::Desc),
475 ]);
476
477 LoadExecutor::<SortableEntity>::apply_sort(rows.as_mut_slice(), &sort_expr);
478
479 let ids: Vec<u64> = rows.iter().map(|(_, e)| e.id).collect();
480 assert_eq!(ids, vec![2, 1, 3]);
481 }
482
483 #[test]
484 fn apply_sort_places_none_before_some_and_falls_back() {
485 let mut rows = vec![
486 (
487 Key::from(3_u64),
488 SortableEntity::new(3, 0, 0, Some(vec![3, 4])),
489 ),
490 (Key::from(1_u64), SortableEntity::new(1, 0, 0, None)),
491 (
492 Key::from(2_u64),
493 SortableEntity::new(2, 0, 0, Some(vec![2])),
494 ),
495 ];
496 let sort_expr = SortExpr::from(vec![
497 ("optional_blob".to_string(), Order::Asc),
498 ("id".to_string(), Order::Asc),
499 ]);
500
501 LoadExecutor::<SortableEntity>::apply_sort(rows.as_mut_slice(), &sort_expr);
502
503 let ids: Vec<u64> = rows.iter().map(|(_, e)| e.id).collect();
504 assert_eq!(ids, vec![1, 2, 3]);
505 }
506}